Skip to content

The agent that grows with you

test: copilot-acp wire E2E: schema-validating fake ACP agent, tool flow, resume, lifecycle, error semantics

teknium120c41d1e697f
diff --git a/tests/e2e/core/providers/test_native_copilot_acp.py b/tests/e2e/core/providers/test_native_copilot_acp.py
new file mode 100644
index 00000000000..48468167470
--- /dev/null
+++ b/tests/e2e/core/providers/test_native_copilot_acp.py
@@ -0,0 +1,264 @@
+"""Copilot ACP wire conformance, part 1: the multi-call tool flow, resume, and the process lifecycle.
+
+``provider: copilot-acp`` makes Hermes spawn an external ACP agent (``copilot --acp --stdio``) per model
+call and speak the Agent Client Protocol to it over stdio. Here the agent is
+``tests/fakes/providers/copilot_acp.py``, a fake that validates every request against the published
+ACP schema and replays scripted turns. Everything on the Hermes side is real: the ``hermes chat -q``
+process, runtime resolution from ``config.yaml`` + the profile ``.env`` (``HERMES_COPILOT_ACP_COMMAND``
+/ ``HERMES_COPILOT_ACP_ARGS``), the ACP client, the agent loop, the ``read_file`` tool and ``state.db``.
+
+Contract under test (documented in ``agent/copilot_acp_client.py`` and the ACP spec):
+
+* each model call is a fresh agent process: ``initialize`` -> ``session/new`` (absolute cwd) ->
+ model selection via the advertised ``model`` config option -> ``session/prompt``; every request is
+ schema-valid;
+* ACP has no tools channel: Hermes' tools travel in the prompt text, a ``<tool_call>`` block in the
+ agent's message runs a REAL Hermes tool, and the result is in the next call's prompt;
+* ``--resume`` in a new process does NOT use ``session/load`` (even when the agent advertises it): it
+ opens a new ACP session whose prompt carries the persisted history;
+* agent-side ``session/request_permission`` is never granted (Hermes has no human channel there) and
+ ``fs/read_text_file`` is confined to the session cwd;
+* no agent process outlives the CLI, including one that ignores SIGTERM and stdin EOF.
+"""
+
+from __future__ import annotations
+
+import os
+import signal
+import sys
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Callable
+
+import pytest
+
+from tests.e2e.core.providers._native_helpers import (
+ ChatResult,
+ NativeHome,
+ assert_no_duplicate_assistant_text,
+ latest_session,
+ make_home,
+ messages,
+ run_chat,
+ session_ids,
+ tool_calls_of,
+ wait_until,
+)
+from tests.fakes.providers import copilot_acp as acp
+
+pytest.importorskip("acp.schema", reason="the fake validates against the agent-client-protocol package (acp extra)")
+
+pytestmark = [
+ pytest.mark.skipif(not sys.platform.startswith("linux"), reason="POSIX launcher script + /proc pid checks"),
+ pytest.mark.live_system_guard_bypass,
+]
+
+MODELS = ["fake-model-a", "fake-model-b"]
+CONFIGURED_MODEL = "fake-model-b" # NOT the agent's default: selection must happen on the wire
+CANARY = "CANARY-7731-acp"
+SECRET = "OUTSIDE-CWD-SECRET-5512"
+Q1 = "Read canary.txt and tell me what it says (Q1-marker)."
+Q2 = "Now summarise what you found (Q2-marker)."
+FINAL_ONE = f"The file says {CANARY} (FINAL-ONE)"
+FINAL_TWO = "Summary: the canary was read (FINAL-TWO)"
+LATE_TEXT = "LATE-ANSWER-65788"
+
+
+class KnownSymptom(AssertionError):
+ """Raised ONLY for a tracked bug's exact symptom, so a strict xfail cannot hide an unrelated failure."""
+
+
+KNOWN: dict[str, str] = {
+ "late_chunk": "#65788 agent_message_chunk emitted after the session/prompt result is dropped",
+}
+
+
+@dataclass
+class Scenario:
+ nh: NativeHome
+ fake: acp.AcpFake
+ runs: list[ChatResult] = field(default_factory=list)
+ extra: dict[str, Any] = field(default_factory=dict)
+
+
+def _home(root: Path, turns: list[list[dict[str, Any]]], **fake_kw: Any) -> Scenario:
+ fake = acp.AcpFake(root / "acp", turns, models=MODELS, **fake_kw)
+ nh = make_home(root, {"provider": "copilot-acp", "default": CONFIGURED_MODEL}, env_file=fake.env())
+ return Scenario(nh, fake)
+
+
+def _alive(pid: int) -> bool:
+ """True while ``pid`` is a live (non-zombie) process."""
+ try:
+ with open(f"/proc/{pid}/stat", encoding="utf-8") as fh:
+ return fh.read().rsplit(")", 1)[1].split()[0] != "Z"
+ except (FileNotFoundError, ProcessLookupError, IndexError):
+ return False
+
+
+def _reap(fake: acp.AcpFake) -> None:
+ """Teardown: SIGKILL any fake agent this scenario spawned that is still alive (by recorded pid)."""
+ for pid in fake.pids():
+ if _alive(pid):
+ os.kill(pid, signal.SIGKILL)
+
+
+# ── scenarios (independent; run concurrently in the module fixture) ──────────────────────────
+
+
+def _flow(root: Path) -> Scenario:
+ """Turn 1 (two model calls): agent-side permission + a Hermes read_file call, then fs reads + the
+ answer. Turn 2: ``--resume`` in a new process. The agent ignores SIGTERM and stdin EOF."""
+ project = NativeHome(root).project
+ turns = [
+ [acp.tool_call("agent-native-1", "run shell", kind="execute"), acp.permission("agent-native-1"),
+ acp.message(acp.hermes_tool_call("call_rf_1", "read_file", {"path": str(project / "canary.txt")}))],
+ [acp.fs_read(str(project / "canary.txt")), acp.fs_read(str(root / "outside" / "secret.txt")),
+ acp.thought("REASONING-ONE: the tool result names the canary"), acp.message(FINAL_ONE)],
+ [acp.message(FINAL_TWO)],
+ ]
+ sc = _home(root, turns, ignore_sigterm=True)
+ (sc.nh.project / "canary.txt").write_text(CANARY + "\n", encoding="utf-8")
+ (root / "outside").mkdir()
+ (root / "outside" / "secret.txt").write_text(SECRET + "\n", encoding="utf-8")
+ sc.runs.append(run_chat(sc.nh, Q1))
+ if sc.runs[0].returncode == 0 and session_ids(sc.nh):
+ sc.extra["turn1_pids"] = sc.fake.pids()
+ sc.runs.append(run_chat(sc.nh, Q2, resume=latest_session(sc.nh)))
+ return sc
+
+
+def _late(root: Path) -> Scenario:
+ """The agent answers ``session/prompt`` first and streams the message chunk 250 ms later."""
+ sc = _home(root, [[acp.result(), acp.message(LATE_TEXT, delay=0.25)], [acp.message("SECOND-TRY-65788")]])
+ sc.runs.append(run_chat(sc.nh, "Say the late answer."))
+ return sc
+
+
+SCENARIOS: dict[str, Callable[[Path], Scenario]] = {"flow": _flow, "late": _late}
+
+
[email protected](scope="module")
+def outcomes(tmp_path_factory: pytest.TempPathFactory):
+ base = tmp_path_factory.mktemp("copilot_acp")
+ with ThreadPoolExecutor(max_workers=len(SCENARIOS)) as pool:
+ futures = {name: pool.submit(fn, base / name) for name, fn in SCENARIOS.items()}
+ done = {name: fut.result() for name, fut in futures.items()}
+ yield done
+ for sc in done.values():
+ _reap(sc.fake)
+
+
+def _flow_ok(outcomes: dict[str, Scenario]) -> Scenario:
+ sc = outcomes["flow"]
+ assert len(sc.runs) == 2 and all(r.returncode == 0 for r in sc.runs), "\n\n".join(r.describe() for r in sc.runs)
+ return sc
+
+
+def _calls(fake: acp.AcpFake) -> dict[int, list[dict[str, Any]]]:
+ """Inbound client requests grouped per agent process (pid), in arrival order."""
+ grouped: dict[int, list[dict[str, Any]]] = {}
+ for rec in fake.inbound():
+ if rec["msg"] and rec["msg"].get("method"):
+ grouped.setdefault(rec["pid"], []).append(rec)
+ return grouped
+
+
+# ── tests ──────────────────────────────────────────────────────────────────────────────────────
+
+
+def test_hermes_tool_call_round_trips_through_acp_and_persists(outcomes):
+ """A ``<tool_call>`` in the agent's message runs Hermes' real read_file; the result reaches the
+ NEXT call's prompt; the CLI prints the answer; state.db pairs the call and result by id."""
+ sc = _flow_ok(outcomes)
+ assert FINAL_ONE in sc.runs[0].stdout, sc.runs[0].describe()
+ prompts = sc.fake.main_prompts()
+ assert len(prompts) == 3, f"expected 3 model calls (tool, answer, resumed answer), got {len(prompts)}"
+ first, second = acp.prompt_text(prompts[0]), acp.prompt_text(prompts[1])
+ assert '"name": "read_file"' in first, "read_file schema was not offered through the prompt tool bridge"
+ assert CANARY not in first, "the canary leaked into the prompt before the tool ran"
+ assert CANARY in second and second.index(Q1) < second.index(CANARY), (
+ "the read_file result must follow the user turn in the next call's prompt")
+
+ rows = messages(sc.nh, latest_session(sc.nh))
+ calls = [(r, tc) for r in rows if r["role"] == "assistant" for tc in tool_calls_of(r)]
+ assert [(tc["id"], tc["function"]["name"]) for _, tc in calls] == [("call_rf_1", "read_file")], calls
+ results = [r for r in rows if r["role"] == "tool"]
+ assert [r["tool_call_id"] for r in results] == ["call_rf_1"] and CANARY in results[0]["content"], results
+ finals = [r for r in rows if r["role"] == "assistant" and FINAL_ONE in (r["content"] or "")]
+ assert len(finals) == 1 and rows.index(finals[0]) > rows.index(results[0]), rows
+ assert "<tool_call>" not in "".join(r["content"] or "" for r in rows if r["role"] == "assistant"), (
+ "raw tool-call bridge markup was persisted as assistant text")
+ assert "REASONING-ONE" in (finals[0].get("reasoning") or ""), "agent_thought_chunk text was not kept as reasoning"
+
+
+def test_every_request_is_schema_valid_and_selects_the_configured_model(outcomes):
+ """Per process: initialize -> session/new (absolute project cwd) -> set_config_option(model) ->
+ session/prompt on the issued sessionId; zero requests the fake had to reject."""
+ sc = _flow_ok(outcomes)
+ assert sc.fake.invalid() == [], f"requests rejected by the ACP schema: {sc.fake.invalid()}"
+ grouped = _calls(sc.fake)
+ assert len(grouped) == 3, f"one agent process per model call expected, got {len(grouped)}"
+ for pid, recs in grouped.items():
+ methods = [r["msg"]["method"] for r in recs if r["msg"]["method"] not in ("session/cancel",)]
+ assert methods == ["initialize", "session/new", "session/set_config_option", "session/prompt"], (pid, methods)
+ init, new, select, prompt = (r["msg"]["params"] for r in recs[:4])
+ assert init["protocolVersion"] == acp.PROTOCOL_VERSION
+ assert Path(new["cwd"]) == sc.nh.project.resolve(), new
+ assert select["value"] == CONFIGURED_MODEL and select["configId"] == "model", select
+ assert select["sessionId"] == prompt["sessionId"], (select, prompt)
+
+
+def test_agent_permission_is_never_granted_and_fs_reads_stay_in_cwd(outcomes):
+ """The agent's own permission request is refused; fs/read_text_file inside the session cwd returns
+ the file, outside it returns a JSON-RPC error and no content."""
+ sc = _flow_ok(outcomes)
+ outcomes_seen = [r["msg"]["result"]["outcome"] for r in sc.fake.records() if r.get("kind") == "permission_outcome"]
+ assert len(outcomes_seen) == 1, sc.fake.records()
+ assert outcomes_seen[0].get("outcome") != "selected", f"Hermes granted an agent-side permission: {outcomes_seen}"
+ reads = [r for r in sc.fake.records() if r.get("kind") == "fs_read_result"]
+ assert len(reads) == 2 and not any(r["errors"] for r in reads), reads
+ inside, outside = reads[0]["msg"], reads[1]["msg"]
+ assert CANARY in inside["result"]["content"], inside
+ assert "error" in outside and SECRET not in str(outside), f"fs read escaped the session cwd: {outside}"
+
+
+def test_resume_opens_a_fresh_acp_session_seeded_with_persisted_history(outcomes):
+ """``--resume`` in a new CLI process: a new agent process, ``session/new`` (never ``session/load``,
+ although the agent advertises loadSession), and a prompt carrying turn 1 then the new question."""
+ sc = _flow_ok(outcomes)
+ assert FINAL_TWO in sc.runs[1].stdout, sc.runs[1].describe()
+ resumed_pids = [pid for pid in _calls(sc.fake) if pid not in sc.extra["turn1_pids"]]
+ assert len(resumed_pids) == 1, "the resumed turn must run in its own agent process"
+ assert sc.fake.inbound("session/load") == [], "Hermes sent session/load; the contract is a seeded session/new"
+ text = acp.prompt_text(sc.fake.main_prompts()[-1])
+ order = [text.find(s) for s in (Q1, CANARY, FINAL_ONE, Q2)]
+ assert -1 not in order and order == sorted(order), f"resumed prompt lost or reordered history: {order}"
+ sessions = session_ids(sc.nh)
+ rows = messages(sc.nh, sessions[-1])
+ assert len(sessions) == 1 and [r["content"] for r in rows if r["role"] == "user"] == [Q1, Q2], rows
+ assert_no_duplicate_assistant_text(rows, FINAL_ONE)
+ assert_no_duplicate_assistant_text(rows, FINAL_TWO)
+
+
+def test_no_agent_process_outlives_the_cli(outcomes):
+ """Every spawned agent is gone once the CLI exits, even one ignoring SIGTERM and stdin EOF."""
+ sc = _flow_ok(outcomes)
+ pids = sc.fake.pids()
+ wedged = {r["pid"] for r in sc.fake.events("signal")}
+ assert len(pids) == 3 and wedged, "vacuity: the scenario must spawn 3 agents that ignored SIGTERM"
+ wait_until(lambda: not [p for p in pids if _alive(p)], 10.0, f"agent processes {pids} to exit")
+
+
[email protected](strict=True, raises=KnownSymptom, reason=KNOWN["late_chunk"])
+def test_message_chunk_after_prompt_result_reaches_the_user(outcomes):
+ sc = outcomes["late"]
+ run = sc.runs[0]
+ assert run.returncode == 0, run.describe()
+ assert sc.fake.invalid() == [], sc.fake.invalid()
+ rows = messages(sc.nh, latest_session(sc.nh))
+ if LATE_TEXT not in run.stdout:
+ raise KnownSymptom(f"late chunk dropped: {len(sc.fake.main_prompts())} model calls, stdout={run.stdout!r}")
+ assert_no_duplicate_assistant_text(rows, LATE_TEXT)
+ assert len(sc.fake.main_prompts()) == 1, "a delivered late chunk must not trigger an empty-response retry"
diff --git a/tests/e2e/core/providers/test_native_copilot_acp_errors.py b/tests/e2e/core/providers/test_native_copilot_acp_errors.py
new file mode 100644
index 00000000000..08626575c19
--- /dev/null
+++ b/tests/e2e/core/providers/test_native_copilot_acp_errors.py
@@ -0,0 +1,160 @@
+"""Copilot ACP wire conformance, part 2: ACP error responses and agent crashes.
+
+The agent (``tests/fakes/providers/copilot_acp.py``) answers ``session/prompt`` with JSON-RPC errors from
+the ACP / JSON-RPC 2.0 error space or dies mid-stream. Each row drives one real ``hermes chat -q`` and
+asserts the retry semantics the user sees:
+
+* transient failures (``-32603`` internal error, a crash after a partial chunk) are retried with a
+ fresh agent process and the turn then succeeds, with none of the failed attempt's text persisted;
+* ``-32000 Authentication required`` is not retried: surfaced once, one model call;
+* persistent failures (``-32602`` invalid params, repeated crashes) stop after the configured retry
+ budget (``agent.api_max_retries: 2``) and are surfaced ONCE — never a loop, never a duplicate;
+* no agent process survives the CLI in any row.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import signal
+import subprocess
+import sys
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from tests.e2e.core.providers._native_helpers import (
+ ChatResult,
+ NativeHome,
+ latest_session,
+ make_home,
+ messages,
+ run_chat,
+ wait_until,
+)
+from tests.fakes.providers import copilot_acp as acp
+
+pytest.importorskip("acp.schema", reason="the fake validates against the agent-client-protocol package (acp extra)")
+
+pytestmark = [
+ pytest.mark.skipif(not sys.platform.startswith("linux"), reason="POSIX launcher script + /proc pid checks"),
+ pytest.mark.live_system_guard_bypass,
+]
+
+API_MAX_RETRIES = 2 # _native_helpers.make_home pins agent.api_max_retries
+OK_TEXT = "RECOVERED-ANSWER-OK"
+PARTIAL = "PARTIAL-BEFORE-CRASH "
+CRASH_STDERR = "fatal: agent segfaulted (fake)"
+
+
+class KnownSymptom(AssertionError):
+ """Raised ONLY for a tracked bug's exact symptom, so a strict xfail cannot hide an unrelated failure."""
+
+
+KNOWN: dict[str, str] = {
+ "auth_remedy": "#121290 copilot-acp auth failure tells the user to run a hermes command that is not implemented",
+}
+
+
+@dataclass(frozen=True)
+class Row:
+ turns: list[list[dict[str, Any]]]
+ succeeds: bool
+ model_calls: int
+ visible: str # text the user must see exactly once (answer or the agent's error message)
+ never_persisted: tuple[str, ...] = ()
+
+
+ROWS: dict[str, Row] = {
+ "internal_error_retried": Row(
+ [[acp.rpc_error(-32603, "Internal error: upstream hiccup")], [acp.message(OK_TEXT)]],
+ succeeds=True, model_calls=2, visible=OK_TEXT, never_persisted=("upstream hiccup",)),
+ "crash_mid_stream_retried": Row(
+ [[acp.message(PARTIAL), acp.crash(3, CRASH_STDERR)], [acp.message(OK_TEXT)]],
+ succeeds=True, model_calls=2, visible=OK_TEXT, never_persisted=(PARTIAL.strip(),)),
+ "auth_required_not_retried": Row(
+ [[acp.rpc_error(-32000, "Authentication required")]] * 3,
+ succeeds=False, model_calls=1, visible="Authentication required"),
+ "invalid_params_bounded": Row(
+ [[acp.rpc_error(-32602, "Invalid params: prompt exceeds agent limit")]] * 4,
+ succeeds=False, model_calls=API_MAX_RETRIES, visible="prompt exceeds agent limit"),
+ "crash_every_time_bounded": Row(
+ [[acp.message(PARTIAL), acp.crash(3, CRASH_STDERR)]] * 4,
+ succeeds=False, model_calls=API_MAX_RETRIES, visible=CRASH_STDERR, never_persisted=(PARTIAL.strip(),)),
+}
+
+
+@dataclass
+class Outcome:
+ nh: NativeHome
+ fake: acp.AcpFake
+ run: ChatResult
+ extra: dict[str, Any] = field(default_factory=dict)
+
+
+def _alive(pid: int) -> bool:
+ try:
+ with open(f"/proc/{pid}/stat", encoding="utf-8") as fh:
+ return fh.read().rsplit(")", 1)[1].split()[0] != "Z"
+ except (FileNotFoundError, ProcessLookupError, IndexError):
+ return False
+
+
+def _drive(root: Path, row: Row) -> Outcome:
+ fake = acp.AcpFake(root / "acp", row.turns)
+ nh = make_home(root, {"provider": "copilot-acp", "default": "copilot-acp"}, env_file=fake.env())
+ return Outcome(nh, fake, run_chat(nh, "Answer the question, please."))
+
+
[email protected](scope="module")
+def outcomes(tmp_path_factory: pytest.TempPathFactory):
+ base = tmp_path_factory.mktemp("copilot_acp_errors")
+ with ThreadPoolExecutor(max_workers=len(ROWS)) as pool:
+ futures = {name: pool.submit(_drive, base / name, row) for name, row in ROWS.items()}
+ done = {name: fut.result() for name, fut in futures.items()}
+ yield done
+ for out in done.values():
+ for pid in out.fake.pids():
+ if _alive(pid):
+ os.kill(pid, signal.SIGKILL)
+
+
[email protected]("name", list(ROWS))
+def test_acp_failure_is_retried_per_semantics_and_surfaced_once(outcomes, name):
+ row, out = ROWS[name], outcomes[name]
+ run, fake = out.run, out.fake
+ assert fake.invalid() == [], f"requests rejected by the ACP schema: {fake.invalid()}"
+ assert len(fake.main_prompts()) == row.model_calls, (
+ f"{name}: {len(fake.main_prompts())} model calls, expected {row.model_calls}\n{run.describe()}")
+ assert (run.returncode == 0) is row.succeeds, run.describe()
+ assert run.stdout.count(row.visible) == 1, f"{row.visible!r} must be shown exactly once\n{run.describe()}"
+ rows = messages(out.nh, latest_session(out.nh))
+ persisted = "\n".join(r["content"] or "" for r in rows if r["role"] == "assistant")
+ for text in row.never_persisted:
+ assert text not in persisted, f"failed-attempt text {text!r} was persisted: {rows}"
+ if row.succeeds:
+ assert persisted.count(OK_TEXT) == 1, rows
+ pids = fake.pids()
+ assert len(pids) == row.model_calls, f"one agent process per model call expected: {pids}"
+ wait_until(lambda: not [p for p in pids if _alive(p)], 10.0, f"agent processes {pids} to exit")
+
+
+REMEDY_RE = re.compile(r"`(hermes [^`]+)`")
+
+
[email protected](strict=True, raises=KnownSymptom, reason=KNOWN["auth_remedy"])
+def test_auth_failure_remedy_is_an_actionable_command(outcomes):
+ """The sign-in remedy printed for an ACP ``Authentication required`` must not be a dead end: any
+ ``hermes ...`` command it names has to be implemented for this provider."""
+ out = outcomes["auth_required_not_retried"]
+ assert out.run.returncode != 0 and "Authentication required" in out.run.stdout, out.run.describe()
+ for command in REMEDY_RE.findall(out.run.stdout):
+ argv = [sys.executable, "-m", "hermes_cli.main", *command.split()[1:]]
+ proc = subprocess.run(argv, cwd=out.nh.project, env=out.nh.env(), capture_output=True, text=True,
+ timeout=60, stdin=subprocess.DEVNULL)
+ said = (proc.stdout + proc.stderr).lower()
+ if "not implemented" in said:
+ raise KnownSymptom(f"remedy {command!r} is not implemented for copilot-acp: {said.strip()[:300]}")
diff --git a/tests/fakes/providers/copilot_acp.py b/tests/fakes/providers/copilot_acp.py
new file mode 100644
index 00000000000..4a429d4f4fe
--- /dev/null
+++ b/tests/fakes/providers/copilot_acp.py
@@ -0,0 +1,460 @@
+#!/usr/bin/env python3
+"""Fake ACP agent executable standing in for ``copilot --acp --stdio`` (provider ``copilot-acp``).
+
+Hermes' ``copilot-acp`` provider spawns an external agent process per model call and speaks the
+Agent Client Protocol to it: JSON-RPC 2.0, one JSON object per line over stdio
+(https://agentclientprotocol.com/protocol/overview). This module is that process. It
+
+* answers ``<cmd> --help`` with a usage text advertising ``--acp`` (Hermes probes it before spawning);
+* validates every client request against the published ACP schema (the ``agent-client-protocol``
+ package's pydantic models, ``acp.schema``) plus the spec rules the models do not encode
+ (initialize-first, absolute ``cwd``, no custom root fields, known ``sessionId``) and REJECTS
+ malformed ones with a JSON-RPC ``-32602 Invalid params`` / ``-32600`` error, as an agent would;
+* builds every message it sends from the same schema models, so a shape drift fails here first;
+* replays a scripted turn per main-turn ``session/prompt`` (thought / message chunks with delays,
+ ``tool_call`` / ``tool_call_update``, ``session/request_permission``, ``fs/read_text_file``,
+ the ``{stopReason}`` result, JSON-RPC errors, a hard crash, chunks AFTER the result);
+* appends every inbound and outbound message, with wall-clock time and pid, to
+ ``<state>/transcript.jsonl`` (shared by every process of one scenario).
+
+Test-side API: :class:`AcpFake` (write the script, build the launcher, read the transcript) and the
+action builders (:func:`thought`, :func:`message`, ...). Run as a script it is the agent itself:
+``copilot_acp.py --acp --stdio --state <dir>``.
+"""
+
+from __future__ import annotations
+
+import fcntl
+import json
+import os
+import signal
+import sys
+import time
+from pathlib import Path
+from typing import Any
+
+from pydantic import ValidationError
+
+PROTOCOL_VERSION = 1
+TOOLS_MARKER = "Available tools"
+AUX_ANSWER = "fake-acp auxiliary answer"
+USAGE = """usage: copilot [options]
+
+Options:
+ --acp Run as an Agent Client Protocol server
+ --stdio Use stdio transport (with --acp)
+ --state <dir> (fake) scenario directory holding script.json / transcript.jsonl
+ -h, --help Show help
+"""
+
+
+# ── test-side API ────────────────────────────────────────────────────────────────────────────
+
+
+def thought(text: str, delay: float = 0.0) -> dict[str, Any]:
+ return {"type": "thought", "text": text, "delay": delay}
+
+
+def message(text: str, delay: float = 0.0) -> dict[str, Any]:
+ return {"type": "message", "text": text, "delay": delay}
+
+
+def tool_call(call_id: str, title: str, kind: str = "other", status: str = "pending") -> dict[str, Any]:
+ return {"type": "tool_call", "id": call_id, "title": title, "kind": kind, "status": status}
+
+
+def tool_update(call_id: str, status: str = "completed", text: str = "") -> dict[str, Any]:
+ return {"type": "tool_update", "id": call_id, "status": status, "text": text}
+
+
+def permission(call_id: str, title: str = "run a command") -> dict[str, Any]:
+ return {"type": "permission", "id": call_id, "title": title}
+
+
+def fs_read(path: str) -> dict[str, Any]:
+ return {"type": "fs_read", "path": path}
+
+
+def result(stop_reason: str = "end_turn") -> dict[str, Any]:
+ return {"type": "result", "stopReason": stop_reason}
+
+
+def rpc_error(code: int, msg: str, data: Any = None) -> dict[str, Any]:
+ return {"type": "error", "code": code, "message": msg, "data": data}
+
+
+def crash(exit_code: int = 1, stderr: str = "fatal: agent crashed") -> dict[str, Any]:
+ return {"type": "crash", "code": exit_code, "stderr": stderr}
+
+
+def hermes_tool_call(call_id: str, name: str, args: dict[str, Any]) -> str:
+ """Text a model behind ACP emits to call a Hermes tool (ACP has no OpenAI tools channel)."""
+ body = {"id": call_id, "type": "function", "function": {"name": name, "arguments": json.dumps(args)}}
+ return f"<tool_call>{json.dumps(body)}</tool_call>"
+
+
+class AcpFake:
+ """One scenario directory: ``script.json`` in, ``transcript.jsonl`` out, plus a launcher."""
+
+ def __init__(self, state_dir: Path, turns: list[list[dict[str, Any]]], *, models: list[str] | None = None,
+ current_model: str | None = None, ignore_sigterm: bool = False, load_session: bool = True):
+ self.state_dir = Path(state_dir)
+ self.state_dir.mkdir(parents=True, exist_ok=True)
+ script = {"turns": turns, "models": models or [], "current_model": current_model,
+ "ignore_sigterm": ignore_sigterm, "load_session": load_session}
+ (self.state_dir / "script.json").write_text(json.dumps(script), encoding="utf-8")
+ self.launcher = self.state_dir / "copilot"
+ self.launcher.write_text(
+ f'#!/bin/sh\nexec "{sys.executable}" "{Path(__file__).resolve()}" "$@"\n', encoding="utf-8")
+ self.launcher.chmod(0o755)
+
+ def env(self) -> dict[str, str]:
+ """Env vars that point Hermes' copilot-acp client at this fake."""
+ return {"HERMES_COPILOT_ACP_COMMAND": str(self.launcher),
+ "HERMES_COPILOT_ACP_ARGS": f"--acp --stdio --state {self.state_dir}"}
+
+ def records(self) -> list[dict[str, Any]]:
+ path = self.state_dir / "transcript.jsonl"
+ if not path.exists():
+ return []
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
+
+ def inbound(self, method: str | None = None) -> list[dict[str, Any]]:
+ """Client->agent messages (requests, notifications, responses), optionally one method."""
+ return [r for r in self.records() if r["dir"] == "in" and (method is None or r["msg"].get("method") == method)]
+
+ def main_prompts(self) -> list[dict[str, Any]]:
+ """Main-turn ``session/prompt`` records (those carrying Hermes' tool bridge)."""
+ return [r for r in self.inbound("session/prompt") if r.get("main")]
+
+ def invalid(self) -> list[dict[str, Any]]:
+ return [r for r in self.records() if r["dir"] == "in" and r.get("errors")]
+
+ def pids(self) -> list[int]:
+ return sorted({r["pid"] for r in self.records() if r["dir"] == "spawn"})
+
+ def events(self, kind: str) -> list[dict[str, Any]]:
+ return [r for r in self.records() if r["dir"] == kind]
+
+
+def prompt_text(record: dict[str, Any]) -> str:
+ return "".join(b.get("text", "") for b in record["msg"]["params"].get("prompt", []) if b.get("type") == "text")
+
+
+# ── agent process ────────────────────────────────────────────────────────────────────────────
+
+
+class Agent:
+ """One spawned agent process (one Hermes model call)."""
+
+ def __init__(self, state_dir: Path):
+ import acp.schema as schema # validation/building uses the published ACP models
+
+ self.s = schema
+ self.state_dir = state_dir
+ self.script = json.loads((state_dir / "script.json").read_text(encoding="utf-8"))
+ self.initialized = False
+ self.client_caps: dict[str, Any] = {}
+ self.sessions: set[str] = set()
+ self.turn: int | None = None
+ self.next_id = 1000
+ self.request_schemas = {
+ "initialize": schema.InitializeRequest,
+ "session/new": schema.NewSessionRequest,
+ "session/load": schema.LoadSessionRequest,
+ "session/prompt": schema.PromptRequest,
+ "session/set_model": schema.SetSessionModelRequest,
+ "session/set_config_option": schema.SetSessionConfigOptionSelectRequest,
+ "session/cancel": schema.CancelNotification,
+ }
+ self.handlers = {
+ "initialize": self._initialize, "session/new": self._new_session, "session/load": self._load_session,
+ "session/set_model": self._ack, "session/set_config_option": self._set_config_option,
+ "session/prompt": self._prompt,
+ }
+
+ # transcript + wire ------------------------------------------------------------------------
+
+ def log(self, direction: str, msg: Any = None, **extra: Any) -> None:
+ rec = {"t": time.time(), "pid": os.getpid(), "turn": self.turn, "dir": direction, "msg": msg, **extra}
+ with open(self.state_dir / "transcript.jsonl", "a", encoding="utf-8") as fh:
+ fh.write(json.dumps(rec) + "\n")
+
+ def send(self, msg: dict[str, Any]) -> None:
+ self.log("out", msg)
+ sys.stdout.write(json.dumps(msg) + "\n")
+ sys.stdout.flush()
+
+ def dump(self, model: Any) -> dict[str, Any]:
+ return model.model_dump(by_alias=True, exclude_none=True, mode="json")
+
+ def reply(self, msg_id: Any, result_model: Any) -> None:
+ body = result_model if isinstance(result_model, dict) or result_model is None else self.dump(result_model)
+ self.send({"jsonrpc": "2.0", "id": msg_id, "result": body})
+
+ def error(self, msg_id: Any, code: int, text: str, data: Any = None) -> None:
+ err = {"code": code, "message": text, **({"data": data} if data is not None else {})}
+ self.send({"jsonrpc": "2.0", "id": msg_id, "error": err})
+
+ def update(self, session_id: str, update_model: Any) -> None:
+ note = self.s.SessionNotification(session_id=session_id, update=update_model)
+ self.send({"jsonrpc": "2.0", "method": "session/update", "params": self.dump(note)})
+
+ def read(self) -> dict[str, Any] | None:
+ line = sys.stdin.readline()
+ if not line:
+ return None
+ try:
+ msg = json.loads(line)
+ except json.JSONDecodeError as exc:
+ self.log("in", line.rstrip("\n"), errors=[f"parse error: {exc}"])
+ self.error(None, -32700, "Parse error")
+ return {}
+ return msg
+
+ # validation -------------------------------------------------------------------------------
+
+ def validate(self, msg: dict[str, Any]) -> list[str]:
+ """Spec violations of one client request/notification (empty list = valid)."""
+ errors: list[str] = []
+ if msg.get("jsonrpc") != "2.0":
+ errors.append("jsonrpc must be '2.0'")
+ method = msg.get("method")
+ if "id" in msg and not isinstance(msg["id"], (int, str)):
+ errors.append("id must be a string or integer")
+ model = self.request_schemas.get(method)
+ if model is None:
+ return errors
+ params = msg.get("params")
+ try:
+ parsed = model.model_validate(params)
+ except ValidationError as exc:
+ return errors + [f"schema: {e['loc']} {e['msg']}" for e in exc.errors()]
+ allowed = {f.alias or name for name, f in model.model_fields.items()}
+ errors += [f"custom root field {k!r} (spec: use _meta)" for k in sorted(set(params) - allowed)]
+ if method != "initialize" and not self.initialized:
+ errors.append("request before initialize")
+ if method in ("session/new", "session/load") and not os.path.isabs(parsed.cwd):
+ errors.append("cwd must be an absolute path")
+ sid = getattr(parsed, "session_id", None)
+ if method not in ("session/load",) and sid is not None and sid not in self.sessions:
+ errors.append(f"unknown sessionId {sid!r}")
+ return errors
+
+ # request handlers -------------------------------------------------------------------------
+
+ def _initialize(self, msg_id: Any, params: dict[str, Any]) -> None:
+ self.initialized = True
+ self.client_caps = params.get("clientCapabilities") or {}
+ caps = self.s.AgentCapabilities(load_session=bool(self.script.get("load_session")))
+ self.reply(msg_id, self.s.InitializeResponse(
+ protocol_version=PROTOCOL_VERSION, agent_capabilities=caps, auth_methods=[],
+ agent_info=self.s.Implementation(name="fake-copilot", title="Fake Copilot", version="1.0.0")))
+
+ def _session_response(self, session_id: str) -> Any:
+ models = self.script.get("models") or []
+ options = None
+ if models:
+ current = self.script.get("current_model") or models[0]
+ options = [self.s.SessionConfigOptionSelect(
+ id="model", name="Model", category="model", type="select", current_value=current,
+ options=[self.s.SessionConfigSelectOption(value=m, name=m) for m in models])]
+ return self.s.NewSessionResponse(session_id=session_id, config_options=options)
+
+ def _new_session(self, msg_id: Any, params: dict[str, Any]) -> None:
+ session_id = f"fake-sess-{os.getpid()}-{len(self.sessions) + 1}"
+ self.sessions.add(session_id)
+ self.reply(msg_id, self._session_response(session_id))
+
+ def _load_session(self, msg_id: Any, params: dict[str, Any]) -> None:
+ self.sessions.add(params["sessionId"])
+ self.reply(msg_id, self.s.LoadSessionResponse())
+
+ def _ack(self, msg_id: Any, params: dict[str, Any]) -> None:
+ self.reply(msg_id, {})
+
+ def _set_config_option(self, msg_id: Any, params: dict[str, Any]) -> None:
+ models = self.script.get("models") or []
+ if params.get("configId") != "model" or params.get("value") not in models:
+ self.error(msg_id, -32602, "Invalid params", {"reason": "unknown config option or value"})
+ return
+ self.script["current_model"] = params["value"]
+ self.reply(msg_id, self.s.SetSessionConfigOptionResponse(config_options=self._session_response("x").config_options))
+
+ def _claim_turn(self) -> int:
+ """Next scripted turn index, shared across every process of the scenario (file lock)."""
+ with open(self.state_dir / "turn.counter", "a+", encoding="utf-8") as fh:
+ fcntl.flock(fh, fcntl.LOCK_EX)
+ fh.seek(0)
+ index = int(fh.read().strip() or 0)
+ fh.seek(0)
+ fh.truncate()
+ fh.write(str(index + 1))
+ return index
+
+ def _prompt(self, msg_id: Any, params: dict[str, Any]) -> None:
+ text = "".join(b.get("text", "") for b in params["prompt"] if b.get("type") == "text")
+ session_id = params["sessionId"]
+ if TOOLS_MARKER not in text: # auxiliary call (title/summary): never consumes a scripted turn
+ self.update(session_id, self._chunk("agent_message_chunk", AUX_ANSWER))
+ self.reply(msg_id, self.s.PromptResponse(stop_reason="end_turn"))
+ return
+ turns = self.script.get("turns") or []
+ index = self._claim_turn()
+ self.turn = index
+ self.log("turn", {"index": index})
+ actions = turns[index] if index < len(turns) else [message("(fake-acp: script exhausted)")]
+ replied = False
+ for action in actions:
+ replied = self._run_action(action, msg_id, session_id) or replied
+ if not replied:
+ self.reply(msg_id, self.s.PromptResponse(stop_reason="end_turn"))
+
+ # scripted actions -------------------------------------------------------------------------
+
+ def _chunk(self, kind: str, text: str) -> Any:
+ cls = {"agent_message_chunk": self.s.AgentMessageChunk, "agent_thought_chunk": self.s.AgentThoughtChunk}[kind]
+ return cls(session_update=kind, content=self.s.TextContentBlock(type="text", text=text))
+
+ def _run_action(self, action: dict[str, Any], msg_id: Any, session_id: str) -> bool:
+ """Perform one scripted action; True when it answered the pending ``session/prompt``."""
+ if action.get("delay"):
+ time.sleep(float(action["delay"]))
+ return bool(self._actions[action["type"]](self, action, msg_id, session_id))
+
+ def _a_thought(self, action, msg_id, session_id):
+ self.update(session_id, self._chunk("agent_thought_chunk", action["text"]))
+
+ def _a_message(self, action, msg_id, session_id):
+ self.update(session_id, self._chunk("agent_message_chunk", action["text"]))
+
+ def _a_tool_call(self, action, msg_id, session_id):
+ self.update(session_id, self.s.ToolCallStart(
+ session_update="tool_call", tool_call_id=action["id"], title=action["title"], kind=action["kind"],
+ status=action["status"]))
+
+ def _a_tool_update(self, action, msg_id, session_id):
+ content = None
+ if action.get("text"):
+ content = [self.s.ContentToolCallContent(
+ type="content", content=self.s.TextContentBlock(type="text", text=action["text"]))]
+ self.update(session_id, self.s.ToolCallProgress(
+ session_update="tool_call_update", tool_call_id=action["id"], status=action["status"], content=content))
+
+ def _a_permission(self, action, msg_id, session_id):
+ req = self.s.RequestPermissionRequest(
+ session_id=session_id,
+ tool_call=self.s.ToolCallUpdate(tool_call_id=action["id"], title=action["title"], kind="execute"),
+ options=[self.s.PermissionOption(option_id="allow-once", name="Allow once", kind="allow_once"),
+ self.s.PermissionOption(option_id="reject-once", name="Reject", kind="reject_once")])
+ response = self._client_request("session/request_permission", self.dump(req))
+ self._check_response(response, self.s.RequestPermissionResponse, "permission_outcome")
+
+ def _a_fs_read(self, action, msg_id, session_id):
+ if not (self.client_caps.get("fs") or {}).get("readTextFile"):
+ self.log("fs_skipped", {"reason": "client did not advertise fs.readTextFile"})
+ return
+ req = self.s.ReadTextFileRequest(session_id=session_id, path=action["path"])
+ response = self._client_request("fs/read_text_file", self.dump(req))
+ self._check_response(response, self.s.ReadTextFileResponse, "fs_read_result")
+
+ def _a_result(self, action, msg_id, session_id):
+ self.reply(msg_id, self.s.PromptResponse(stop_reason=action["stopReason"]))
+ return True
+
+ def _a_error(self, action, msg_id, session_id):
+ self.error(msg_id, int(action["code"]), action["message"], action.get("data"))
+ return True
+
+ def _a_crash(self, action, msg_id, session_id):
+ self.log("crash", {"code": action["code"]})
+ sys.stderr.write(action["stderr"] + "\n")
+ sys.stderr.flush()
+ os._exit(int(action["code"]))
+
+ _actions = {"thought": _a_thought, "message": _a_message, "tool_call": _a_tool_call, "tool_update": _a_tool_update,
+ "permission": _a_permission, "fs_read": _a_fs_read, "result": _a_result, "error": _a_error,
+ "crash": _a_crash}
+
+ def _client_request(self, method: str, params: dict[str, Any]) -> dict[str, Any] | None:
+ self.next_id += 1
+ req_id = self.next_id
+ self.send({"jsonrpc": "2.0", "id": req_id, "method": method, "params": params})
+ while (msg := self.read()) is not None:
+ if msg.get("id") == req_id and "method" not in msg:
+ return msg
+ self.dispatch(msg)
+ return None
+
+ def _check_response(self, response: dict[str, Any] | None, model: Any, kind: str) -> None:
+ errors: list[str] = []
+ if response is None:
+ errors.append("client closed stdin before answering")
+ elif "result" in response:
+ try:
+ model.model_validate(response["result"])
+ except ValidationError as exc:
+ errors += [f"schema: {e['loc']} {e['msg']}" for e in exc.errors()]
+ elif not isinstance((response or {}).get("error"), dict):
+ errors.append("response carries neither result nor error")
+ self.log("in", response, kind=kind, errors=errors)
+
+ # loop -------------------------------------------------------------------------------------
+
+ def dispatch(self, msg: dict[str, Any]) -> None:
+ method = msg.get("method")
+ errors = self.validate(msg) if method else ["unsolicited response"]
+ main = method == "session/prompt" and TOOLS_MARKER in "".join(
+ b.get("text", "") for b in ((msg.get("params") or {}).get("prompt") or []) if isinstance(b, dict))
+ self.log("in", msg, errors=errors, main=main)
+ if "id" not in msg or not method:
+ return # notification (session/cancel) or stray response
+ if errors:
+ code = -32600 if errors == ["request before initialize"] else -32602
+ self.error(msg["id"], code, "Invalid params" if code == -32602 else "Invalid request", {"errors": errors})
+ return
+ handler = self.handlers.get(method)
+ if handler is None:
+ self.error(msg["id"], -32601, f"Method not found: {method}")
+ return
+ handler(msg["id"], msg.get("params") or {})
+
+ def serve(self) -> int:
+ self.log("spawn", {"argv": sys.argv[1:], "cwd": os.getcwd()})
+ while (msg := self.read()) is not None:
+ if msg:
+ self.dispatch(msg)
+ if self.script.get("ignore_sigterm"):
+ # A wedged agent: ignores SIGTERM AND stdin EOF; only SIGKILL ends it.
+ self.log("wedged", {"reason": "stdin closed; ignoring EOF"})
+ while True:
+ time.sleep(3600)
+ self.log("exit", {"reason": "stdin closed"})
+ return 0
+
+
+def _install_signals(agent: Agent) -> None:
+ def _on_term(signum, _frame):
+ if agent.script.get("ignore_sigterm"):
+ agent.log("signal", {"signal": signum, "ignored": True})
+ return
+ agent.log("exit", {"reason": f"signal {signum}"})
+ os._exit(0)
+
+ signal.signal(signal.SIGTERM, _on_term)
+
+
+def main(argv: list[str]) -> int:
+ if not argv or "-h" in argv or "--help" in argv:
+ sys.stdout.write(USAGE)
+ return 0
+ if "--acp" not in argv or "--state" not in argv:
+ sys.stderr.write("error: unknown option; this fake only runs with --acp --stdio --state <dir>\n")
+ return 1
+ agent = Agent(Path(argv[argv.index("--state") + 1]))
+ _install_signals(agent)
+ return agent.serve()
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))