From 6578a05ba2becb3feca125b26e7d8b0192c008e3 Mon Sep 17 00:00:00 2001 From: mmjzmy Date: Mon, 16 Nov 2026 19:59:51 +0800 Subject: [PATCH 01/19] feat(ahe-beta): add native simulated-user Codex adapter evolution Add an example-local Codex conversation bridge with mailbox hooks for insertion, follow-up, interruption, adapter Stop hooks, and explicit process shutdown. Connect AHE native direct and simulated sessions to Harbor task rewards while retaining complete session artifacts and separate Actor and user usage. Reuse completed rollouts and bind tested adapter content to delivery commits. Add a constrained Codex adapter template and an Evolver that delegates each whole-cohort feedback round to AHE's native demand and OpenAgents delivery flow. Prepare frozen training configurations with a separate final user-only round. Propagate RunUnavailable through rollouts and training so missing prerequisites leave the step unfinished rather than becoming zero-valued training examples. Include scripted control checks, real-model smoke entry points, regression tests, package data, test-group registration, and source-checkout setup documentation. --- examples/ahe_beta/README.md | 200 ++++++++ examples/ahe_beta/prepare.py | 183 +++++++ examples/ahe_beta/requirements.txt | 5 + examples/ahe_beta/smoke/Dockerfile | 7 + examples/ahe_beta/smoke/native.py | 189 +++++++ examples/ahe_beta/smoke/smoke.py | 277 ++++++++++ examples/ahe_beta/utils/acting.py | 124 +++++ examples/ahe_beta/utils/binding.py | 54 ++ examples/ahe_beta/utils/channel.py | 141 +++++ examples/ahe_beta/utils/hermit_user_codex.py | 485 ++++++++++++++++++ examples/ahe_beta/utils/processes.py | 97 ++++ examples/ahe_beta/utils/scripted_user.py | 61 +++ examples/ahe_beta/utils/tests/test_acting.py | 79 +++ examples/ahe_beta/utils/tests/test_binding.py | 33 ++ examples/ahe_beta/utils/tests/test_channel.py | 76 +++ examples/ahe_beta/utils/user_hook.py | 245 +++++++++ .../ahe_beta/.agents/skills/.gitkeep | 0 .../templates/ahe_beta/.codex/hooks.json | 1 + .../templates/ahe_beta/.hermit/STRUCTURE.md | 9 + .../templates/ahe_beta/.hermit/adapter.yaml | 46 ++ .../templates/ahe_beta/.hermit/check.py | 58 +++ hermit/adapter/templates/ahe_beta/ADAPTER.md | 1 + hermit/adapter/templates/ahe_beta/README.md | 5 + .../templates/ahe_beta/agents/.gitkeep | 0 .../adapter/templates/ahe_beta/exports.yaml | 4 + .../agent/evolver/methods/ahe_beta/evolver.py | 222 ++++++++ .../evolver/methods/ahe_beta/evolver.yaml | 4 + hermit/task.py | 9 + hermit/trainer/rollout.py | 8 +- hermit/trainer/trainer.py | 7 +- pyproject.toml | 3 +- tests/README.md | 2 +- tests/core/test_run_unavailable.py | 59 +++ tests/methods/ahe_beta/test_ahe_beta.py | 76 +++ tests/selection.py | 1 + 35 files changed, 2765 insertions(+), 6 deletions(-) create mode 100644 examples/ahe_beta/README.md create mode 100644 examples/ahe_beta/prepare.py create mode 100644 examples/ahe_beta/requirements.txt create mode 100644 examples/ahe_beta/smoke/Dockerfile create mode 100644 examples/ahe_beta/smoke/native.py create mode 100644 examples/ahe_beta/smoke/smoke.py create mode 100644 examples/ahe_beta/utils/acting.py create mode 100644 examples/ahe_beta/utils/binding.py create mode 100644 examples/ahe_beta/utils/channel.py create mode 100644 examples/ahe_beta/utils/hermit_user_codex.py create mode 100644 examples/ahe_beta/utils/processes.py create mode 100644 examples/ahe_beta/utils/scripted_user.py create mode 100644 examples/ahe_beta/utils/tests/test_acting.py create mode 100644 examples/ahe_beta/utils/tests/test_binding.py create mode 100644 examples/ahe_beta/utils/tests/test_channel.py create mode 100644 examples/ahe_beta/utils/user_hook.py create mode 100644 hermit/adapter/templates/ahe_beta/.agents/skills/.gitkeep create mode 100644 hermit/adapter/templates/ahe_beta/.codex/hooks.json create mode 100644 hermit/adapter/templates/ahe_beta/.hermit/STRUCTURE.md create mode 100644 hermit/adapter/templates/ahe_beta/.hermit/adapter.yaml create mode 100644 hermit/adapter/templates/ahe_beta/.hermit/check.py create mode 100644 hermit/adapter/templates/ahe_beta/ADAPTER.md create mode 100644 hermit/adapter/templates/ahe_beta/README.md create mode 100644 hermit/adapter/templates/ahe_beta/agents/.gitkeep create mode 100644 hermit/adapter/templates/ahe_beta/exports.yaml create mode 100644 hermit/agent/evolver/methods/ahe_beta/evolver.py create mode 100644 hermit/agent/evolver/methods/ahe_beta/evolver.yaml create mode 100644 tests/core/test_run_unavailable.py create mode 100644 tests/methods/ahe_beta/test_ahe_beta.py diff --git a/examples/ahe_beta/README.md b/examples/ahe_beta/README.md new file mode 100644 index 00000000..7c677492 --- /dev/null +++ b/examples/ahe_beta/README.md @@ -0,0 +1,200 @@ +# AHE-Beta adapter evolution with Codex + +This example connects AHE-Beta's native simulated users and demand pipeline to Hermit. +The learned object is a **Codex adapter**: instructions, skills, helper scripts, roles +and hooks. It does not evolve the Codex binary or the AHE controller. This is narrower +than AHE's original experiments, which evolved a complete NexAU Harness. + +The first integration targets **Harbor 0.25.0, Codex 0.164.0 and local Docker**. +Interaction remains in this example; no user-simulation abstract has been added. + +```mermaid +flowchart LR + A[Frozen adapter and cohort] --> B[Harbor: one container per session] + B --> C[Codex and native AHE user] + C --> D[Stop writers and freeze outputs] + D --> E[Native terminal review and Session] + E --> F[Task verifier: experience reward] + F --> G[Complete round of learning material] + G --> H[Native triage / architect / divergent / owner] + H --> I[Gitea and OpenAgents delivery] + I --> J[Check adapter and record new version] + J --> A +``` + +Direct tasks send one instruction and have a terminal reviewer, without a simulated +user steering the Actor. Interactive tasks use the native persona loop, including +live workspace inspection, messages and interruption. Terminal review reads frozen +files. A valid 1–4 experience rating becomes `(rating - 1) / 3`; this is **subjective +experience**, not independent benchmark correctness. A task's verifier publishes +this rating using Harbor's standard reward file. + +## Install + +Use Python 3.12+ and a working Docker daemon. Keep two source checkouts: + +```bash +export HERMIT_ROOT=/path/to/hermit +export AHE_ROOT=/path/to/AHE-Beta +cd "$HERMIT_ROOT" +python3.13 -m venv .venv-ahe +. .venv-ahe/bin/activate +pip install -e '.[test]' -r examples/ahe_beta/requirements.txt +export PYTHONPATH="$AHE_ROOT/backend:$HERMIT_ROOT" +``` + +AHE currently uses a source checkout rather than an installable Python distribution. +Its feedback/delivery subprocess uses AHE's own locked environment: + +```bash +cd "$AHE_ROOT" +uv sync --locked --extra experiments +``` + +Do not put Gitea, delivery or simulated-user credentials into the task image. The +Harbor process receives the native user configuration through `USER_LLM_BASE_URL`, +`USER_LLM_API_KEY` and `USER_LLM_MODEL`; Codex receives only its Actor credentials. +Set `ACTOR_API_KEY` separately. The Actor endpoint must support the Responses API; +a Chat Completions-only endpoint is insufficient. Use `--http-only` below when a +Responses gateway does not support WebSockets. No gateway address is hard-coded. + +## Export a cohort + +Run the exporter in AHE's environment. It verifies downloaded materials against the +existing task hashes and translates the container recipes into Harbor tasks: + +```bash +cd "$AHE_ROOT" +PYTHONPATH=backend uv run --locked --extra experiments \ + python -m ahe_beta.integrations.hermit.export \ + --experiment examples/experiments/u8-mixed-e2b.json \ + --output /path/to/materials/u8-mixed --cache /path/to/material-cache +``` + +Replace the source file with `u8-direct-e2b.json`, `u16-mixed-e2b.json` or +`u32-mixed-e2b.json` for the other assignments. The exporter preserves each cohort's +persona reuse, task rotation, direct/simulated modes, source instructions, image +digests, companion services, declared artifacts and task budgets. Source `e2b` +configuration is recorded as provenance; the resulting tasks run in **local Harbor +Docker**, with separate resources for each session. Exporting is not a claim that +all 32 environments have been executed successfully. + +The generated directory contains: + +- `tasks/`: Harbor task packages, including container recipes and rating verifiers. +- `tasks.jsonl`: one immutable task/persona assignment per logical round and slot. +- `train.txt`: all sessions from R1–R5, in round order. +- `final-round.txt`: R6 only, using the final adapter without another delivery round. +- `cohort.json`: source configuration hash, group size, role counts and model metadata. + +The final split is a **same-cohort observation**, not a held-out benchmark. Independent +benchmarks need a separate configuration and must not enter the feedback pipeline. +`--agent-seconds` is an explicit optional budget override; omitting it keeps each +task's declared budget (for example, KV's 28,800 seconds). + +## Configure delivery and training + +Provision a dedicated Gitea repository containing the files from +`hermit/adapter/templates/ahe_beta/`. Preserve hidden directories. Start the ordinary +OpenAgents worker for that repository using your existing Gitea configuration and +engineering gates. Keep a separate clean clone for this bridge: the OpenAgents +worker must not share that checkout. Repository creation and the OpenAgents worker's +lifecycle remain managed by their existing deployment tools. + +Generate the Hermit configuration: + +```bash +cd "$HERMIT_ROOT" +python examples/ahe_beta/prepare.py \ + --cohort /path/to/materials/u8-mixed \ + --ahe-root "$AHE_ROOT" --ahe-python "$AHE_ROOT/.venv/bin/python" \ + --harbor "$HERMIT_ROOT/.venv-ahe/bin/harbor" \ + --delivery-repo /path/to/clean-adapter-clone \ + --run-id u8-mixed-codex --actor-model YOUR_CODEX_MODEL \ + --actor-url https://your-responses-provider.example/v1 --http-only +``` + +Edit the generated `delivery.json` tracker URL, owner and repository. Its token is +referenced by environment-variable name (`GITEA_TOKEN`); never write it in JSON. +Configure AHE demand model variables and your OpenAgents worker's model separately. +The cohort metadata records the original experiment's models; these do not silently +become a Codex-compatible model configuration. + +The generated `run.yaml` sets `step_size` to the **whole cohort**, `shuffle: false` +and one epoch, so one Hermit step equals one AHE round. User concurrency comes from +the source experiment. Its example run budget is 168 hours and the delivery call +limit is 24 hours; review these explicit limits before a full experiment. + +```bash +python -m hermit check --no-probe --config /path/to/materials/u8-mixed/run.yaml +python -m hermit train --config /path/to/materials/u8-mixed/run.yaml +python -m hermit eval --config /path/to/materials/u8-mixed/run.yaml --adapter final +``` + +Use `check --no-probe` for configuration validation: the general Hermit probe runs +without an adapter and is not a complete AHE training round. Run the real smoke below +before the expensive experiment. + +The Evolver reuses AHE's native feedback pipeline in the AHE Python environment. +Gitea commit identities and Hermit commit identities are kept separate and bound by +adapter content. A mismatching checkout, incomplete cohort or failed delivery stops +the round. Infrastructure failures raise `RunUnavailable`, leaving the Trainer step +unfinished. Completed rollouts and native delivery receipts are retained for resume; +restore the same files/configuration and rerun `train`. An already delivered round +can be reconciled without repeating valid user sessions or duplicating reports. + +## Smoke checks + +Build a small reusable image with Codex already installed, then verify insertion, +follow-up and interruption with a scripted model and user: + +```bash +docker build -t ahe-hermit-smoke:local examples/ahe_beta/smoke +SMOKE_IMAGE=ahe-hermit-smoke:local DOCKER_GATEWAY=host.docker.internal \ + HARBOR_BIN="$HERMIT_ROOT/.venv-ahe/bin/harbor" \ + python examples/ahe_beta/smoke/smoke.py /path/to/new/channel-smoke +``` + +`DOCKER_GATEWAY` must be the host address reachable from Docker. On native Linux, +configure the Docker host-gateway mapping or provide the reachable host IP. +`DEBIAN_MIRROR` is an optional Docker build argument for dependency installation. + +Run a real Codex model with the native user/reviewer: + +```bash +python examples/ahe_beta/smoke/native.py \ + --output /path/to/new/native-smoke --ahe-root "$AHE_ROOT" \ + --harbor "$HERMIT_ROOT/.venv-ahe/bin/harbor" \ + --model YOUR_CODEX_MODEL --base-url https://your-provider.example/v1 \ + --http-only --interaction simulated_user +``` + +Repeat with a different output directory and `--interaction direct`. This creates a +small frozen test-adapter Git repository under the output directory. It does not +commit to either source checkout. Reports preserve Actor usage separately from user +usage, the complete native Session, frozen file bytes, conversation and tool events. + +## Files and boundaries + +| Component | Responsibility | +| --- | --- | +| AHE `integrations/hermit/session.py` | Native user lifecycle and full Session, deferred Issue plans | +| AHE `integrations/hermit/workspace.py` | Host workspace operations, freeze and native artifact collection | +| AHE `integrations/hermit/export.py` | Source task recipes and frozen cohort conversion | +| AHE `integrations/hermit/feedback.py` | Native report publication, demand roles and delivery recovery | +| `utils/hermit_user_codex.py`, `channel.py`, `user_hook.py` | One Codex process, mailbox interaction and Actor shutdown | +| `utils/acting.py`, `binding.py` | Per-task assignment, valid-rollout reuse and code-version binding | +| `hermit/agent/evolver/methods/ahe_beta/` | One full feedback/delivery cycle per training step | +| `hermit/adapter/templates/ahe_beta/` | Declared mutable adapter surface and fixed checker | + +The initial hook/channel design comes from the Hermit authors' reference handoff for +Hermit `e813538`, Harbor 0.25.0 and Codex 0.164.0. This version adds native AHE lifecycle +integration, explicit shutdown, failure propagation and full evidence preservation. +It does not replace the authors' general interaction abstract or add another host. + +Real smoke results cover a small file task in both modes and scripted control-message +races. The exported M02 and KV tasks also passed real Harbor environment startup; +KV finalization and both public and private measurement collection were exercised +without an Actor. This is environment acceptance, not a successful KV solution. +Full U8/U16/U32 training, OpenAgents delivery against a real model, and the remaining +task environments still need end-to-end acceptance before reporting experiments. diff --git a/examples/ahe_beta/prepare.py b/examples/ahe_beta/prepare.py new file mode 100644 index 00000000..11bbf840 --- /dev/null +++ b/examples/ahe_beta/prepare.py @@ -0,0 +1,183 @@ +"""Generate a runnable Hermit configuration for a cohort exported by AHE.""" + +import argparse +import hashlib +import json +import subprocess +from pathlib import Path + +import yaml + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] + + +def prepare( + *, + cohort, + ahe_root, + ahe_python, + harbor, + delivery_repo, + run_id, + actor_model, + actor_url, + http_only=False, +): + cohort = Path(cohort).resolve() + for name in ("delivery.json", "run.yaml"): + if (cohort / name).exists(): + raise FileExistsError(cohort / name) + info = json.loads((cohort / "cohort.json").read_text()) + state = cohort / "delivery-state" + binding = state / "binding.json" + request = { + "ahe_root": str(Path(ahe_root).resolve()), + "ahe_python": str(Path(ahe_python).resolve()), + "root": str(state), + "repo": str(Path(delivery_repo).resolve()), + "binding": str(binding), + "identity": { + "experiment_id": run_id, + "run_id": run_id, + "config_hash": info["source_config_sha256"], + "controller_sha": subprocess.check_output( + ["git", "-C", str(ahe_root), "rev-parse", "HEAD"], text=True + ).strip(), + "plan_hash": hashlib.sha256( + (cohort / "tasks.jsonl").read_bytes() + ).hexdigest(), + }, + "roster": { + **{ + name: info["roles"][name] + for name in ("triager", "architect", "divergent") + }, + "owner": 0 if info["roles"]["owner_mode"] == "mechanical" else 1, + }, + "definitions_root": str(Path(ahe_root).resolve() / "backend/agent_defs"), + "sessions_per_round": info["sessions_per_round"], + "delivery_timeout": 86400, + "tracker": { + "base_url": "http://localhost:3000", + "owner": "REPLACE", + "repo": "REPLACE", + "token_env": "GITEA_TOKEN", + }, + } + config = { + "data": { + "tasks": "tasks.jsonl", + "train": "train.txt", + "test": "final-round.txt", + "step_size": info["sessions_per_round"], + "shuffle": False, + }, + "task_info": "task-info", + "template": str(ROOT / "hermit/adapter/templates/ahe_beta"), + "agent": { + "name": str(HERE / "utils/acting.py") + ":AheHarborAgent", + "concurrency": info["max_parallel_users"], + "params": { + "tasks_dir": str(cohort / "tasks"), + "jobs_dir": str(cohort / "jobs"), + "harbor": str(Path(harbor).resolve()), + "binding": str(binding), + "model": { + "model": actor_model, + "base_url": actor_url, + "api_key_env": "ACTOR_API_KEY", + }, + "codex_login": False, + "codex_version": "0.164.0", + "agent_timeout_sec": None, + "environment": { + "type": "docker", + "delete": True, + "kwargs": {"auto_mounting": True}, + }, + "acting_agent": { + "import_path": "hermit_user_codex:HermitCodex", + "pythonpath": [ + str(HERE / "utils"), + str(Path(ahe_root).resolve() / "backend"), + ], + "kwargs": { + **( + { + "config": { + "model_provider": "gateway", + "model_providers": { + "gateway": { + "name": "gateway", + "base_url": actor_url, + "env_key": "OPENAI_API_KEY", + "wire_api": "responses", + "supports_websockets": False, + } + }, + } + } + if http_only + else {} + ), + "user": { + "simulate": "ahe_beta.integrations.hermit.session:simulate", + "wait_s": 3600, + }, + }, + }, + }, + }, + "judge": {"path": str(ROOT / "hermit/harbor/judge.py"), "name": "score"}, + "evolver": {"name": "ahe_beta", "params": {"delivery_config": "delivery.json"}}, + "evolver_access": {"send_material_out": True}, + "sandbox": {"enforce": "required"}, + "environment": {"runner": "host"}, + "trainer": { + "run_name": run_id, + "output_dir": str(cohort / "runs"), + "epochs": 1, + "call_timeout_min": 1440, + "budget": {"hours": 168}, + }, + } + (cohort / "task-info").mkdir(exist_ok=True) + (cohort / "task-info/README.md").write_text( + "# AHE adapter evolution\n\nEach step is one complete user cohort. Preserve direct and interactive use.\n" + "The final split is a same-cohort observation round, not a held-out benchmark.\n" + ) + for name, value in [ + ("delivery.json", json.dumps(request, indent=2) + "\n"), + ("run.yaml", yaml.safe_dump(config, sort_keys=False)), + ]: + path = cohort / name + if path.exists(): + raise FileExistsError(path) + path.write_text(value) + return config + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ( + "cohort", + "ahe-root", + "ahe-python", + "harbor", + "delivery-repo", + "run-id", + "actor-model", + "actor-url", + ): + parser.add_argument("--" + name, required=True) + parser.add_argument( + "--http-only", + action="store_true", + help="Responses HTTP for gateways without WebSocket support", + ) + prepare(**vars(parser.parse_args())) + + +if __name__ == "__main__": + main() diff --git a/examples/ahe_beta/requirements.txt b/examples/ahe_beta/requirements.txt new file mode 100644 index 00000000..35d9e96b --- /dev/null +++ b/examples/ahe_beta/requirements.txt @@ -0,0 +1,5 @@ +# Install into Harbor's own environment, alongside this Hermit source checkout. +harbor==0.25.0 +openai>=2.29,<4 +python-dotenv>=1.1,<2 +requests>=2.32,<3 diff --git a/examples/ahe_beta/smoke/Dockerfile b/examples/ahe_beta/smoke/Dockerfile new file mode 100644 index 00000000..a881e390 --- /dev/null +++ b/examples/ahe_beta/smoke/Dockerfile @@ -0,0 +1,7 @@ +FROM node:22-bookworm-slim +ARG DEBIAN_MIRROR=http://deb.debian.org/debian +RUN sed -i "s|http://deb.debian.org/debian|${DEBIAN_MIRROR}|g" /etc/apt/sources.list.d/debian.sources \ + && apt-get update && apt-get install -y --no-install-recommends python3 curl ripgrep ca-certificates \ + && rm -rf /var/lib/apt/lists/* +RUN npm install -g @openai/codex@0.164.0 +WORKDIR /app diff --git a/examples/ahe_beta/smoke/native.py b/examples/ahe_beta/smoke/native.py new file mode 100644 index 00000000..4045c4c8 --- /dev/null +++ b/examples/ahe_beta/smoke/native.py @@ -0,0 +1,189 @@ +"""One real Codex rollout with the native AHE user/reviewer and artifact collector. + +Credentials come from ACTOR_API_KEY, USER_LLM_API_KEY and USER_LLM_BASE_URL. +The temporary Git commit is the frozen test adapter, not a source-repository commit. +""" + +import argparse +import hashlib +import json +from pathlib import Path +import shutil +import subprocess +import sys + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / "utils")) +from acting import AheHarborAgent +from binding import write + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--ahe-root", required=True, type=Path) + parser.add_argument("--harbor", required=True) + parser.add_argument("--model", required=True) + parser.add_argument("--base-url", required=True) + parser.add_argument( + "--http-only", + action="store_true", + help="Use Responses HTTP for gateways without WebSocket support", + ) + parser.add_argument( + "--interaction", choices=["direct", "simulated_user"], default="direct" + ) + args = parser.parse_args() + root = args.output.resolve() + root.mkdir(parents=True) + template = HERE.parents[2] / "hermit/adapter/templates/ahe_beta" + adapter = root / "adapter" + shutil.copytree(template, adapter) + + def git(*cmd): + subprocess.run( + ["git", "-C", str(adapter), *cmd], check=True, capture_output=True + ) + + git("init", "-b", "main") + git("config", "user.name", "Integration fixture") + git("config", "user.email", "fixture@example.invalid") + git("add", ".") + git("commit", "-m", "Freeze the smoke adapter") + write( + root / "binding.json", + adapter=adapter, + repo=adapter, + run_id=root.name, + round_no=1, + ) + task_dir = root / "tasks/native-demo" + for directory in ("environment", "tests"): + (task_dir / directory).mkdir(parents=True) + instruction = "Create /app/answer.txt containing exactly the single line hello hermit. Read it back to verify the contents. Do not modify other files." + (task_dir / "instruction.md").write_text(instruction) + (task_dir / "environment/Dockerfile").write_text( + "FROM ahe-hermit-smoke:local\nWORKDIR /app\n" + ) + (task_dir / "task.toml").write_text( + 'schema_version = "1.4"\n[agent]\ntimeout_sec = 600\n[verifier]\ntimeout_sec = 60\n[environment]\ncpus = 1\nmemory_mb = 1024\nbuild_timeout_sec = 300\n' + ) + (task_dir / "tests/test.sh").write_text( + "#!/bin/sh\nset -eu\nmkdir -p /logs/verifier\ntest -s /logs/agent/user-reward.txt\ncp /logs/agent/user-reward.txt /logs/verifier/reward.txt\n" + ) + digest = hashlib.sha256(instruction.encode()).hexdigest() + card = json.loads((args.ahe_root / "examples/personas/library.json").read_text())[0] + artifacts = [ + { + "id": "answer", + "source": "workspace", + "path": "answer.txt", + "content_type": "text/plain", + "required": True, + "max_bytes": 1024, + } + ] + row = { + "id": "r01-s00-native-demo", + "harbor_task": "native-demo", + "agent_timeout_sec": 600, + "build_timeout_sec": 300, + "verifier_timeout_sec": 60, + "ahe_session": { + "task_id": "native-demo", + "task_digest": digest, + "task_kind": "ordinary", + "round": 1, + "slot": 0, + "persona": card, + "interaction": args.interaction, + "environment": {"workdir": "/app", "patch": "not_applicable"}, + "scenario": { + "description": instruction, + "workspace": { + "kind": "external", + "params": { + "task_id": "native-demo", + "task_digest": digest, + "task_kind": "ordinary", + "interaction": args.interaction, + "evaluation_artifacts": artifacts, + "execution": { + "task_budget_seconds": 600, + "budget_source": "operator_quota", + }, + }, + }, + }, + }, + } + runner = AheHarborAgent( + { + "harbor": args.harbor, + "tasks_dir": str(root / "tasks"), + "jobs_dir": str(root / "jobs"), + "binding": str(root / "binding.json"), + "disk_gate_gb": 5, + "model": { + "model": args.model, + "base_url": args.base_url, + "api_key_env": "ACTOR_API_KEY", + }, + "codex_version": "0.164.0", + "codex_login": False, + "agent_timeout_sec": None, + "environment": {"delete": True, "kwargs": {"auto_mounting": True}}, + "acting_agent": { + "import_path": "hermit_user_codex:HermitCodex", + "pythonpath": [ + str(HERE.parent / "utils"), + str(args.ahe_root / "backend"), + ], + "kwargs": { + **( + { + "config": { + "model_provider": "gateway", + "model_providers": { + "gateway": { + "name": "gateway", + "base_url": args.base_url, + "env_key": "OPENAI_API_KEY", + "wire_api": "responses", + "supports_websockets": False, + } + }, + } + } + if args.http_only + else {} + ), + "user": { + "simulate": "ahe_beta.integrations.hermit.session:simulate", + "wait_s": 300, + }, + }, + }, + }, + base=root, + ) + result = runner.run(row, adapter) + verdict = json.loads((Path(result.log) / "agent/user-verdict.json").read_text()) + summary = { + "output": result.output, + "log": str(result.log), + "rating": verdict["rating"], + "score_kind": verdict["score_kind"], + "user_usage": verdict["usage"], + "actor_tokens": result.extra.get("actor_tokens", result.tokens), + "total_tokens": result.tokens, + } + (root / "report.json").write_text(json.dumps(summary, indent=2) + "\n") + session = json.loads((Path(result.log) / "agent/user-session.json").read_text()) + assert session["workspace_evidence"]["evaluation_artifacts"]["complete"] + assert session["workspace_evidence"]["actor_freeze"]["status"] == "frozen" + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/examples/ahe_beta/smoke/smoke.py b/examples/ahe_beta/smoke/smoke.py new file mode 100644 index 00000000..c80b1fa7 --- /dev/null +++ b/examples/ahe_beta/smoke/smoke.py @@ -0,0 +1,277 @@ +"""End-to-end check of the user channel on Hermit main, unchanged: a real Harbor trial (Docker), Codex installed by +Harbor, a scripted model on this host, the scripted user in utils/scripted_user.py. + + PYTHONPATH= smoke.py [adapter dir] +""" + +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import os +from pathlib import Path +import sys +import threading + +HERE = Path(__file__).resolve().parent +GATEWAY = os.environ.get( + "DOCKER_GATEWAY", "10.100.0.1" +) # the host, as a container reaches it +TOML = """schema_version = "1.4" + +[metadata] +author_name = "hermit" +difficulty = "easy" +category = "smoke" +tags = ["smoke"] + +[verifier] +timeout_sec = 60.0 + +[agent] +timeout_sec = 600.0 + +[environment] +build_timeout_sec = 300.0 +cpus = 1 +memory_mb = 1024 +""" +TEST_SH = """#!/bin/bash +# The reward of a session with a simulated user is the user's rating, which the agent class left in the agent's logs. +mkdir -p /logs/verifier +if [ -s /logs/agent/user-reward.txt ]; then + cp /logs/agent/user-reward.txt /logs/verifier/reward.txt + echo "user verdict:"; cat /logs/agent/user-verdict.json +else + echo "no user rating: this trial is not scored" +fi +""" +TURNS = [ + {"cmd": "echo one >> /app/a.txt"}, + {"cmd": "sleep 4; echo two >> /app/a.txt"}, + "REPLY-1", + {"cmd": "sleep 4; echo three >> /app/a.txt"}, + {"cmd": "echo four >> /app/a.txt"}, + "REPLY-2", + "REPLY-3", + "REPLY-EXTRA", +] + + +def js(command): + return ( + 'try {\n const r = await tools.exec_command({"cmd": ' + + json.dumps(command) + + "});\n text(r);\n" + '} catch (e) {\n text("CAUGHT: " + String(e));\n}' + ) + + +def items_of(turn, n): + if isinstance(turn, str): + return [ + { + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": turn}], + } + ] + return [ + { + "type": "custom_tool_call", + "name": "exec", + "call_id": f"call{n}", + "input": js(turn["cmd"]), + } + ] + + +def serve(): + requests, lock = [], threading.Lock() + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + self.send_response(404) + self.send_header("content-length", "0") + self.end_headers() + + def do_POST(self): + body = json.loads( + self.rfile.read(int(self.headers.get("content-length") or 0)) or b"{}" + ) + with lock: + n = len(requests) + requests.append(body) + items = [ + dict(item, id=f"it{n}_{k}", status="completed") + for k, item in enumerate(items_of(TURNS[min(n, len(TURNS) - 1)], n)) + ] + events = [ + { + "type": "response.created", + "response": {"id": f"r{n}", "status": "in_progress", "output": []}, + } + ] + events += [ + {"type": "response.output_item.done", "output_index": k, "item": item} + for k, item in enumerate(items) + ] + events.append( + { + "type": "response.completed", + "response": { + "id": f"r{n}", + "status": "completed", + "output": items, + "usage": { + "input_tokens": 1, + "input_tokens_details": {"cached_tokens": 0}, + "output_tokens": 1, + "output_tokens_details": {"reasoning_tokens": 0}, + "total_tokens": 2, + }, + }, + } + ) + data = b"".join( + f"event: {e['type']}\ndata: {json.dumps(e)}\n\n".encode() + for e in events + ) + self.send_response(200) + self.send_header("content-type", "text/event-stream") + self.send_header("content-length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + server = ThreadingHTTPServer(("0.0.0.0", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, f"http://{GATEWAY}:{server.server_address[1]}/v1", requests + + +def main(): + root = Path(sys.argv[1]).resolve() + adapter = Path(sys.argv[2]).resolve() if len(sys.argv) > 2 else None + task = root / "tasks" / "user-demo" + for rel, text in { + "task.toml": TOML, + "instruction.md": "Append the lines one and two to /app/a.txt.\n", + "environment/Dockerfile": "FROM " + + os.environ.get("SMOKE_IMAGE", "python:3.11-slim") + + "\nWORKDIR /app\n", + "tests/test.sh": TEST_SH, + }.items(): + (task / rel).parent.mkdir(parents=True, exist_ok=True) + (task / rel).write_text(text) + (task / "tests" / "test.sh").chmod(0o755) + from hermit.harbor import dataset + from hermit.harbor.judge import score + from hermit.harbor.runner import HarborAgent + + rows = {r["id"]: r for r in dataset.index(root / "tasks")} + if adapter is not None: # the adapter's Stop hook sends the first answer back once + TURNS.insert(2, "DRAFT-1") + server, url, requests = serve() + os.environ["MOCK_API_KEY"] = "dummy" + agent = HarborAgent( + { + "harbor": os.environ.get( + "HARBOR_BIN", str(Path.home() / ".cache/hermit/harbor-venv/bin/harbor") + ), + "tasks_dir": str(root / "tasks"), + "jobs_dir": str(root / "jobs"), + "disk_gate_gb": 5, + "model": { + "model": "gpt-5.6-luna", + "base_url": url, + "api_key_env": "MOCK_API_KEY", + }, + "codex_version": "0.164.0", + "codex_login": False, + "agent_timeout_sec": int(os.environ.get("SMOKE_TIMEOUT", "600")), + "sandbox_enforce": "best_effort", + "environment": {"delete": True, "kwargs": {"auto_mounting": True}}, + "acting_agent": { + "import_path": "hermit_user_codex:HermitCodex", + "pythonpath": [str(HERE.parent / "utils"), str(HERE)], + "kwargs": { + "user": { + "simulate": os.environ.get( + "SMOKE_SIM", "scripted_user:simulate" + ), + "params": {"persona": "demo"}, + "wait_s": 120, + } + }, + }, + }, + base=root, + ) + out = agent.run(rows["user-demo"], adapter) + server.shutdown() + blobs = [json.dumps(r) for r in requests] + first = { + t: next((i for i, b in enumerate(blobs) if t in b), None) + for t in ( + "FIRST:", + "USER-INSERT", + "USER-FOLLOWUP", + "USER-INTERRUPT", + "USER-FINAL", + "ADAPTER-CHECK", + ) + } + log = Path(out.log) if out.log else None + report = { + "output": out.output, + "judge": score(rows["user-demo"], out), + "model_requests": len(requests), + "first_request_with": first, + "agent_metadata_user": (out.extra.get("agent_metadata") or {}).get("user"), + "replies_heard": [ + r.get("text") + for r in json.loads( + (Path(out.log) / "agent" / "user-verdict.json").read_text() + ) + .get("record", {}) + .get("replies", []) + ] + if out.log and (Path(out.log) / "agent" / "user-verdict.json").is_file() + else None, + "deployed": out.extra.get("deployed"), + "exception": [ + out.extra.get("exception_type"), + out.extra.get("exception_message"), + ], + "log_agent_files": sorted(p.name for p in (log / "agent").iterdir()) + if log + else None, + "verifier_stdout": (log / "verifier" / "test-stdout.txt").read_text()[:600] + if log and (log / "verifier" / "test-stdout.txt").is_file() + else None, + "log": str(log), + } + (root / "report.json").write_text(json.dumps(report, indent=1, default=str)) + print(json.dumps(report, indent=1, default=str)) + assert out.output["status"] == "ok", report["exception"] + assert all( + first[name] is not None + for name in ( + "FIRST:", + "USER-INSERT", + "USER-FOLLOWUP", + "USER-INTERRUPT", + "USER-FINAL", + ) + ) + assert report["agent_metadata_user"]["interrupts"] == 1 + assert ( + "four" + not in json.loads((log / "agent/user-verdict.json").read_text())["record"][ + "workspace" + ] + ) + + +if __name__ == "__main__": + main() diff --git a/examples/ahe_beta/utils/acting.py b/examples/ahe_beta/utils/acting.py new file mode 100644 index 00000000..7686bb6b --- /dev/null +++ b/examples/ahe_beta/utils/acting.py @@ -0,0 +1,124 @@ +"""A task-local Harbor runner: inject frozen user assignment and reject invalid trials.""" + +from __future__ import annotations + +import copy +from dataclasses import asdict +import hashlib +import threading +import json +import os +from pathlib import Path +import shutil +import uuid + +from hermit.harbor.runner import HarborAgent +from hermit.task import RunOutput, RunUnavailable +from binding import fingerprint, read + + +class AheHarborAgent(HarborAgent): + def __init__(self, params=None, base=None): + super().__init__(params, base) + self._binding = threading.local() + + def agent_config(self, task, staging, deployed): + config = super().agent_config(task, staging, deployed) + spec = copy.deepcopy(config.setdefault("kwargs", {}).get("user") or {}) + spec.setdefault("simulate", "ahe_beta.integrations.hermit.session:simulate") + spec["params"] = { + **spec.get("params", {}), + **task["ahe_session"], + "session_id": task["id"] + "-" + uuid.uuid4().hex[:12], + **self._binding.value, + } + config["kwargs"]["user"] = spec + return config + + def run(self, task, adapter): + try: + return self._run(task, adapter) + except RunUnavailable: + raise + except Exception as exc: + raise RunUnavailable( + f"AHE rollout {task['id']} unavailable: {type(exc).__name__}: {exc}" + ) from exc + + def _run(self, task, adapter): + # A completed rollout is reusable only for the same frozen assignment, adapter, + # endpoint/model and runner settings. Credentials are deliberately not cache keys. + binding_path = self.path(self.params["binding"]) + run_id = json.loads(binding_path.read_text())["run_id"] + key = hashlib.sha256( + json.dumps( + { + "task": task, + "adapter": fingerprint(adapter), + "params": self.params, + "run_id": run_id, + "user_model": { + k: os.environ.get(k) + for k in ( + "USER_LLM_MODEL", + "USER_LLM_BASE_URL", + "USER_LLM_MAX_TOKENS", + "USER_LLM_REASONING_EFFORT", + "USER_LLM_MAX_CONTEXT_TOKENS", + ) + }, + }, + sort_keys=True, + default=str, + ).encode() + ).hexdigest() + cached = self.jobs_dir / "completed" / (key + ".json") + if cached.exists(): + saved = json.loads(cached.read_text()) + log = Path(saved["log"]) + if log.is_dir() and (log / "ahe-session").is_dir(): + return RunOutput(**saved) + raise RunUnavailable("cached successful rollout lost its native evidence") + self._binding.value = read(binding_path, adapter) + if self._binding.value["round"] != task["ahe_session"]["round"]: + raise RunUnavailable("rollout is not in the current frozen cohort") + result = super().run(task, adapter) + output = result.output if isinstance(result.output, dict) else {} + # Keep native AHE snapshots/binary exports alongside Hermit's curated text logs. + if result.log: + log = Path(result.log) + job = log.parent + for source in job.glob("*/agent/ahe-session"): + shutil.copytree(source, log / "ahe-session", dirs_exist_ok=True) + verdict_file = ( + Path(result.log) / "agent/user-verdict.json" if result.log else None + ) + verdict = ( + json.loads(verdict_file.read_text()) + if verdict_file and verdict_file.exists() + else {} + ) + if ( + output.get("status") != "ok" + or verdict.get("error") + or verdict.get("score") is None + ): + raise RunUnavailable( + f"AHE rollout {task['id']} is unscored; inspect {result.log}" + ) + user_usage = verdict.get("usage", {}) + actor_tokens = result.tokens + result.extra["actor_tokens"] = actor_tokens + result.extra["user_usage"] = user_usage + result.tokens = ( + actor_tokens + user_usage.get("total_tokens", 0) + if actor_tokens is not None and not user_usage.get("unavailable_count") + else None + ) + # Harbor estimates only Actor cost. User-call prices are not supplied here. + result.cost_usd = None + cached.parent.mkdir(parents=True, exist_ok=True) + temporary = cached.with_suffix(".tmp") + temporary.write_text(json.dumps(asdict(result), default=str)) + temporary.replace(cached) + return result diff --git a/examples/ahe_beta/utils/binding.py b/examples/ahe_beta/utils/binding.py new file mode 100644 index 00000000..8b4273ae --- /dev/null +++ b/examples/ahe_beta/utils/binding.py @@ -0,0 +1,54 @@ +"""Bind tested adapter bytes to the delivery repository without equating Git histories.""" + +import hashlib +import json +from pathlib import Path +import subprocess + +from hermit.adapter.manifest import files_of + + +def fingerprint(root): + root = Path(root) + digest = hashlib.sha256() + for relative in files_of(root): + # Hermit owns the card/history, not the learning method's delivery repository. + if relative == ".hermit/CARD.md": + continue + path = root / relative + if path.is_symlink(): + raise ValueError("adapter binding does not accept symlinks") + digest.update(relative.encode() + b"\0") + digest.update(str(path.stat().st_mode & 0o111).encode() + b"\0") + digest.update(path.read_bytes() + b"\0") + return digest.hexdigest() + + +def git(repo, *args): + return subprocess.check_output(["git", "-C", str(repo), *args], text=True).strip() + + +def read(path, adapter): + value = json.loads(Path(path).read_text()) + if value["adapter_sha256"] != fingerprint(adapter): + raise ValueError("tested adapter differs from the frozen delivery binding") + return value + + +def write(path, *, adapter, repo, run_id, round_no): + if git(repo, "status", "--porcelain"): + raise ValueError("delivery checkout must be clean") + if fingerprint(repo) != fingerprint(adapter): + raise ValueError("delivery checkout and Hermit adapter have different contents") + value = { + "run_id": run_id, + "round": round_no, + "harness_sha": git(repo, "rev-parse", "HEAD"), + "adapter_sha256": fingerprint(adapter), + } + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n") + temporary.replace(path) + return value diff --git a/examples/ahe_beta/utils/channel.py b/examples/ahe_beta/utils/channel.py new file mode 100644 index 00000000..0c47b6fc --- /dev/null +++ b/examples/ahe_beta/utils/channel.py @@ -0,0 +1,141 @@ +"""File mailbox shared by the Codex hooks and a task-owned simulated user.""" + +from __future__ import annotations +import json +import os +from pathlib import Path +import threading +import time + + +class ConversationClosed(RuntimeError): + """Codex is no longer running (it exited, or the trial was cancelled).""" + + +class Conversation: + """The running session, as the user's code holds it. Called from the thread `simulate` runs in.""" + + capabilities = frozenset({"turns", "insert", "interrupt", "progress"}) + + def __init__(self, mail: Path, start, alive, stop): + self.mail, self._start, self._alive, self._stop = mail, start, alive, stop + self.transcript: list[dict] = [] + self.closed = False + self._started = False + self._seen: set[str] = set() + self._events: list[dict] = [] + self._replies: list[dict] = [] + self._n = 0 + self._lock = threading.Lock() + for name in ("to-agent", "to-user", "taken"): + (mail / name).mkdir(parents=True, exist_ok=True) + os.chmod( + mail / name, 0o777 + ) # the container's user is not this process's user + os.chmod(mail, 0o777) + + # ----- to the agent ----------------------------------------------------------------------------------------------- + def _drop(self, kind: str, **fields) -> dict: + with self._lock: + self._n += 1 + record = { + "id": f"u{self._n}", + "kind": kind, + "t": round(time.time(), 3), + **fields, + } + name = f"{time.time():017.6f}-{kind}.json" + tmp = self.mail / "to-agent" / ("." + name) + tmp.write_text(json.dumps(record)) + os.chmod(tmp, 0o666) + os.replace(tmp, self.mail / "to-agent" / name) + self.transcript.append({"from": "user", **record}) + return record + + def write(self, text: str) -> None: + """Say something. The first message starts Codex with it as the prompt; a later one reaches the model after + the tool call that is running, or as the next turn when the agent has stopped.""" + if self.closed: + raise ConversationClosed("the session is over") + if not self._started: + self._started = True + self._n += 1 + self.transcript.append( + { + "from": "user", + "id": f"u{self._n}", + "kind": "message", + "t": round(time.time(), 3), + "text": text, + "first": True, + } + ) + self._start(text) + return + self._drop("message", text=text) + + def interrupt(self, text: str = "", timeout: float = 300.0) -> dict | None: + """Stop the agent at its next tool call (it is told why) and wait for it to stop: the reply it stops with, + or None when it has not stopped within `timeout`.""" + if self.closed or not self._started: + raise ConversationClosed("there is no active request to interrupt") + self._drop("interrupt", text=text) + return self.poll(timeout) if timeout > 0 else None + + def end(self) -> None: + """Let the agent stop for good. Called by the framework side when `simulate` returns.""" + if self._started and not self.closed: + self._drop("end") + self.closed = True + + def close(self) -> None: + """End the conversation and synchronously stop the Actor before capture.""" + self.end() + self._stop() + + # ----- from the agent --------------------------------------------------------------------------------------------- + def _read(self) -> None: + for path in sorted((self.mail / "to-user").glob("[!.]*.json")): + if path.name in self._seen: + continue + try: + event = json.loads(path.read_text()) + except (OSError, ValueError): + continue + self._seen.add(path.name) + self.transcript.append({"from": "agent", **event}) + (self._replies if event.get("kind") == "reply" else self._events).append( + event + ) + + def poll(self, timeout: float = 0.0) -> dict | None: + """The agent's next reply ({"kind": "reply", "text": ..., "interrupted": bool}), waiting up to `timeout` + seconds; None when it is still working. Raises ConversationClosed when Codex is gone.""" + deadline = time.monotonic() + max(0.0, timeout) + while True: + self._read() + if self._replies: + return self._replies.pop(0) + if self.closed or not self._alive(): + self._read() + if self._replies: + return self._replies.pop(0) + raise ConversationClosed("Codex exited without a reply") + if time.monotonic() >= deadline: + return None + time.sleep(0.2) + + def send(self, text: str, timeout: float | None = None) -> str: + """Say something and wait for the whole reply.""" + self.write(text) + reply = self.poll(timeout if timeout is not None else 10**9) + if reply is None: + raise TimeoutError(f"no reply within {timeout} s") + return reply["text"] + + def events(self) -> list[dict]: + """What the agent did since the last call: tool_start, tool (with its output), denied, delivered (a message + of the user's reached the model, and where), adapter_block, timeout.""" + self._read() + out, self._events = self._events, [] + return out diff --git a/examples/ahe_beta/utils/hermit_user_codex.py b/examples/ahe_beta/utils/hermit_user_codex.py new file mode 100644 index 00000000..e96bfcef --- /dev/null +++ b/examples/ahe_beta/utils/hermit_user_codex.py @@ -0,0 +1,485 @@ +"""Codex in a Harbor task container, with a simulated user talking to it while it works. + +The interaction bridge lives in this example. Harbor imports this class through the run's own YAML: + + agent: + name: harbor + params: + acting_agent: + import_path: hermit_user_codex:HermitCodex # the class name must be HermitCodex (see below) + pythonpath: [../utils] # this file, user_hook.py and the user's own code + kwargs: + user: + simulate: my_user:simulate # module:function, importable from `pythonpath` + params: {} # passed to the function as given + wait_s: 3600 # how long the agent waits for the user's next message + exit_wait_s: 120 # how long Codex gets to exit after the user ends + environment: + kwargs: {auto_mounting: true} # Harbor mounts /logs/agent from the host (off by default) + +The function the task side writes: + + def simulate(task: dict, agent: Conversation, workspace: Workspace, params: dict) -> dict + + task {"name": the Harbor task's name, "instruction": its instruction.md} + agent the running Codex session: write / poll / send / events / interrupt (class Conversation) + workspace the task container: run / read / write (class Workspace) + returns {"score": float | None, ...}: `score` becomes the trial's reward through the task's verifier + (None: no reward is written); every other key is kept in user-verdict.json. A `files` key + ({name: text}) writes more files beside it. + +One `codex exec` runs for the whole conversation. Three hooks (user_hook.py, in the container) pass the messages: +PostToolUse inserts a message while the agent works, PreToolUse denies tool calls after an interrupt, Stop hands +the reply to the user and continues the session with the user's next message. The mailbox is a directory under the +agent's log directory, which Harbor mounts from the host, so this side only reads and writes files. + +What the trial leaves in the agent's log directory (Hermit copies each into the learning material): + + user-verdict.json what `simulate` returned (without `files`) + user-transcript.jsonl every user message, every reply, every tool call the user could see, with times + user-reward.txt the score, when there is one (the task's tests/test.sh copies it to the reward file) + +The class is named HermitCodex because Hermit's runner (hermit/harbor/runner.py, `deploys_adapter`) gives the +adapter to an agent whose import path ends in `:HermitCodex`. +""" + +from __future__ import annotations + +import asyncio +import importlib +import json +import math +import inspect +import processes +import os +from pathlib import Path, PurePosixPath +import shlex +import tempfile +from typing import Any + +from harbor.environments.base import BaseEnvironment +from harbor.models.agent.context import AgentContext +from harborside.codex import HermitCodex as _HermitCodex +from harborside.codex import HermitCodexOptions as _HermitCodexOptions +from pydantic import Field + +MAIL = "user-mail" # under the agent's log directory +HOOK_DIR = "hermit-user" # under $CODEX_HOME: outside the project the agent works on +EVENTS = ("PreToolUse", "PostToolUse", "Stop") +FRAMES = { + "reply_frame": "The user says:\n{text}", + "insert_frame": "The user sent this while you were working:\n{text}", + "interrupt_frame": "The user interrupted you: {text}\nStop here. Do not call any more tools. Say in one or " + "two sentences where things stand, then wait for the user's next message.", +} + + +from channel import Conversation + + +class Workspace: + """The task container, for the user's own checks. Called from the thread `simulate` runs in.""" + + def __init__( + self, environment: BaseEnvironment, loop: asyncio.AbstractEventLoop, stop + ): + self._environment, self._loop, self._stop = environment, loop, stop + self._closed = False + + def quiesce(self) -> None: + self._stop() + + def close(self) -> None: + # Harbor owns container deletion. Closing only revokes the user's command capability. + self._closed = True + + def _wait(self, coroutine, timeout: float | None): + return asyncio.run_coroutine_threadsafe(coroutine, self._loop).result(timeout) + + def run(self, command: str, timeout: float = 60.0, cwd: str | None = None) -> dict: + if self._closed: + raise RuntimeError("workspace access has ended") + result = self._wait( + self._environment.exec(command=command, cwd=cwd, timeout_sec=int(timeout)), + timeout + 30, + ) + return { + "code": result.return_code, + "stdout": result.stdout or "", + "stderr": result.stderr or "", + } + + def read(self, path: str) -> str: + out = self.run(f"cat {shlex.quote(path)}") + if out["code"] != 0: + raise FileNotFoundError(f"{path}: {out['stderr'].strip()}") + return out["stdout"] + + def write(self, path: str, text: str) -> None: + if self._closed: + raise RuntimeError("workspace access has ended") + with tempfile.TemporaryDirectory(prefix="hermit-user-") as tmp: + local = Path(tmp) / PurePosixPath(path).name + local.write_text(text) + self._wait(self._environment.upload_file(local, path), 120) + + def service_identity(self, name): + return self._environment.environment_name + ":" + name + + def service_run(self, command, *, service, timeout, cwd): + if self._closed: + raise RuntimeError("workspace access has ended") + result = self._wait( + self._environment.service_exec( + command, service=service, cwd=cwd, timeout_sec=int(timeout) + ), + timeout + 30, + ) + return { + "code": result.return_code, + "stdout": result.stdout or "", + "stderr": result.stderr or "", + } + + def service_read(self, path, *, service, max_bytes): + # Copy an explicitly declared controller-owned output; reject non-regular files first. + quoted = shlex.quote(path) + check = self.service_run( + f"test -f {quoted} && test ! -L {quoted} && stat -c %s {quoted}", + service=service, + timeout=30, + cwd="/", + ) + if check["code"]: + raise FileNotFoundError(path) + if int(check["stdout"].strip()) > max_bytes: + raise OverflowError(path) + with tempfile.TemporaryDirectory(prefix="ahe-service-") as tmp: + target = Path(tmp) / "artifact" + self._wait( + self._environment.service_download_file(path, target, service=service), + 120, + ) + if ( + target.is_symlink() + or not target.is_file() + or target.stat().st_size > max_bytes + ): + raise ValueError("invalid or oversized service artifact") + return target.read_bytes() + + +def load(spec: str): + module, _, name = str(spec).partition(":") + if not module or not name: + raise ValueError(f"user.simulate must be module:function, not {spec!r}") + return getattr(importlib.import_module(module), name) + + +class HermitCodexOptions(_HermitCodexOptions): + user: dict | None = Field( + default=None, + description="The simulated user: {simulate: module:function, params: {}, " + "wait_s, exit_wait_s}. Omit for a session without a user.", + ) + + +class HermitCodex(_HermitCodex): + options_model = HermitCodexOptions + options: HermitCodexOptions + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._user_summary: dict | None = None + if self.options.user: + load( + self.options.user["simulate"] + ) # a wrong name fails before any container + self.options.dangerously_bypass_hook_trust = ( + True # the hooks are this file's own + ) + + # ----- the hooks --------------------------------------------------------------------------------------------------- + + async def _upload_effective_config( + self, environment: BaseEnvironment, config: dict[str, Any], remote_path: str + ) -> None: + """After Hermit's deployment: the adapter's hooks stay, except its Stop hooks, which user_hook.py runs itself + before the user hears a reply (Codex runs the hooks of one event at the same time).""" + await super()._upload_effective_config(environment, config, remote_path) + spec = self.options.user + if not spec: + return + if self._agent_identity is None: + await self._ensure_agent_owned_dir(environment, self._REMOTE_CODEX_HOME) + if not await self._ensure_python3(environment): + raise RuntimeError("the user channel needs python3 in the task's image") + workdir = await self._workdir(environment) + hook_dir = PurePosixPath(remote_path).parent / HOOK_DIR + script = (hook_dir / "user_hook.py").as_posix() + adapter = ( + json.loads(self._hooks_file.read_text()).get("hooks", {}) + if self._hooks_file + else {} + ) + for group in adapter.get("Stop", []): + if group.get("matcher") or any( + h.get("type") != "command" for h in group.get("hooks", []) + ): + raise ValueError( + "interactive Stop hooks require unconditional command hooks" + ) + settings = { + "mail": (self.environment_logs_dir / MAIL).as_posix(), + "wait_s": float(spec.get("wait_s") or 3600), + "adapter_stop": [ + h + for group in adapter.get("Stop") or [] + for h in group.get("hooks") or [] + if h.get("type") == "command" + ], + **{key: str(spec.get(key) or default) for key, default in FRAMES.items()}, + } + timeout = int( + settings["wait_s"] + + sum(float(h.get("timeout") or 60) for h in settings["adapter_stop"]) + + 60 + ) + merged = { + event: list(groups) for event, groups in adapter.items() if event != "Stop" + } + for event in EVENTS: + merged.setdefault(event, []).append( + { + "hooks": [ + { + "type": "command", + "command": f"python3 -B {shlex.quote(script)} {event}", + "timeout": timeout if event == "Stop" else 30, + } + ] + } + ) + remote_hooks = workdir.rstrip("/") + "/.codex/hooks.json" + await self.exec_as_root( + environment, + command=f"mkdir -p {shlex.quote(hook_dir.as_posix())} " + f"{shlex.quote(workdir.rstrip('/') + '/.codex')}", + ) + await environment.upload_file(Path(__file__).with_name("user_hook.py"), script) + await self._upload_text( + environment, + json.dumps(settings, indent=1), + (hook_dir / "user_hook.json").as_posix(), + ) + await self._upload_text( + environment, json.dumps({"hooks": merged}, indent=2), remote_hooks + ) + uid, gid = self._agent_identity + owned = shlex.join([hook_dir.as_posix(), workdir.rstrip("/") + "/.codex"]) + await self.exec_as_root( + environment, + command=f"chown -R {uid}:{gid} {owned} && chmod -R u+rwX,go+rX {owned}", + ) + self._hooks_active = True + + # ----- the session ------------------------------------------------------------------------------------------------- + + async def run( + self, instruction: str, environment: BaseEnvironment, context: AgentContext + ) -> None: + spec = self.options.user + if not spec: + return await super().run(instruction, environment, context) + if not environment.is_path_mounted(self.environment_logs_dir, self.logs_dir): + raise RuntimeError( + "the user channel passes messages through the agent's log directory, which must be " + "mounted from the host: set agent.params.environment.kwargs.auto_mounting: true" + ) + loop = asyncio.get_running_loop() + first: dict = {} + started = asyncio.Event() + codex: asyncio.Task | None = None + + def start(text: str) -> None: + first["text"] = text + loop.call_soon_threadsafe(started.set) + + baseline_script = ( + inspect.getsource(processes) + + "\nimport json; print(json.dumps(snapshot()))" + ) + baseline_run = await self.exec_as_root( + environment, command=shlex.join(["python3", "-c", baseline_script]) + ) + if baseline_run.return_code: + raise RuntimeError("could not capture rollout process boundary") + baseline = json.loads(baseline_run.stdout) + stopped = False + stopping = asyncio.Lock() + + async def stop_actor(): + nonlocal stopped + async with stopping: + if stopped: + return + conversation.end() + if codex is not None: + try: + await asyncio.wait_for( + asyncio.shield(codex), + timeout=float(spec.get("exit_wait_s", 10)), + ) + except asyncio.TimeoutError: + # User abandonment is allowed, but all children must stop before snapshotting. + codex.cancel() + finally: + ports = [ + p + for row in ( + (spec.get("params") or {}).get("environment") or {} + ).get("services", []) + for p in row.get("handoff_ports", []) + ] + cleanup = ( + inspect.getsource(processes) + + "\nquiesce(" + + repr(baseline) + + ", " + + repr(ports) + + ")" + ) + result = await self.exec_as_root( + environment, + command=shlex.join(["python3", "-c", cleanup]), + timeout_sec=15, + ) + if result.return_code: + raise RuntimeError( + "Actor processes could not be quiesced: " + + str(result.stderr) + ) + if codex.cancelled() or codex.cancelling(): + await asyncio.gather(codex, return_exceptions=True) + stopped = True + + def stop_sync(): + asyncio.run_coroutine_threadsafe(stop_actor(), loop).result( + float(spec.get("exit_wait_s", 10)) + 45 + ) + + conversation = Conversation( + self.logs_dir / MAIL, + start, + lambda: codex is None or not codex.done(), + stop_sync, + ) + task = {"name": environment.environment_name, "instruction": instruction} + workspace = Workspace(environment, loop, stop_sync) + user_params = dict(spec.get("params") or {}) + user_params["artifact_root"] = str(self.logs_dir / "ahe-session") + os.environ["AHE_BETA_USAGE_PATH"] = str( + self.logs_dir / "ahe-session" / "usage.jsonl" + ) + simulate = loop.run_in_executor( + None, load(spec["simulate"]), task, conversation, workspace, user_params + ) + waiter = asyncio.ensure_future(started.wait()) + verdict = None + error = None + try: + await asyncio.wait({simulate, waiter}, return_when=asyncio.FIRST_COMPLETED) + if started.is_set() and not stopped: + codex = asyncio.ensure_future( + super().run(first["text"], environment, context) + ) + verdict = await simulate + if not isinstance(verdict, dict): + raise TypeError( + f"simulate returned {type(verdict).__name__}, not a dict" + ) + await stop_actor() # Actor failures cannot become a successful user score. + except BaseException as exc: + error = exc + raise + finally: + waiter.cancel() + conversation.end() + try: + await stop_actor() + except BaseException as cleanup_error: + if error is None: + error = cleanup_error + raise + finally: + workspace.close() + conversation.events() + self._leave(verdict, conversation, error) + + def _leave( + self, + verdict: dict | None, + conversation: Conversation, + error: BaseException | None, + ) -> None: + """The user's files, at the top of the agent's log directory (Hermit's log curation copies top-level files).""" + kept = {k: v for k, v in (verdict or {}).items() if k != "files"} + if error is not None: + kept["error"] = f"{type(error).__name__}: {error}" + said = [ + e + for e in conversation.transcript + if e["from"] == "user" and e["kind"] == "message" + ] + self._user_summary = { + "score": kept.get("score"), + "rating": kept.get("rating"), + "outcome": kept.get("outcome"), + "messages": len(said), + "interrupts": sum( + 1 + for e in conversation.transcript + if e["from"] == "user" and e["kind"] == "interrupt" + ), + "inserted": sum( + 1 + for e in conversation.transcript + if e.get("kind") == "delivered" and e.get("at") == "PostToolUse" + ), + "replies": sum( + 1 for e in conversation.transcript if e.get("kind") == "reply" + ), + "error": kept.get("error"), + } + self.logs_dir.mkdir(parents=True, exist_ok=True) + (self.logs_dir / "user-verdict.json").write_text( + json.dumps(kept, indent=1, ensure_ascii=False, default=str) + "\n" + ) + with open(self.logs_dir / "user-transcript.jsonl", "w") as f: + for entry in conversation.transcript: + f.write(json.dumps(entry, ensure_ascii=False, default=str) + "\n") + reward = self.logs_dir / "user-reward.txt" + reward.unlink(missing_ok=True) + for name, text in ((verdict or {}).get("files") or {}).items(): + if Path(str(name)).name != name or name in { + "reward.txt", + "verdict.json", + "transcript.jsonl", + }: + raise ValueError( + "user attachment name is reserved or contains a directory" + ) + (self.logs_dir / f"user-{name}").write_text(str(text)) + if kept.get("score") is not None and error is None: + score = float(kept["score"]) + if not math.isfinite(score) or not 0 <= score <= 1: + raise ValueError("user score must be finite and between 0 and 1") + reward.write_text(f"{score:g}\n") + for path in self.logs_dir.glob("user-*"): + if path.is_file(): + os.chmod(path, 0o644) + + def populate_context_post_run(self, context: AgentContext) -> None: + super().populate_context_post_run(context) + if self._user_summary is not None: + context.metadata = {**(context.metadata or {}), "user": self._user_summary} diff --git a/examples/ahe_beta/utils/processes.py b/examples/ahe_beta/utils/processes.py new file mode 100644 index 00000000..b63cf565 --- /dev/null +++ b/examples/ahe_beta/utils/processes.py @@ -0,0 +1,97 @@ +"""Stop processes created during one rollout before the terminal review snapshot. + +The environment's existing services and PID 1 remain alive. Process identity includes +start time so that a recycled PID does not inherit an exclusion from the baseline. +""" + +import os +from pathlib import Path +import signal +import time + + +def processes(): + rows = {} + for path in Path("/proc").iterdir(): + if not path.name.isdigit(): + continue + try: + fields = path.joinpath("stat").read_text().rsplit(")", 1)[1].split() + if fields[0] != "Z": + rows[int(path.name)] = (int(fields[1]), fields[19]) + except (OSError, IndexError, ValueError): + continue + return rows + + +def snapshot(): + return {str(pid): start for pid, (_, start) in processes().items()} + + +def exclusions(rows, ports): + excluded = {1} + parent = os.getpid() + while parent in rows and parent not in excluded: + excluded.add(parent) + parent = rows[parent][0] + # Services are recipe-owned, and a hot replacement may own a declared handoff port. + services = set() + for marker in Path("/run/ahe-services").glob("*.pid"): + try: + services.add(int(marker.read_text().strip())) + except (ValueError, OSError): + continue + inodes = set() + for name in ("tcp", "tcp6"): + table = Path("/proc/net") / name + if not table.exists(): + continue + for line in table.read_text().splitlines()[1:]: + fields = line.split() + if fields[3] == "0A" and int(fields[1].rsplit(":", 1)[1], 16) in ports: + inodes.add(fields[9]) + for pid in rows: + try: + for fd in Path("/proc", str(pid), "fd").iterdir(): + try: + if os.readlink(fd) in {f"socket:[{i}]" for i in inodes}: + services.add(pid) + except FileNotFoundError: + pass + except FileNotFoundError: + pass + while True: + expanded = services | { + pid for pid, (ppid, _) in rows.items() if ppid in services + } + if expanded == services: + break + services = expanded + return excluded | services + + +def quiesce(baseline, ports): + for sig in (signal.SIGTERM, signal.SIGKILL): + rows = processes() + excluded = exclusions(rows, ports) + victims = [ + pid + for pid, (_, start) in rows.items() + if pid not in excluded and baseline.get(str(pid)) != start + ] + for pid in victims: + try: + if processes().get(pid) == rows[pid]: + os.kill(pid, sig) + except ProcessLookupError: + pass + time.sleep(0.2) + rows = processes() + excluded = exclusions(rows, ports) + remaining = [ + pid + for pid, (_, start) in rows.items() + if pid not in excluded and baseline.get(str(pid)) != start + ] + if remaining: + raise RuntimeError(f"rollout processes still active: {remaining}") diff --git a/examples/ahe_beta/utils/scripted_user.py b/examples/ahe_beta/utils/scripted_user.py new file mode 100644 index 00000000..64dcb3ab --- /dev/null +++ b/examples/ahe_beta/utils/scripted_user.py @@ -0,0 +1,61 @@ +"""A scripted user, for checking the channel without a model: it inserts a message while the agent works, asks a +follow-up, interrupts, asks once more, looks at the workspace and rates the session.""" + +import json + + +def simulate(task: dict, agent, workspace, params: dict) -> dict: + replies, seen, inserted = [], [], False + agent.write("FIRST: " + task["instruction"].strip()) # starts Codex + while True: # the agent is working: watch, and insert once + reply = agent.poll(1.0) + seen += agent.events() + if reply: + replies.append(reply) + break + if not inserted and any(e["kind"] == "tool" for e in seen): + agent.write("USER-INSERT: use method B instead") + inserted = True + agent.write("USER-FOLLOWUP: now do part two") + while True: # interrupt when it starts the wrong thing + reply = agent.poll(1.0) + events = agent.events() + seen += events + if reply: + replies.append(reply) + break + if any( + e["kind"] == "tool_start" and "three" in json.dumps(e["input"]) + for e in events + ): + replies.append( + agent.interrupt("USER-INTERRUPT: wrong direction", timeout=120) + ) + break + replies.append( + {"kind": "reply", "text": agent.send("USER-FINAL: summarize", timeout=120)} + ) + seen += agent.events() + check = workspace.run("cat /app/a.txt") + return { + "score": 0.75, + "rating": 3, + "outcome": "accept_with_reservations", + "reason": "did the work, but needed an interrupt", + "issues": [ + { + "title": "ignores the user's preferred method", + "body": "had to interrupt", + "labels": ["bug"], + } + ], + "record": { + "replies": replies, + "workspace": check["stdout"], + "params": params, + "kinds_seen": sorted({e["kind"] for e in seen}), + }, + "files": { + "session.json": '{"note": "the simulator\'s own session record goes here"}\n' + }, + } diff --git a/examples/ahe_beta/utils/tests/test_acting.py b/examples/ahe_beta/utils/tests/test_acting.py new file mode 100644 index 00000000..98f8c17f --- /dev/null +++ b/examples/ahe_beta/utils/tests/test_acting.py @@ -0,0 +1,79 @@ +"""A resumed cohort reuses valid native evidence and stops on unavailable trials.""" + +import json +from pathlib import Path +import subprocess +import sys + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from acting import AheHarborAgent +from binding import write +from hermit.harbor.runner import HarborAgent +from hermit.task import RunOutput, RunUnavailable + + +def test_completed_rollout_is_reused_after_delivery_but_requires_its_evidence( + tmp_path, monkeypatch +): + adapter = tmp_path / "adapter" + adapter.mkdir() + (adapter / "ADAPTER.md").write_text("Solve the task.") + for args in ( + ["init", "-b", "main"], + ["config", "user.name", "Test"], + ["config", "user.email", "test@example.invalid"], + ["add", "."], + ["commit", "-m", "fixture"], + ): + subprocess.run( + ["git", "-C", str(adapter), *args], check=True, capture_output=True + ) + binding = tmp_path / "binding.json" + write(binding, adapter=adapter, repo=adapter, run_id="test", round_no=1) + runner = AheHarborAgent( + { + "tasks_dir": str(tmp_path / "tasks"), + "jobs_dir": str(tmp_path / "jobs"), + "binding": str(binding), + } + ) + task = {"id": "r1-user1", "ahe_session": {"round": 1}} + log = tmp_path / "job/log" + (log / "agent").mkdir(parents=True) + (log / "ahe-session").mkdir() + (log / "agent/user-verdict.json").write_text( + json.dumps( + { + "score": 0, + "usage": {"total_tokens": 7}, + } + ) + ) + calls = [] + + def trial(self, task, adapter): + calls.append(task["id"]) + return RunOutput(output={"status": "ok"}, log=str(log), tokens=13) + + monkeypatch.setattr(HarborAgent, "run", trial) + first = runner.run(task, adapter) + assert first.tokens == 20 and first.extra["actor_tokens"] == 13 + write(binding, adapter=adapter, repo=adapter, run_id="test", round_no=2) + assert runner.run(task, adapter) == first + assert calls == ["r1-user1"] + (log / "ahe-session").rmdir() + with pytest.raises(RunUnavailable, match="lost its native evidence"): + runner.run(task, adapter) + + +def test_unexpected_runner_error_is_unavailable_not_a_task_score(tmp_path, monkeypatch): + runner = AheHarborAgent({"tasks_dir": str(tmp_path)}) + + def fail(*args): + raise OSError("connection lost") + + monkeypatch.setattr(runner, "_run", fail) + with pytest.raises(RunUnavailable, match="connection lost"): + runner.run({"id": "trial"}, tmp_path) diff --git a/examples/ahe_beta/utils/tests/test_binding.py b/examples/ahe_beta/utils/tests/test_binding.py new file mode 100644 index 00000000..438fd775 --- /dev/null +++ b/examples/ahe_beta/utils/tests/test_binding.py @@ -0,0 +1,33 @@ +"""Tested adapter bindings compare content, not unrelated repository commit IDs.""" + +from pathlib import Path +import sys +import subprocess +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from binding import read, write + + +def test_binding_rejects_different_bytes_and_ignores_generated_card(tmp_path): + repo = tmp_path / "repo" + repo.mkdir() + (repo / "ADAPTER.md").write_text("Inspect and solve.") + + def git(*args): + subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True) + + git("init", "-b", "main") + git("config", "user.name", "Test") + git("config", "user.email", "test@example.invalid") + git("add", ".") + git("commit", "-m", "fixture") + binding = tmp_path / "binding.json" + expected = write(binding, adapter=repo, repo=repo, run_id="run", round_no=1) + assert read(binding, repo) == expected + (repo / ".hermit").mkdir() + (repo / ".hermit/CARD.md").write_text("Generated by the Trainer") + assert read(binding, repo) == expected + (repo / "ADAPTER.md").write_text("Changed") + with pytest.raises(ValueError, match="differs"): + read(binding, repo) diff --git a/examples/ahe_beta/utils/tests/test_channel.py b/examples/ahe_beta/utils/tests/test_channel.py new file mode 100644 index 00000000..d6561bb4 --- /dev/null +++ b/examples/ahe_beta/utils/tests/test_channel.py @@ -0,0 +1,76 @@ +"""Mailbox races and adapter hook decisions must not fabricate a successful turn.""" + +import importlib.util +import json +from pathlib import Path +import subprocess +import sys + +import pytest + +UTILS = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("ahe_channel_test", UTILS / "channel.py") +channel = importlib.util.module_from_spec(spec) +spec.loader.exec_module(channel) + + +def test_close_before_first_message_does_not_wait(tmp_path): + stopped = [] + c = channel.Conversation( + tmp_path, lambda text: None, lambda: True, lambda: stopped.append(True) + ) + c.close() + with pytest.raises(channel.ConversationClosed): + c.poll(30) + assert stopped == [True] + + +def hook(tmp_path, *, incoming, adapter=()): + for folder in ("to-agent", "to-user", "taken"): + (tmp_path / folder).mkdir(exist_ok=True) + script = tmp_path / "user_hook.py" + script.write_bytes((UTILS / "user_hook.py").read_bytes()) + script.with_suffix(".json").write_text( + json.dumps( + { + "mail": str(tmp_path), + "wait_s": 0.01, + "adapter_stop": list(adapter), + "reply_frame": "{text}", + "insert_frame": "{text}", + "interrupt_frame": "{text}", + } + ) + ) + for i, (kind, text) in enumerate(incoming): + (tmp_path / "to-agent" / f"{i:04}-{kind}.json").write_text( + json.dumps({"id": str(i), "kind": kind, "text": text}) + ) + return subprocess.run( + [sys.executable, str(script), "Stop"], + input=json.dumps({"last_assistant_message": "done"}), + text=True, + capture_output=True, + timeout=3, + ) + + +def test_end_wins_over_queued_followup(tmp_path): + result = hook(tmp_path, incoming=[("message", "continue"), ("end", "")]) + assert result.returncode == 0 and not result.stdout.strip() + assert len(list((tmp_path / "to-agent").glob("*-message.json"))) == 1 + + +def test_adapter_stop_session_is_preserved(tmp_path): + result = hook( + tmp_path, + incoming=[], + adapter=[ + {"command": 'printf \'%s\' \'{"continue":false,"stopReason":"done"}\''} + ], + ) + assert json.loads(result.stdout) == {"continue": False, "stopReason": "done"} + assert any( + json.loads(p.read_text()).get("terminal") is True + for p in (tmp_path / "to-user").glob("*.json") + ) diff --git a/examples/ahe_beta/utils/user_hook.py b/examples/ahe_beta/utils/user_hook.py new file mode 100644 index 00000000..2c034170 --- /dev/null +++ b/examples/ahe_beta/utils/user_hook.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python3 +"""The user channel, container side: three Codex hooks that carry a simulated user's messages into a running session. + + python3 user_hook.py PreToolUse | PostToolUse | Stop (registered in /.codex/hooks.json) + +Standard library only. The settings are in `user_hook.json` beside this file: `mail` (the mailbox directory, under +the agent's log directory, which Harbor shares with the host), `wait_s` (how long a Stop waits for the user), +`adapter_stop` (the adapter's own Stop commands, run here before the user hears anything). + +The mailbox: + + to-user/