From 5d02ca863e2494dd20957a90f7b4e12442b8ecf5 Mon Sep 17 00:00:00 2001 From: Raymond Chen Date: Sun, 15 Nov 2026 05:13:32 +0000 Subject: [PATCH 1/2] feat(acp): ClaudeHarness, claude-agent-acp on the shared runtime with per-session setup (not routed) --- .../modules/claude-code-provider.md | 5 +- docs/system-specs/modules/providers.md | 6 +- src/kiro_crew/acp/claude_shared_session.py | 127 +++++ src/kiro_crew/acp/harness/__init__.py | 7 +- src/kiro_crew/acp/harness/base.py | 64 +++ src/kiro_crew/acp/harness/claude.py | 441 ++++++++++++++---- src/kiro_crew/acp/runtime_class.py | 6 + src/kiro_crew/acp/runtime_session_create.py | 102 +++- src/kiro_crew/acp/runtime_session_load.py | 81 +++- src/kiro_crew/acp/runtime_session_registry.py | 17 +- src/kiro_crew/acp/runtime_session_setup.py | 27 +- test/test_acp_harness_contract.py | 44 +- test/test_claude_shared_runtime.py | 428 +++++++++++++++++ test/test_runtime_bindings.py | 18 +- 14 files changed, 1245 insertions(+), 128 deletions(-) create mode 100644 src/kiro_crew/acp/claude_shared_session.py create mode 100644 test/test_claude_shared_runtime.py diff --git a/docs/system-specs/modules/claude-code-provider.md b/docs/system-specs/modules/claude-code-provider.md index 067d9bc9fc0f..568c4714697b 100644 --- a/docs/system-specs/modules/claude-code-provider.md +++ b/docs/system-specs/modules/claude-code-provider.md @@ -950,7 +950,8 @@ claude-agent-acp reports Claude Code's TodoWrite or Task* list as a legacy ACP ` update (Crew declares no `clientCapabilities.plan`): the whole list on every change, `entries: []` once it is gone, and no tool row. Claude Code 2.1.325 offers no checklist tool in the adapter's SDK mode unless `CLAUDE_CODE_ENABLE_TODO_TOOLS` is set, so -`ClaudeLaunch._apply_env_defaults` sets it to `1` (`CLAUDE_TODO_TOOLS_ENV`) on a +`harness.claude._apply_claude_env_defaults` (called by `ClaudeLaunch` and +`ClaudeHarness`'s `apply_spawn_env`) sets it to `1` (`CLAUDE_TODO_TOOLS_ENV`) on a backend in `ACP_BACKENDS_PLAN_CHECKLIST` (claude) when the spawn environment does not name it. A value already there (the gateway's environment, `agent.env`, `extra_env`), an empty one included, is the operator's and is kept, and a Claude Code settings file's @@ -978,7 +979,7 @@ Frames: `test/fixtures/acp_frames/claude/plan-checklist.jsonl` and Claude Code's recent models default the thinking display to `omitted`, so a turn streams no `agent_thought_chunk`. claude-agent-acp 0.107.0 reads `CLAUDE_CODE_THINKING_DISPLAY` and `MAX_THINKING_TOKENS` from its process environment -at `session/new` (0.94.0 reads only the budget), so `ClaudeLaunch._apply_env_defaults` +at `session/new` (0.94.0 reads only the budget), so `_apply_claude_env_defaults` sets `CLAUDE_CODE_THINKING_DISPLAY=summarized` (`CLAUDE_THINKING_DISPLAY_ENV`) on a backend in `ACP_BACKENDS_SUMMARIZED_THINKING`, by the checklist default's rule. A settings file's `env` never reaches the adapter. Summarized thinking bills the full diff --git a/docs/system-specs/modules/providers.md b/docs/system-specs/modules/providers.md index ced532651e41..ac82b7951b50 100644 --- a/docs/system-specs/modules/providers.md +++ b/docs/system-specs/modules/providers.md @@ -1645,8 +1645,10 @@ adapted runtime harness neither bypasses the bound nor changes the Kiro path. the server as the unrestricted one of the two. `session_key` and `channel_id` ride the elements because a codex stdio server starts from `env_clear()` plus an allowlist and can learn its session no other way. `permission_surface_owned` is - False: this runtime authors no native permission file, so a mirror in claude's - class fails closed here rather than delivering tools Crew's gate cannot see. The + the harness's answer for this session: False wherever the runtime authors no + native permission file, so a mirror in claude's class fails closed there rather + than delivering tools Crew's gate cannot see; `ClaudeHarness` answers True only + for a session whose own settings seed governs its permission surface. The harness still narrows transports afterwards (`session_mcp_servers`), which is the last word on what this session's handshake advertised. diff --git a/src/kiro_crew/acp/claude_shared_session.py b/src/kiro_crew/acp/claude_shared_session.py new file mode 100644 index 000000000000..ac9e49435b51 --- /dev/null +++ b/src/kiro_crew/acp/claude_shared_session.py @@ -0,0 +1,127 @@ +"""One claude session's own setup on a claude-agent-acp process other sessions share. + +On ``AcpClient`` a claude session owns its process, so its setup and its checks ride +the process: the settings seed is written at spawn, the starting-mode pin talks on +the process's own pipe, and a failed pin ends the process. On the shared runtime +(:class:`kiro_crew.acp.harness.claude.ClaudeHarness`) one process serves several +sessions, so each of those steps has to be one session's, not the process's. + +:class:`ClaudeSharedSession` is that session's state. It is a ``ClaudeAcpClient`` +that never starts a process: the seed, the side-session deny rules, the floor +refusal, the envelope, the pin and the seed's teardown are the same methods the +per-session client runs, so the two paths cannot drift. What differs is where the +two transport steps of the pin go, and that is the whole of this class: + +* ``_claude_set_mode`` sends ``session/set_mode`` for THIS session on the shared + connection; +* ``_claude_stop_session`` ends THIS session with ``session/close`` and leaves the + process, which other sessions are running on, alone. + +Built per session by :meth:`ClaudeHarness.prepare_session`, in the session's own +working directory, so every session writes the seed its own folder reads. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Any, Awaitable, Callable + +from kiro_crew.acp.client_claude import ClaudeAcpClient +from kiro_crew.acp.harness import claude as claude_mod +from kiro_crew.acp.session_handle_runtime_contract import AcpRequestTimeout, AcpRuntimeError +from kiro_crew.acp.transport_errors import AcpError, AcpTimeoutError +from kiro_crew.acp.types import ACP_BACKEND_CLAUDE, METHOD_SET_MODE + + +class ClaudeSharedSession(ClaudeAcpClient): + """The state of one claude session on a shared claude-agent-acp process.""" + + # The three overrides below carry ``type: ignore[override]``: the base members are + # owner functions whose ``self`` is annotated with the base class, which mypy reads + # as a narrower receiver than a method's. The signatures are the same. + + def __init__( + self, + *, + work_dir: str | Path, + model: str, + agent: str | None, + session_key: str, + channel_id: str, + ) -> None: + super().__init__( + work_dir=work_dir, + model=model or None, + agent=agent or "kirocrew", + session_key=session_key or None, + channel_id=channel_id or None, + acp_backend=ACP_BACKEND_CLAUDE, + ) + self._shared_send: Callable[[str, dict[str, Any]], Awaitable[Any]] | None = None + self._shared_close: Callable[[], Awaitable[None]] | None = None + + async def prepare(self, argv: list[str]) -> None: + """Write this session's seed and side-session deny rules, before its request. + + The same steps, in the same order, as ``harness.claude.prepare_claude_session`` + runs for a session that owns its process, except the MCP array: on the shared + runtime the runtime's mirror builds it, told by + :meth:`ClaudeHarness.permission_surface_owned` whether this seed governs the + session. The exclusion record the envelope reads is taken here, beside the + seed that decided it. + """ + self._agent_version_read = False + self._claude_adapter_argv = tuple(argv) + installed = await asyncio.to_thread(claude_mod._claude_adapter_installed_version, argv) + self._claude_adapter_disk_version = ( + installed or claude_mod._claude_adapter_handshake_versions.get(tuple(argv), "") + ) + await self._seed_session_settings() + await self._prepare_claude_side_read_denies() + excludes_local, inline_settings = self._local_settings_exclusion() + self._session_mcp_excludes_local = excludes_local + self._session_mcp_inline_settings = inline_settings + self._refuse_claude_session_below_floor_before_spawn(installed) + + def bind_started( + self, + session_id: str, + agent_version: str, + *, + send_request: Callable[[str, dict[str, Any]], Awaitable[Any]], + close_session: Callable[[], Awaitable[None]], + ) -> None: + """Bind the session the request just created, and the two ways to reach it.""" + self._session_id = session_id + self._agent_version = agent_version + self._agent_version_read = True + self._shared_send = send_request + self._shared_close = close_session + + async def _claude_set_mode(self, session_id: str | None, mode_id: str) -> None: # type: ignore[override] + """``session/set_mode`` for this session, on the shared connection. + + The shared connection raises ``AcpRequestTimeout`` and ``AcpRuntimeError``; + they are raised here as the per-chat client's own request raises them + (``AcpTimeoutError``, ``AcpError``), which the starting-mode pin reads as a + failed pin: it then closes this session and refuses it. + """ + if self._shared_send is None: + raise AcpError("the shared claude session is not bound to its connection yet") + try: + await self._shared_send(METHOD_SET_MODE, {"sessionId": session_id, "modeId": mode_id}) + except AcpRequestTimeout as exc: + raise AcpTimeoutError(message=f"session/set_mode timed out: {exc}") from exc + except AcpRuntimeError as exc: + raise AcpError(str(exc)) from exc + + async def _claude_stop_session(self) -> None: # type: ignore[override] + """End THIS session only: other sessions share the process.""" + if self._shared_close is not None: + await self._shared_close() + + async def _kill_process(self, *, force: bool = False, exit_grace: float = 0.0) -> None: # type: ignore[override] + """Never the process: this state owns none. A step that would end it ends + this session instead.""" + await self._claude_stop_session() diff --git a/src/kiro_crew/acp/harness/__init__.py b/src/kiro_crew/acp/harness/__init__.py index 58f851e30f48..0ba16d18f81b 100644 --- a/src/kiro_crew/acp/harness/__init__.py +++ b/src/kiro_crew/acp/harness/__init__.py @@ -31,7 +31,7 @@ SpawnPlan, TeardownPolicy, ) -from kiro_crew.acp.harness.claude import ClaudeLaunch +from kiro_crew.acp.harness.claude import ClaudeHarness, ClaudeLaunch from kiro_crew.acp.harness.codex import CodexHarness from kiro_crew.acp.harness.copilot import CopilotLaunch from kiro_crew.acp.harness.deepseek import DeepseekLaunch @@ -57,6 +57,7 @@ ) __all__ = [ + "ClaudeHarness", "ClaudeLaunch", "CodexHarness", "CopilotLaunch", @@ -93,6 +94,10 @@ # a harness unreachable to its own tests, and would leave the runtime resolving # one that exists on disk but not in the table. ACP_BACKEND_CODEX: CodexHarness, + # Registered ahead of routing, for the reason above: no session is routed to + # the shared runtime for claude yet, and a process-per-session client still + # launches it through ``ClaudeLaunch`` below. + ACP_BACKEND_CLAUDE: ClaudeHarness, } diff --git a/src/kiro_crew/acp/harness/base.py b/src/kiro_crew/acp/harness/base.py index 033a4c5d200f..efb1e270d5fd 100644 --- a/src/kiro_crew/acp/harness/base.py +++ b/src/kiro_crew/acp/harness/base.py @@ -799,6 +799,70 @@ def session_request( """ return params, agent + # ── Seam 3b: per-session state (a host whose sessions carry their own setup) ── + + #: True on a host that prepares each session on its own before ``session/new`` / + #: ``session/load`` and checks it after (:meth:`prepare_session` and the seams + #: below). The runtime reads this before awaiting any of them, so a host that + #: answers False -- kiro-cli, KAS, codex -- makes no extra call at all + #: (harness-parity H13). + per_session_state: bool = False + + async def prepare_session( + self, + *, + work_dir: str | Path, + agent: str | None, + model: str, + session_key: str, + channel_id: str, + memory_mode: str, + ) -> Any: + """Prepare one session before its ``session/new`` or ``session/load`` goes out. + + Returns the session's state, handed back to every seam below, or None. + Off-loop work (a settings file this host reads per session) belongs here. + Raising refuses the start before anything is sent. Reached only where + :attr:`per_session_state` is True. + """ + return None + + def permission_surface_owned(self, state: Any) -> bool: + """Whether Crew governs this session's native permission surface, for the + mirror's array: False unless the host's own state says it does.""" + return False + + def session_meta( + self, state: Any, mcp_servers: list[dict[str, Any]], *, zero_tools: bool = False + ) -> dict[str, Any] | None: + """The ``_meta`` entries this session's request carries, built after its array, or None.""" + return None + + async def after_session_start( + self, + state: Any, + session_id: str, + resp: dict[str, Any], + *, + send_request: Callable[[str, dict[str, Any]], Awaitable[Any]], + close_session: Callable[[], Awaitable[None]], + agent_version: str = "", + ) -> None: + """Check the session that just started, before its first prompt. + + *agent_version* is the ``agentInfo.version`` the process reported at its + handshake. + + *send_request* sends a request on the shared connection and awaits its + answer; *close_session* ends THIS session only. A host that refuses the + session closes it through *close_session* and raises; it never ends the + process, which other sessions share. + """ + + async def end_session(self, state: Any) -> None: + """Release what :meth:`prepare_session` set up, once the session is over or + never started. Must not raise.""" + def holds_replayed_permission(self, session_id: str) -> bool: """Whether a permission request for *session_id* arrived inside a resume hold. diff --git a/src/kiro_crew/acp/harness/claude.py b/src/kiro_crew/acp/harness/claude.py index c89291fbed88..e36a9bc3cb7a 100644 --- a/src/kiro_crew/acp/harness/claude.py +++ b/src/kiro_crew/acp/harness/claude.py @@ -26,8 +26,19 @@ from kiro_crew import model_registry, platform_compat from kiro_crew.acp import launch as launch_mod from kiro_crew.acp.claude_settings_sources import a_source_decides_thinking -from kiro_crew.acp.harness.base import ProcessAdapter, ProcessSession, SpawnContext, SpawnPlan +from kiro_crew.acp.harness._common import MembershipHarness +from kiro_crew.acp.harness.base import ( + NotificationAliases, + ProcessAdapter, + ProcessSession, + ReclaimPolicy, + SessionExtras, + SpawnContext, + SpawnPlan, + TeardownPolicy, +) from kiro_crew.acp.transport_errors import AcpError +from kiro_crew.acp.types import METHOD_SESSION_CLOSE, METHOD_SESSION_UPDATE from kiro_crew.agent_sdk.backends import ( ACP_BACKEND_CLAUDE, ACP_BACKEND_NODE_ADAPTER_PACKAGES, @@ -50,9 +61,15 @@ "CLAUDE_THINKING_DISPLAY_DEFAULT", "CLAUDE_THINKING_DISPLAY_ENV", "CLAUDE_TODO_TOOLS_ENV", + "ClaudeHarness", "ClaudeLaunch", ] +#: The ``protocolVersion`` claude-agent-acp takes: the integer the per-session +#: client sends it too (``client_start.PROTOCOL_VERSION_CLAUDE``, which a test holds +#: equal to this one). +PROTOCOL_VERSION_CLAUDE = 1 + CLAUDE_ACP_BIN = ACP_BACKEND_PROCESS_NAMES[ACP_BACKEND_CLAUDE] # On-disk name of the Claude backend CLI. The claude-agent-acp adapter # delegates the actual model turn to @anthropic-ai/claude-agent-sdk, which @@ -364,49 +381,19 @@ async def resolve_spawn(self, ctx: SpawnContext) -> SpawnPlan: the wire will. No-op on a cold cache (first-ever session), which is why ``_apply_startup_model`` folds AGAIN after ``session/new`` has warmed it. """ - global _claude_acp_argv_cache # noqa: PLW0603 session = ctx.session assert session is not None, "claude-agent-acp is launched for one session" self._work_dir = Path(ctx.work_dir) if ctx.work_dir is not None else None session._model = model_registry.resolve_wire_model_id( session._model, model_registry_namespace(self.backend) ) - cached: tuple[list[str] | None, str] | object = _claude_acp_argv_cache - if cached is launch_mod._UNRESOLVED: - # Fenced on the resolution generation -- see ``acp.launch._resolution_generation``. - epoch = launch_mod._resolution_epoch(self.backend) - cached = await asyncio.to_thread(_resolve_claude_acp_bin) - if launch_mod._resolution_epoch(self.backend) == epoch: - _claude_acp_argv_cache = cached - claude_argv, acp_search_path = cached if isinstance(cached, tuple) else (None, "") - if not isinstance(claude_argv, list) or not claude_argv: - raise AcpError( - f"{CLAUDE_ACP_BIN} not found " - f"({describe_search_path(acp_search_path)}). Install it with " - f"'npm i -g {CLAUDE_ACP_NPM_PKG}' (or add it as a project " - f"dependency), or set CLAUDE_AGENT_ACP_BIN to its entry script." - ) - argv: list[str] = claude_argv + argv = await _resolve_claude_argv() await prepare_claude_session(cast(ClaudeProcessSession, session), argv) # Bound here rather than in AcpClient.__init__ for the same reason: the # constructor is shared with kiro-cli. if self.backend in ACP_BACKENDS_AGENT_STARTED_TURNS: session._install_idle_reader() - return SpawnPlan( - argv=argv, - spawn_label=launch_mod._adapter_spawn_label( - argv, - CLAUDE_ACP_BIN, - pkg_entry=_CLAUDE_ACP_PKG_ENTRY, - override_env="CLAUDE_AGENT_ACP_BIN", - ), - stderr_label=launch_mod._adapter_spawn_label( - argv, - "claude-acp", - pkg_entry=_CLAUDE_ACP_PKG_ENTRY, - override_env="CLAUDE_AGENT_ACP_BIN", - ), - ) + return _claude_spawn_plan(argv) async def prepare_spawn_env( self, @@ -424,54 +411,352 @@ def apply_spawn_env(self, env: dict[str, str], *, spawned_binary: str | None = N PATH for ``claude`` itself, so it is named explicitly. Only set when unset, so an operator override always wins. - Also sets the launch's environment defaults (:meth:`_apply_env_defaults`). + Also sets the launch's environment defaults (:func:`_apply_claude_env_defaults`). """ - self._apply_env_defaults(env) - if env.get("CLAUDE_CODE_EXECUTABLE"): + _apply_claude_env_defaults(env, self.backend, self._work_dir) + _point_at_claude_code(env) + + +async def _resolve_claude_argv() -> list[str]: + """The claude-agent-acp entry argv, resolved once per resolution generation. + + Shared by both drivers' launches. Raises ``AcpError`` naming the install + command when no adapter is found. + """ + global _claude_acp_argv_cache # noqa: PLW0603 + cached: tuple[list[str] | None, str] | object = _claude_acp_argv_cache + if cached is launch_mod._UNRESOLVED: + # Fenced on the resolution generation -- see ``acp.launch._resolution_generation``. + epoch = launch_mod._resolution_epoch(ACP_BACKEND_CLAUDE) + cached = await asyncio.to_thread(_resolve_claude_acp_bin) + if launch_mod._resolution_epoch(ACP_BACKEND_CLAUDE) == epoch: + _claude_acp_argv_cache = cached + claude_argv, acp_search_path = cached if isinstance(cached, tuple) else (None, "") + if not isinstance(claude_argv, list) or not claude_argv: + raise AcpError( + f"{CLAUDE_ACP_BIN} not found " + f"({describe_search_path(acp_search_path)}). Install it with " + f"'npm i -g {CLAUDE_ACP_NPM_PKG}' (or add it as a project " + f"dependency), or set CLAUDE_AGENT_ACP_BIN to its entry script." + ) + return list(claude_argv) + + +def _claude_spawn_plan(argv: list[str], **kwargs: Any) -> SpawnPlan: + """The plan for a claude-agent-acp spawn of *argv*, labelled as both drivers label it.""" + return SpawnPlan( + argv=argv, + spawn_label=launch_mod._adapter_spawn_label( + argv, + CLAUDE_ACP_BIN, + pkg_entry=_CLAUDE_ACP_PKG_ENTRY, + override_env="CLAUDE_AGENT_ACP_BIN", + ), + stderr_label=launch_mod._adapter_spawn_label( + argv, + "claude-acp", + pkg_entry=_CLAUDE_ACP_PKG_ENTRY, + override_env="CLAUDE_AGENT_ACP_BIN", + ), + **kwargs, + ) + + +def _apply_claude_env_defaults(env: dict[str, str], backend: str, work_dir: Path | None) -> None: + """Set each variable this launch defaults, unless the environment names it. + + A value already in the environment, an empty one included, is the operator's + (the gateway's own environment, ``agent.env`` or a session's ``extra_env``). + + - :data:`CLAUDE_TODO_TOOLS_ENV` ``=1`` on a backend in + ``ACP_BACKENDS_PLAN_CHECKLIST``: Claude Code then offers its checklist + tools, whose list the adapter sends as the ``plan`` the task progress bar + draws. + - :data:`CLAUDE_THINKING_DISPLAY_ENV` ``=summarized`` on a backend in + ``ACP_BACKENDS_SUMMARIZED_THINKING``, so the adapter streams the model's + thinking as text. Not when a Claude Code settings file decides thinking + (:func:`a_source_decides_thinking`: turns it off, sets its budget or + chooses its display): the adapter turns a display into an explicit + ``--thinking=adaptive`` and an explicit display, which would override + that file. Blocking: it reads those files, so it runs off the loop with + the rest of a launch's ``apply_spawn_env``. + """ + if backend in ACP_BACKENDS_PLAN_CHECKLIST: + env.setdefault(CLAUDE_TODO_TOOLS_ENV, "1") + if ( + backend not in ACP_BACKENDS_SUMMARIZED_THINKING + or CLAUDE_THINKING_DISPLAY_ENV in env + ): + return + # The child's own config directory when the environment names one. + config_dir = env.get("CLAUDE_CONFIG_DIR") + if not a_source_decides_thinking( + work_dir, config_dir=Path(config_dir) if config_dir else None + ): + env[CLAUDE_THINKING_DISPLAY_ENV] = CLAUDE_THINKING_DISPLAY_DEFAULT + + +def _point_at_claude_code(env: dict[str, str]) -> None: + """Name a native ``claude`` binary for the adapter's SDK, unless one is named.""" + if env.get("CLAUDE_CODE_EXECUTABLE"): + return + claude_exe = _resolve_claude_code_executable() + if claude_exe: + env["CLAUDE_CODE_EXECUTABLE"] = claude_exe + elif _sdk_bundles_native_binary(_claude_acp_argv_cache): + # The SDK runs its own binary; nothing is missing. + logger.debug("%s not on PATH; the adapter's SDK ships its own", CLAUDE_CODE_BIN) + else: + logger.warning( + "%s not found on PATH; the claude-agent-acp adapter will " + "fail with 'Claude native binary not found'. Set " + "CLAUDE_CODE_EXECUTABLE.", + CLAUDE_CODE_BIN, + ) + + +class ClaudeHarness(MembershipHarness): + """claude-agent-acp as one process that several sessions share (``AcpRuntime``). + + Registered so the shared runtime can drive it and so it can be tested, and not + yet a member of ``ACP_BACKENDS_ACP_RUNTIME``: no session takes this path until + the routing change names it. Each session's own setup, which a + process-per-session client does at spawn, is done per session here + (:attr:`per_session_state`), through :class:`ClaudeSharedSession`. + """ + + backend = ACP_BACKEND_CLAUDE + + #: Adapter-only RSS ceiling, in MB, over :attr:`CORE_RSS_DEPTH`. The adapter + #: alone is about 110 MB; each session's ``claude`` child and the MCP servers it + #: starts sit below it and are left out, because they grow with the number of + #: sessions, and a whole-subtree ceiling would recycle -- and so end -- every + #: chat on the process once a few were open. + CORE_RSS_CEILING_MB = 512.0 + + #: Generations below the adapter the ceiling above counts: none. + CORE_RSS_DEPTH = 0 + + per_session_state = True + + #: The process's working directory, recorded by :meth:`resolve_spawn`. + _work_dir: Path | None = None + + # ── Seam 1: spawn ── + + async def resolve_spawn(self, ctx: SpawnContext) -> SpawnPlan: + """The adapter entry argv, measured adapter-only. No seed: that is per session.""" + from kiro_crew.acp.harness.codex import _sandbox_wrapper_generations + from kiro_crew.acp.session_handle import AcpRuntimeError + + try: + argv = await _resolve_claude_argv() + except AcpError as exc: + raise AcpRuntimeError(str(exc)) from exc + # The process's own directory, which decides whether a Claude Code + # settings file there decides thinking (``_apply_claude_env_defaults``). + self._work_dir = Path(ctx.work_dir) if ctx.work_dir is not None else None + # A sandbox launcher that stays resident sits between the spawned pid and + # the adapter, so the adapter-only scope starts one generation lower. + wrapper_generations = await asyncio.to_thread( + _sandbox_wrapper_generations, ctx.sandbox_mode + ) + return _claude_spawn_plan(argv, rss_depth=self.CORE_RSS_DEPTH + wrapper_generations) + + def apply_spawn_env( + self, + env: dict[str, str], + *, + spawned_binary: str | None = None, + cli_owned_auth: bool = False, + ) -> None: + """Take kiro-cli's API key out, set the launch's environment defaults, and + name the native ``claude`` for the SDK, as the per-session launch does.""" + from kiro_crew.config import loader as loader_mod + + loader_mod.strip_kiro_cli_api_key(env) + _apply_claude_env_defaults(env, self.backend, self._work_dir) + _point_at_claude_code(env) + + @property + def verifies_agent_activation(self) -> bool: + """No: the adapter takes no ``--agent``, and its modes are permission modes.""" + return False + + # ── Seam 2: initialize ── + + @property + def protocol_version(self) -> Any: + return PROTOCOL_VERSION_CLAUDE + + @property + def client_capabilities(self) -> dict[str, Any]: + """What ``AcpClient`` declares to claude-agent-acp, unchanged.""" + from kiro_crew.acp.client_native_children import CLAUDE_CLIENT_CAPABILITIES + + return CLAUDE_CLIENT_CAPABILITIES + + # ── Seam 3: session/new and session/load ── + + async def session_extras(self, agent: str, **_kwargs: Any) -> SessionExtras: + """Empty: claude has no custom-agent channel. Its per-session payload is + the envelope (:meth:`session_meta`) and the mirrored array.""" + return SessionExtras() + + def session_mcp_servers( + self, + requested: list[dict[str, Any]], + *, + agent_capabilities: dict[str, Any], + ) -> list[dict[str, Any]]: + """The mirrored array as built: the adapter accepts every shape Crew sends.""" + return requested + + @property + def wants_session_file_on_load(self) -> bool: + """No: the adapter finds the session from its id.""" + return False + + async def prepare_session( + self, + *, + work_dir: str | Path, + agent: str | None, + model: str, + session_key: str, + channel_id: str, + memory_mode: str, + ) -> Any: + """Write THIS session's settings seed in its own folder, before its request. + + On a process-per-session client the seed is written at spawn, which on a + shared process would seed only the first session: a later one, in another + folder above all, would start in whatever mode the user's own settings name. + So it is written here, per session. Refusals (a side session with no deny + rules, an adapter below the session-options floor) raise before anything + is sent. + """ + from kiro_crew.acp.claude_shared_session import ClaudeSharedSession + + state = ClaudeSharedSession( + work_dir=work_dir, + model=model_registry.resolve_wire_model_id( + model, model_registry_namespace(self.backend) + ), + agent=agent, + session_key=session_key, + channel_id=channel_id, + ) + state.memory_mode = memory_mode + argv = await _resolve_claude_argv() + try: + await state.prepare(argv) + except BaseException: + await self.end_session(state) + raise + return state + + def permission_surface_owned(self, state: Any) -> bool: + """Whether this session's seed governs its permission surface: the mirror + withholds the whole array otherwise, as on the per-session client.""" + return bool(state is not None and state._permission_surface_governed) + + def session_meta( + self, state: Any, mcp_servers: list[dict[str, Any]], *, zero_tools: bool = False + ) -> dict[str, Any] | None: + """The ``_meta.claudeCode`` envelope the per-session client sends, for this session.""" + if state is None: + return None + # The spec's "tools": [] as the mirror's projection read it: a zero-tool + # session whose array still mounts a server is refused here. + state._spec_zero_tools = zero_tools + # The array this start sends, which the starting-mode pin reads to tell a + # session carrying Crew's tools from one with none (on the per-session + # client, ``_begin_session_report`` records it). + state._mcp_mount_servers = list(mcp_servers) + return state._harness_session_meta(mcp_servers) + + async def after_session_start( + self, + state: Any, + session_id: str, + resp: dict[str, Any], + *, + send_request: Callable[[str, dict[str, Any]], Awaitable[Any]], + close_session: Callable[[], Awaitable[None]], + agent_version: str = "", + ) -> None: + """Pin the asking mode on this session before its first prompt. + + A session that cannot be pinned is closed on its own (``session/close``) and + refused; the process and every other session on it keep running. + """ + if state is None: + return + state.bind_started( + session_id, + agent_version, + send_request=send_request, + close_session=close_session, + ) + await state._pin_starting_mode(resp) + + async def end_session(self, state: Any) -> None: + """Remove this session's seed, as the per-session client does at teardown. + + Once per session: a refused start and the teardown it triggers may both + reach here.""" + if state is None or getattr(state, "_shared_session_ended", False): return - claude_exe = _resolve_claude_code_executable() - if claude_exe: - env["CLAUDE_CODE_EXECUTABLE"] = claude_exe - elif _sdk_bundles_native_binary(_claude_acp_argv_cache): - # The SDK runs its own binary; nothing is missing. - logger.debug("%s not on PATH; the adapter's SDK ships its own", CLAUDE_CODE_BIN) - else: + state._shared_session_ended = True + try: + await state._discard_settings_seed() + except Exception: logger.warning( - "%s not found on PATH; the claude-agent-acp adapter will " - "fail with 'Claude native binary not found'. Set " - "CLAUDE_CODE_EXECUTABLE.", - CLAUDE_CODE_BIN, + "claude shared session: the settings seed was not removed", exc_info=True ) + finally: + state._reset_settings_seed_state() + + # ── Seam 4: inbound requests the host answers ── + + @property + def host_answered_methods(self) -> tuple[str, ...]: + """None: claude-agent-acp asks Crew for no connection-level callback.""" + return () + + async def answer_request(self, method: str) -> dict[str, Any]: + """Never called: :attr:`host_answered_methods` is empty.""" + raise NotImplementedError( + f"claude harness answers no inbound request, including {method!r}" + ) - def _apply_env_defaults(self, env: dict[str, str]) -> None: - """Set each variable this launch defaults, unless the environment names it. - - A value already in the environment, an empty one included, is the operator's - (the gateway's own environment, ``agent.env`` or a session's ``extra_env``). - - - :data:`CLAUDE_TODO_TOOLS_ENV` ``=1`` on a backend in - ``ACP_BACKENDS_PLAN_CHECKLIST``: Claude Code then offers its checklist - tools, whose list the adapter sends as the ``plan`` the task progress bar - draws. - - :data:`CLAUDE_THINKING_DISPLAY_ENV` ``=summarized`` on a backend in - ``ACP_BACKENDS_SUMMARIZED_THINKING``, so the adapter streams the model's - thinking as text. Not when a Claude Code settings file decides thinking - (:func:`a_source_decides_thinking`: turns it off, sets its budget or - chooses its display): the adapter turns a display into an explicit - ``--thinking=adaptive`` and an explicit display, which would override - that file. Blocking: it reads those files, so it runs off the loop with - the rest of :meth:`apply_spawn_env`. + # ── Seam 5: notification aliases ── + + @property + def notification_aliases(self) -> NotificationAliases: + """Plain ACP ``session/update`` only.""" + return NotificationAliases(session_update=(METHOD_SESSION_UPDATE,)) + + # ── Seam 6: teardown ── + + @property + def teardown(self) -> TeardownPolicy: + """``session/close``, awaited: it ends one session and keeps its record. + + Recorded on claude-agent-acp 0.94.0 + (``test/fixtures/acp_frames/claude/new-conversation-live.jsonl``): after + close the session answers ``Session not found``, and a later ``session/load`` + restores it. ``session/delete`` would remove the record, so it is not used. """ - if self.backend in ACP_BACKENDS_PLAN_CHECKLIST: - env.setdefault(CLAUDE_TODO_TOOLS_ENV, "1") - if ( - self.backend not in ACP_BACKENDS_SUMMARIZED_THINKING - or CLAUDE_THINKING_DISPLAY_ENV in env - ): - return - # The child's own config directory when the environment names one. - config_dir = env.get("CLAUDE_CONFIG_DIR") - if not a_source_decides_thinking( - self._work_dir, config_dir=Path(config_dir) if config_dir else None - ): - env[CLAUDE_THINKING_DISPLAY_ENV] = CLAUDE_THINKING_DISPLAY_DEFAULT + return TeardownPolicy(method=METHOD_SESSION_CLOSE, notification=False) + + # ── Seam 9: reclaim ── + + def reclaim_policy(self, *, max_age_secs: float, max_rss_mb: float) -> ReclaimPolicy: + """The adapter-only ceiling over :attr:`CORE_RSS_DEPTH`; age passes through. + + The operator's ``max_rss_mb`` counts the whole subtree, a different unit from + the adapter-only scope this spawn is measured over, so it is not carried over. + """ + return ReclaimPolicy(max_age_secs=max_age_secs, max_rss_mb=self.CORE_RSS_CEILING_MB) diff --git a/src/kiro_crew/acp/runtime_class.py b/src/kiro_crew/acp/runtime_class.py index 194d85587a9f..fb39bdcd0d12 100644 --- a/src/kiro_crew/acp/runtime_class.py +++ b/src/kiro_crew/acp/runtime_class.py @@ -148,6 +148,7 @@ class AcpRuntime: _start_mount_check = _rt_setup._start_mount_check # ``session/new`` end to end: ``kiro_crew.acp.runtime_session_create``. create_session = _rt_create.create_session + _create_session_with_harness_state = _rt_create._create_session_with_harness_state _collect_late_start = _rt_create._collect_late_start _teardown_late_session = _rt_create._teardown_late_session start_collectors = _rt_create.start_collectors @@ -155,6 +156,7 @@ class AcpRuntime: probe_advertised_models = _rt_create.probe_advertised_models # ``session/load`` end to end: ``kiro_crew.acp.runtime_session_load``. load_session = _rt_load.load_session + _load_session_with_harness_state = _rt_load._load_session_with_harness_state _wait_managed_mcp = _rt_load._wait_managed_mcp _park_in_start_agent = _rt_load._park_in_start_agent # The sessions held and how each leaves: ``kiro_crew.acp.runtime_session_registry``. @@ -628,6 +630,10 @@ def __init__( # binary THIS process is executing, which can differ from the one on # disk after an in-place upgrade. Empty until the handshake completes. self._agent_version = "" + # Per-session state a harness with ``per_session_state`` prepared before each + # session's request (``HarnessAdapter.prepare_session``), by session id, ended + # with the session (``HarnessAdapter.end_session``). Empty on every other host. + self._session_harness_states: dict[str, Any] = {} # Entitlement probe state (probe_advertised_models): single-flight lock # plus a short-TTL cache of the last non-empty answer. self._entitlement_probe_lock = asyncio.Lock() diff --git a/src/kiro_crew/acp/runtime_session_create.py b/src/kiro_crew/acp/runtime_session_create.py index b73561076206..caba623fe7df 100644 --- a/src/kiro_crew/acp/runtime_session_create.py +++ b/src/kiro_crew/acp/runtime_session_create.py @@ -9,19 +9,19 @@ of the method on the class or on an instance reaches every caller. Instance fields written: ``_entitlement_probe_attempt_at``, ``_entitlement_probe_result``, -``_entitlement_probe_result_at``, ``_first_session_ready``, ``_saw_delegate_launch_failure``, -``_saw_kas_engine_refusal``, ``_saw_sandbox_init_failure``, -``_session_cwds``, ``_session_inits_in_flight``, ``_session_queues``, ``_start_collectors``, ``_stderr_lines``, +``_entitlement_probe_result_at``, ``_first_session_ready``, +``_saw_delegate_launch_failure``, ``_saw_kas_engine_refusal``, +``_saw_sandbox_init_failure``, ``_session_cwds``, ``_session_harness_states``, +``_session_inits_in_flight``, ``_session_queues``, ``_start_collectors``, ``_stderr_lines``, ``recording_allowed``. -Instance fields read: ``_agent``, ``_agent_capabilities``, ``_crew_agent``, ``_dead``, -``_entitlement_probe_lock``, ``_expect_mcp_reports``, ``_fold_mcp_frame``, ``_initialized``, -``_kas_telemetry_sent``, ``_mcp_gateway_overlay``, ``_member_context``, ``_open_mcp_report``, -``_pending_init_notifications``, ``_pid``, -``_pool_lookup``, ``_process``, ``_record_tree_in_background``, -``_refuse_over_ceiling_start``, ``_remote_session_servers``, -``_remote_workspace_agents``, ``_session_label_elements``, ``_start_collect_timeout``, -``_wire_mode_id``, ``_work_dir``, +Instance fields read: ``_agent``, ``_agent_capabilities``, ``_agent_version``, +``_crew_agent``, ``_dead``, ``_entitlement_probe_lock``, ``_expect_mcp_reports``, +``_fold_mcp_frame``, ``_initialized``, ``_kas_telemetry_sent``, ``_mcp_gateway_overlay``, +``_member_context``, ``_model``, ``_open_mcp_report``, ``_pending_init_notifications``, +``_pid``, ``_pool_lookup``, ``_process``, ``_record_tree_in_background``, +``_refuse_over_ceiling_start``, ``_remote_session_servers``, ``_remote_workspace_agents``, +``_session_label_elements``, ``_start_collect_timeout``, ``_wire_mode_id``, ``_work_dir``, ``_write_remote_token``. """ @@ -131,6 +131,7 @@ async def create_session( start_priority: StartPriority = StartPriority.BACKGROUND, bg_runtime_start: bool = False, member_context: bool | None = None, + harness_state: Any = None, ) -> AcpSessionHandle: """Create a new ACP session on this runtime. Returns a session handle. @@ -181,6 +182,25 @@ async def create_session( """ if memory_mode not in {"persistent", "incognito", "temporary"}: raise ValueError("Invalid session memory mode") + if self._harness.per_session_state and harness_state is None: + # A host whose sessions each carry their own setup (``harness_state`` is + # how this call, made again below, carries it). Every other host reads + # the flag and goes on (harness-parity H13). + return await self._create_session_with_harness_state( + cwd=cwd, + agent=agent, + mcp_servers=mcp_servers, + crew_agent=crew_agent, + member_session_key=member_session_key, + session_key=session_key, + channel_id=channel_id, + memory_mode=memory_mode, + on_gate_acquired=on_gate_acquired, + late_adopter=late_adopter, + on_gate_queued=on_gate_queued, + start_priority=start_priority, + bg_runtime_start=bg_runtime_start, + ) agent = await self._source_agent(agent) if memory_mode != "persistent": # A mixed runtime cannot attribute every raw diagnostic frame to a @@ -231,6 +251,10 @@ async def create_session( work_dir=session_work_dir, session_key=session_key, channel_id=channel_id, + permission_surface_owned=( + harness_state is not None + and self._harness.permission_surface_owned(harness_state) + ), ) if mirrored is not None: mcp_servers = mirrored.servers @@ -434,6 +458,11 @@ async def create_session( params, agent = self._harness.session_request( METHOD_SESSION_NEW, params, agent, agent_capabilities=self._agent_capabilities ) + if harness_state is not None: + # This session's own envelope, built after the array it travels with. + meta = self._harness.session_meta(harness_state, wire_servers, zero_tools=zero_tools) + if meta is not None: + params["_meta"] = {**(params.get("_meta") or {}), **meta} projected_sources: dict[str, str] = {} if self._member_context if member_context is None else member_context: @@ -528,7 +557,10 @@ async def create_session( session_work_dir=session_work_dir, projected_sources=projected_sources, payload_snapshot=payload_snapshot, - late_adopter=late_adopter, + # A late session would start without its own pin or seed (both end + # with this failed start), so a host with per-session state has it + # torn down rather than adopted. + late_adopter=None if harness_state is not None else late_adopter, memory_mode=memory_mode, session_key=session_key, member_dispatch_mounted=member_mounted, @@ -553,6 +585,21 @@ async def create_session( # id, so an arm inside that already tore it down is not repeated. Shielded # so a second cancel cannot skip the host-side teardown. try: + if harness_state is not None: + self._session_harness_states[session_id] = harness_state + # Unclaimed from here, not only once the handle is built: a failed or + # cancelled pin below must still reach the shielded close. + self._unclaimed_new_sessions.add(session_id) + # Before the handle exists, so a session the host refuses never + # reaches a caller. Its own refusal ends only this session. + await self._harness.after_session_start( + harness_state, + session_id, + resp, + send_request=lambda method, req: self._send_and_await(method, req, timeout=budget), + close_session=lambda: self.terminate_session(session_id), + agent_version=self._agent_version, + ) return await self._finish_create_session( session_id, resp, @@ -586,6 +633,37 @@ async def create_session( except BaseException: if session_id in self._unclaimed_new_sessions: await asyncio.shield(self.terminate_session(session_id)) + if ( + harness_state is not None + and self._session_harness_states.pop(session_id, None) is not None + ): + await self._harness.end_session(harness_state) + raise + + +async def _create_session_with_harness_state(self: AcpRuntime, **kwargs: Any) -> AcpSessionHandle: + """:meth:`create_session` on a host that prepares each session itself. + + The host's :meth:`~HarnessAdapter.prepare_session` runs first, in the + session's own working directory, and the start then runs with that state. + A start that fails at any step before the session is recorded releases the + state here; once recorded, the session's teardown releases it. + """ + agent = await self._source_agent(kwargs["agent"]) + work_dir = await self._session_work_dir(kwargs["cwd"]) + state = await self._harness.prepare_session( + work_dir=work_dir, + agent=agent or self._agent, + model=self._model or "", + session_key=kwargs["session_key"], + channel_id=kwargs["channel_id"], + memory_mode=kwargs["memory_mode"], + ) + try: + return await self.create_session(**kwargs, harness_state=state) + except BaseException: + if state not in self._session_harness_states.values(): + await self._harness.end_session(state) raise diff --git a/src/kiro_crew/acp/runtime_session_load.py b/src/kiro_crew/acp/runtime_session_load.py index 4128a555c94a..1a1747501ffe 100644 --- a/src/kiro_crew/acp/runtime_session_load.py +++ b/src/kiro_crew/acp/runtime_session_load.py @@ -8,16 +8,16 @@ of the method on the class or on an instance reaches every caller. Instance fields written: ``_load_replay_frames``, ``_parked_copies``, ``_session_cwds``, -``_session_inits_in_flight``, ``_session_queues``. +``_session_harness_states``, ``_session_inits_in_flight``, ``_session_queues``. Instance fields read: ``_acp_backend``, ``_agent``, ``_agent_capabilities``, -``_can_load_session``, ``_crew_agent``, ``_expect_mcp_reports``, ``_fold_mcp_frame``, -``_initialized``, ``_kas_telemetry_sent``, -``_mcp_gateway_overlay``, ``_mcp_switched_off``, ``_open_mcp_report``, ``_park_in_start_agent``, ``_pid``, +``_agent_version``, ``_can_load_session``, ``_crew_agent``, ``_expect_mcp_reports``, +``_fold_mcp_frame``, ``_initialized``, ``_kas_telemetry_sent``, ``_mcp_gateway_overlay``, +``_mcp_switched_off``, ``_model``, ``_open_mcp_report``, ``_park_in_start_agent``, ``_pid``, ``_pool_lookup``, ``_record_tree_in_background``, ``_refuse_over_ceiling_start``, ``_remote_session_servers``, ``_remote_workspace_agents``, ``_session_label_elements``, -``_wire_mode_id``, ``_work_dir``, -``_write_remote_token``, ``can_release``, ``release_session``. +``_wire_mode_id``, ``_work_dir``, ``_write_remote_token``, ``can_release``, +``release_session``. """ from __future__ import annotations @@ -91,6 +91,7 @@ async def load_session( require_replay: bool = False, start_priority: StartPriority = StartPriority.BACKGROUND, focus_resume: bool = False, + harness_state: Any = None, ) -> AcpSessionHandle: """Resume a prior session via session/load — mirrors AcpClient. @@ -135,6 +136,21 @@ async def load_session( agent's own and the first prompt does not wait behind them. Every other resume sends the one load it always sent. """ + if self._harness.per_session_state and harness_state is None: + # A host whose sessions each carry their own setup; see create_session. + return await self._load_session_with_harness_state( + session_file, + resume_sid, + cwd=cwd, + agent=agent, + crew_agent=crew_agent, + member_session_key=member_session_key, + session_key=session_key, + channel_id=channel_id, + require_replay=require_replay, + start_priority=start_priority, + focus_resume=focus_resume, + ) if not self._initialized: raise AcpRuntimeError("Runtime not initialized — call spawn() first") if not self._can_load_session: @@ -183,6 +199,9 @@ async def load_session( work_dir=session_work_dir, session_key=session_key, channel_id=channel_id, + permission_surface_owned=( + harness_state is not None and self._harness.permission_surface_owned(harness_state) + ), ) # The Connection bridge snapshots the array below wrote, for shutdown. crew_bridged: list[str] = [] @@ -409,6 +428,13 @@ async def load_session( # parked copy must be gone before the load below. if person_waits(start_priority, focus_resume=focus_resume) and self.can_release(): parking = parking_load(load_params) + if harness_state is not None: + # This session's own envelope, on every host that prepared per-session + # state, built after the final array it travels with: a resume carries + # the same settings exclusion its session/new did. + meta = self._harness.session_meta(harness_state, wire_servers, zero_tools=zero_tools) + if meta is not None: + load_params["_meta"] = {**(load_params.get("_meta") or {}), **meta} budget = await self._session_start_budget() if parking is not None: await self._park_in_start_agent(resume_sid, parking, budget) @@ -469,6 +495,22 @@ async def load_session( for msg in buffered_init: queue.put_nowait(msg) self._fold_mcp_frame(resume_sid, msg) + if harness_state is not None: + self._session_harness_states[resume_sid] = harness_state + try: + # A restored session carries the mode it was left in, so it is checked + # again before its first prompt. A refusal ends only this session. + await self._harness.after_session_start( + harness_state, + resume_sid, + resp, + send_request=lambda method, req: self._send_and_await(method, req, timeout=budget), + close_session=lambda: self.terminate_session(resume_sid), + agent_version=self._agent_version, + ) + except BaseException: + await asyncio.shield(self.terminate_session(resume_sid)) + raise # Mirrors create_session: a resumed session gets the same # canonical-crew watchdog snapshot, resolved off-loop. @@ -864,3 +906,30 @@ async def _wait_managed_mcp( else: await self.terminate_session(handle.session_id) raise + + +async def _load_session_with_harness_state( + self: AcpRuntime, session_file: str, resume_sid: str, **kwargs: Any +) -> AcpSessionHandle: + """:meth:`load_session` on a host that prepares each session itself. + + The twin of ``_create_session_with_harness_state``: the state is prepared in + the session's own working directory first, and released here when the load + fails before the session is recorded. + """ + agent = kwargs["agent"] or self._agent + work_dir = await self._session_work_dir(kwargs["cwd"]) + state = await self._harness.prepare_session( + work_dir=work_dir, + agent=agent, + model=self._model or "", + session_key=kwargs["session_key"], + channel_id=kwargs["channel_id"], + memory_mode="persistent", + ) + try: + return await self.load_session(session_file, resume_sid, **kwargs, harness_state=state) + except BaseException: + if state not in self._session_harness_states.values(): + await self._harness.end_session(state) + raise diff --git a/src/kiro_crew/acp/runtime_session_registry.py b/src/kiro_crew/acp/runtime_session_registry.py index 6e410d3faca8..a38ddb7d6fce 100644 --- a/src/kiro_crew/acp/runtime_session_registry.py +++ b/src/kiro_crew/acp/runtime_session_registry.py @@ -9,9 +9,10 @@ Instance fields written: ``_announced_children``, ``_announced_overflow``, ``_mcp_sign_in_ended_hooks``, ``_pending_init_notifications``, ``_routed_requests``, -``_session_activity_at``, ``_session_cwds``, ``_session_inits_in_flight``, -``_session_mcp_reports``, ``_session_queues``, -``_subagent_owner``, ``_subagent_roster_overflow``, ``_subagent_sessions``, ``_turn_active_sessions``. +``_session_activity_at``, ``_session_cwds``, ``_session_harness_states``, +``_session_inits_in_flight``, ``_session_mcp_reports``, ``_session_queues``, +``_subagent_owner``, ``_subagent_roster_overflow``, ``_subagent_sessions``, +``_turn_active_sessions``. Instance fields read: ``_agent_capabilities``, ``_dead``, ``_mcp_reports``, ``_process``, ``_record_keeping_sessions``, ``_start_collectors``. @@ -259,6 +260,11 @@ async def terminate_session( finally: self._unclaimed_new_sessions.discard(session_id) self.unregister_session(session_id) + # What the harness prepared for this session (``HarnessAdapter.end_session``). + # A host without per-session state recorded nothing, so nothing is awaited. + harness_state = self._session_harness_states.pop(session_id, None) + if harness_state is not None: + await self._harness.end_session(harness_state) class _RecordKeepingScope: @@ -336,6 +342,11 @@ async def evict_session(self: AcpRuntime, session_id: str) -> None: ) finally: self.unregister_session(session_id) + # What the harness prepared for this session (``HarnessAdapter.end_session``). + # A host without per-session state recorded nothing, so nothing is awaited. + harness_state = self._session_harness_states.pop(session_id, None) + if harness_state is not None: + await self._harness.end_session(harness_state) def can_release(self: AcpRuntime) -> bool: diff --git a/src/kiro_crew/acp/runtime_session_setup.py b/src/kiro_crew/acp/runtime_session_setup.py index 51b0077c3425..8e0e24d1404c 100644 --- a/src/kiro_crew/acp/runtime_session_setup.py +++ b/src/kiro_crew/acp/runtime_session_setup.py @@ -12,12 +12,14 @@ Instance fields written: ``_session_start_timeout``, ``_start_collect_timeout``. -Instance fields read: ``_acp_backend``, ``_agent``, ``_agent_capabilities``, ``_bound_workspace_fd``, -``_child_env_names``, ``_expect_mcp_reports``, ``_governance_scope``, ``_kiro_native_spec_lookup``, -``_launch_agent``, ``_launch_copy_spec``, ``_mcp_gateway_overlay``, ``_mcp_gateway_socket``, -``_member_context``, ``_native_launch_resources``, ``_native_launch_sources``, ``_native_launch_view_alias``, -``_native_skill_projection``, ``_session_queues``, ``_ssh_auth_sock_forwarded``, ``_start_launch_name``, -``_tool_search_wire``, ``_wire_mode_id``, ``_work_dir``. +Instance fields read: ``_acp_backend``, ``_agent``, ``_agent_capabilities``, +``_bound_workspace_fd``, ``_child_env_names``, ``_expect_mcp_reports``, +``_governance_scope``, ``_kiro_native_spec_lookup``, ``_launch_agent``, +``_launch_copy_spec``, ``_mcp_gateway_overlay``, ``_mcp_gateway_socket``, +``_member_context``, ``_native_launch_resources``, ``_native_launch_sources``, +``_native_launch_view_alias``, ``_native_skill_projection``, ``_session_queues``, +``_ssh_auth_sock_forwarded``, ``_start_launch_name``, ``_tool_search_wire``, +``_wire_mode_id``, ``_work_dir``. """ from __future__ import annotations @@ -649,6 +651,7 @@ async def _mirrored_session_mcp( work_dir: str | Path, session_key: str, channel_id: str, + permission_surface_owned: bool = False, ) -> _MirroredSessionMcp | None: """This session's ``mcpServers``, built by the host's agent-config MIRROR. @@ -686,10 +689,12 @@ async def _mirrored_session_mcp( an allowlist and inherits nothing, so Crew's own control plane comes up with no session to act on unless the element carries the identity. - ``permission_surface_owned`` is False because this runtime authors no native - permission file. That is the fail-CLOSED direction: a mirror in claude's class - -- one whose tools could be pre-approved in a file Crew does not own, where - Crew's gate never fires -- withholds its array here rather than delivering it. + ``permission_surface_owned`` is False unless the host's own per-session state + says Crew governs this session's native permission file + (``HarnessAdapter.permission_surface_owned``: the claude harness seeds it per + session). False is the fail-CLOSED direction: a mirror in claude's class -- one + whose tools could be pre-approved in a file Crew does not own, where Crew's gate + never fires -- withholds its array here rather than delivering it. Blocking work (an agent-spec parse, an overlay read) runs off the loop, the same as the pooled resolution it replaces. @@ -751,7 +756,7 @@ def _project_and_snapshot() -> tuple[Any, Any]: active_agent, stub_server_names=stubbed, stub_elements=stubs, - permission_surface_owned=False, + permission_surface_owned=permission_surface_owned, work_dir=work_dir, session_key=session_key, channel_id=channel_id, diff --git a/test/test_acp_harness_contract.py b/test/test_acp_harness_contract.py index 3915c0bdc578..17e46391cdbd 100644 --- a/test/test_acp_harness_contract.py +++ b/test/test_acp_harness_contract.py @@ -35,6 +35,7 @@ from kiro_crew.acp.harness._common import KIRO_FAMILY_ALIASES from kiro_crew.acp.kas_transport import METHOD_KAS_AUTH_GET_ACCESS_TOKEN from kiro_crew.acp.types import ( + ACP_BACKEND_CLAUDE, ACP_BACKEND_CODEX, ACP_BACKEND_KAS, ACP_BACKEND_KIRO, @@ -48,7 +49,11 @@ from kiro_crew.config import paths as paths_mod from kiro_crew.mcp_gateway import session_servers as session_servers_mod -ALL_BACKENDS = [ACP_BACKEND_KIRO, ACP_BACKEND_KAS, ACP_BACKEND_CODEX] +ALL_BACKENDS = [ACP_BACKEND_KIRO, ACP_BACKEND_KAS, ACP_BACKEND_CODEX, ACP_BACKEND_CLAUDE] + +#: Hosts with a shared-runtime harness that no session is routed to yet: they keep +#: their per-process adapter until the routing change names them. +REGISTERED_AHEAD_OF_ROUTING = {ACP_BACKEND_CLAUDE} #: The hosts reached through kiro-cli's own binary and ACP relay. They share a #: notification vocabulary, an agent-spec permission routing and a spawn-time effort @@ -326,12 +331,19 @@ async def _no_bin(*, environ, home): # no harness may return an argv for a binary that is not there -- and narrowing # it to one family would leave the next host's spawn unasserted. monkeypatch.setattr(client_mod, "_resolve_codex_acp_bin", lambda: (None, "/nowhere")) + from kiro_crew.acp import launch as launch_mod + from kiro_crew.acp.harness import claude as claude_harness + + monkeypatch.setattr(claude_harness, "_resolve_claude_acp_bin", lambda: (None, "/nowhere")) + monkeypatch.setattr(claude_harness, "_claude_acp_argv_cache", launch_mod._UNRESOLVED) with pytest.raises(AcpRuntimeError, match="not found") as raised: await harness_for(backend).resolve_spawn(_ctx(tmp_path)) # The two kiro-cli hosts tag the refusal so the chat row can offer the - # feature-request form; codex-acp is a different binary whose install the - # operator chose, and its refusal stays an untagged error row. - assert getattr(raised.value, "kiro_cli_missing", False) is (backend != ACP_BACKEND_CODEX) + # feature-request form; codex-acp and claude-agent-acp are different binaries + # whose install the operator chose, and their refusals stay untagged error rows. + assert getattr(raised.value, "kiro_cli_missing", False) is ( + backend in (ACP_BACKEND_KIRO, ACP_BACKEND_KAS) + ) def test_kiro_injects_the_api_key_and_kas_strips_it(monkeypatch): @@ -999,7 +1011,9 @@ def test_reclaim_thresholds_pass_the_operator_configuration_through(backend): f"ceiling through; got {policy.max_rss_mb!r} for {rss!r}" ) else: - assert isinstance(depth, int) and depth >= 1 + # 0 is the launched process alone (claude-agent-acp: the adapter, not the + # per-session children below it). + assert isinstance(depth, int) and depth >= 0 assert policy.max_rss_mb == ceiling, ( f"{backend!r} measures a bounded scope (depth {depth}) and must state its " f"declared ceiling {ceiling!r} in that unit; got {policy.max_rss_mb!r} for " @@ -1345,14 +1359,16 @@ def test_an_enforced_host_may_not_spawn_without_a_mask(): from kiro_crew.acp.harness import _HARNESSES for backend, harness_cls in _HARNESSES.items(): - routing = acp_tool_gate.routing_for(backend) source = _inspect.getsource(harness_cls.resolve_spawn) - if routing is acp_tool_gate.Routing.AGENT_SPEC: - # Asks by construction: no mask needed, and none claimed. + if not acp_tool_gate.is_enforced(backend): + # The gate does not enforce this host, so there is no gate a mask + # compensates for: an AGENT_SPEC host asks by construction, and claude + # (SEEDED_SETTINGS) is made to ask by the seed Crew writes, with no mask + # on its per-process launch either. None claimed. assert "extra_hidden_dirs" not in source, backend continue assert "extra_hidden_dirs=" in source, ( - f"{backend} is not AGENT_SPEC-routed, so its harness must resolve an " + f"{backend} is enforced by the tool gate, so its harness must resolve an " f"OS credential mask and put it on the plan" ) @@ -1453,7 +1469,7 @@ def test_an_enforced_host_must_consult_the_sandbox_tier(): from kiro_crew.acp.harness import _HARNESSES for backend, harness_cls in _HARNESSES.items(): - if acp_tool_gate.routing_for(backend) is acp_tool_gate.Routing.AGENT_SPEC: + if not acp_tool_gate.is_enforced(backend): continue source = inspect.getsource(harness_cls.resolve_spawn) assert "sandbox_mode" in source, ( @@ -1500,6 +1516,10 @@ def test_every_per_process_host_has_an_adapter_and_no_runtime_harness(): adapter = process_adapter_for(backend) assert isinstance(adapter, ProcessAdapter) assert adapter.backend == backend + if backend in REGISTERED_AHEAD_OF_ROUTING: + # Its runtime harness exists for its own tests; no session reaches it. + assert backend not in ACP_BACKENDS_ACP_RUNTIME + continue with pytest.raises(ValueError, match="no ACP harness for backend"): harness_for(backend) @@ -1509,6 +1529,10 @@ def test_the_client_keeps_its_own_arm_for_every_runtime_served_host(): from kiro_crew.acp.harness import process_adapter_for for backend in ALL_BACKENDS: + if backend in REGISTERED_AHEAD_OF_ROUTING: + # Still launched per process, by its own adapter, until it is routed. + assert process_adapter_for(backend) is not None + continue assert process_adapter_for(backend) is None diff --git a/test/test_claude_shared_runtime.py b/test/test_claude_shared_runtime.py new file mode 100644 index 000000000000..e0c9a9b9b2d6 --- /dev/null +++ b/test/test_claude_shared_runtime.py @@ -0,0 +1,428 @@ +"""claude-agent-acp on the shared runtime (``ClaudeHarness``): each session's own setup. + +On ``AcpClient`` a claude session owns its process, so its settings seed is written at +spawn and a failed mode pin ends the process. On one process several sessions share, +both have to be one session's. These pin the harness's answers: the seed is written per +session in that session's folder, a refused pin closes only that session, the seed goes +with the session, the teardown keeps the record, and the RSS ceiling counts the adapter +alone. No session is routed here yet; the harness is reached through ``harness_for``. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Any + +import pytest + +from kiro_crew.acp.claude_shared_session import ClaudeSharedSession +from kiro_crew.acp.harness import claude as claude_mod +from kiro_crew.acp.harness import harness_for +from kiro_crew.acp.runtime_session_registry import terminate_session +from kiro_crew.acp.session_handle_runtime_contract import AcpRequestTimeout, AcpRuntimeError +from kiro_crew.acp.transport_errors import AcpError +from kiro_crew.acp.types import ACP_BACKEND_CLAUDE, METHOD_SESSION_CLOSE, METHOD_SET_MODE +from kiro_crew.agent_sdk.backends import ACP_BACKENDS_ACP_RUNTIME +from kiro_crew.testing.ids import UNALLOCATABLE_PID + +_ARGV = ["/opt/bin/claude-agent-acp"] + + +@pytest.fixture +def harness(monkeypatch): + async def _argv() -> list[str]: + return list(_ARGV) + + monkeypatch.setattr(claude_mod, "_resolve_claude_argv", _argv) + monkeypatch.setattr(claude_mod, "_claude_adapter_installed_version", lambda _argv: "0.94.0") + return harness_for(ACP_BACKEND_CLAUDE) + + +async def _prepare(harness: Any, work_dir: Path) -> ClaudeSharedSession: + return await harness.prepare_session( + work_dir=work_dir, + agent="kirocrew", + model="", + session_key=f"dashboard:{work_dir.name}", + channel_id="", + memory_mode="persistent", + ) + + +def _seed(work_dir: Path) -> Path: + return work_dir / ".claude" / "settings.local.json" + + +def test_the_harness_is_registered_and_routes_nothing(): + assert ACP_BACKEND_CLAUDE not in ACP_BACKENDS_ACP_RUNTIME + harness = harness_for(ACP_BACKEND_CLAUDE) + assert harness.per_session_state is True + assert harness.teardown.method == METHOD_SESSION_CLOSE + assert harness.teardown.notification is False + assert harness.release(None) is None + assert harness.verifies_agent_activation is False + assert harness.host_answered_methods == () + + +def test_the_protocol_version_is_the_one_the_client_sends(): + from kiro_crew.acp import client_start + + assert harness_for(ACP_BACKEND_CLAUDE).protocol_version == client_start.PROTOCOL_VERSION_CLAUDE + + +def test_the_rss_ceiling_counts_the_adapter_alone(): + """A whole-subtree ceiling would recycle every chat once a few were open.""" + harness = harness_for(ACP_BACKEND_CLAUDE) + policy = harness.reclaim_policy(max_age_secs=60.0, max_rss_mb=500.0) + assert policy.max_rss_mb == harness.CORE_RSS_CEILING_MB == 512.0 + assert harness.CORE_RSS_DEPTH == 0 + + +def test_the_spawn_seeds_nothing_and_is_measured_adapter_only(harness, tmp_path, monkeypatch): + from kiro_crew.acp.harness import SpawnContext + from kiro_crew.acp.harness import codex as codex_mod + + monkeypatch.setattr(codex_mod, "_sandbox_wrapper_generations", lambda _mode: 1) + ctx = SpawnContext( + agent="kirocrew", work_dir=tmp_path, model=None, environ={}, home=tmp_path, session=None + ) + plan = asyncio.run(harness.resolve_spawn(ctx)) + assert plan.argv == _ARGV + # One resident sandbox launcher above the adapter, and nothing below it. + assert plan.rss_depth == 1 + assert not _seed(tmp_path).exists() + + +def test_each_session_writes_its_own_seed_in_its_own_folder(harness, tmp_path): + """A seed written once per process would leave a later session unseeded.""" + first, second = tmp_path / "a", tmp_path / "b" + first.mkdir() + second.mkdir() + + async def _run() -> tuple[Any, Any]: + return await _prepare(harness, first), await _prepare(harness, second) + + one, two = asyncio.run(_run()) + assert _seed(first).exists() and _seed(second).exists() + assert harness.permission_surface_owned(one) is True + assert harness.permission_surface_owned(two) is True + assert harness.permission_surface_owned(None) is False + asyncio.run(harness.end_session(one)) + asyncio.run(harness.end_session(two)) + + +def test_ending_a_session_removes_its_seed_once(harness, tmp_path): + state = asyncio.run(_prepare(harness, tmp_path)) + assert _seed(tmp_path).exists() + asyncio.run(harness.end_session(state)) + assert not _seed(tmp_path).exists() + # A refused start and the teardown it triggers can both reach here. + asyncio.run(harness.end_session(state)) + assert not _seed(tmp_path).exists() + + +def test_the_envelope_is_the_sessions_own(harness, tmp_path): + state = asyncio.run(_prepare(harness, tmp_path)) + meta = harness.session_meta(state, [], zero_tools=False) + assert meta == state._claude_session_meta() + assert "claudeCode" in meta + assert harness.session_meta(None, []) is None + asyncio.run(harness.end_session(state)) + + +def test_a_zero_tool_session_that_mounts_a_server_is_refused(harness, tmp_path): + state = asyncio.run(_prepare(harness, tmp_path)) + with pytest.raises(AcpError): + harness.session_meta(state, [{"name": "srv", "command": "x"}], zero_tools=True) + asyncio.run(harness.end_session(state)) + + +def _pinned_scenario(monkeypatch, state: ClaudeSharedSession) -> None: + """A session the pin applies to: the operator asked for inherited modes to be + pinned, and the session carries Crew's tools.""" + from kiro_crew.acp import client_claude_session + + monkeypatch.setattr(client_claude_session, "resolve_cc_pin_inherited_mode", lambda: True) + state._mcp_mount_servers = ["kirocrew-core"] + + +def test_the_pin_talks_to_this_session_on_the_shared_connection(harness, tmp_path, monkeypatch): + state = asyncio.run(_prepare(harness, tmp_path)) + _pinned_scenario(monkeypatch, state) + sent: list[tuple[str, dict]] = [] + closed: list[str] = [] + + async def _send(method: str, params: dict) -> dict: + sent.append((method, params)) + return {} + + async def _close() -> None: + closed.append("s-1") + + resp = {"sessionId": "s-1", "modes": {"currentModeId": "bypassPermissions"}} + asyncio.run( + harness.after_session_start( + state, "s-1", resp, send_request=_send, close_session=_close, agent_version="0.94.0" + ) + ) + assert sent == [(METHOD_SET_MODE, {"sessionId": "s-1", "modeId": "default"})] + assert closed == [] + asyncio.run(harness.end_session(state)) + + +#: What the shared connection raises for a ``session/set_mode`` it gets no good answer +#: to: an error answer, or none within the budget. +_SHARED_PIN_FAILURES = [ + pytest.param(AcpRuntimeError("set_mode refused"), id="error-answer"), + pytest.param(AcpRequestTimeout("set_mode timed out"), id="timeout"), +] + + +@pytest.mark.parametrize("failure", _SHARED_PIN_FAILURES) +def test_a_failed_pin_closes_only_this_session(harness, tmp_path, monkeypatch, failure): + """The process serves other sessions, so a refused one is closed, never killed.""" + state = asyncio.run(_prepare(harness, tmp_path)) + _pinned_scenario(monkeypatch, state) + closed: list[str] = [] + + async def _send(method: str, params: dict) -> dict: + raise failure + + async def _close() -> None: + closed.append("s-1") + + resp = {"sessionId": "s-1", "modes": {"currentModeId": "bypassPermissions"}} + with pytest.raises(AcpError, match="pin the asking permission mode"): + asyncio.run( + harness.after_session_start( + state, + "s-1", + resp, + send_request=_send, + close_session=_close, + agent_version="0.94.0", + ) + ) + assert closed == ["s-1"] + asyncio.run(harness.end_session(state)) + + +def test_the_shared_state_never_ends_the_process(tmp_path): + closed: list[str] = [] + + async def _close() -> None: + closed.append("closed") + + async def _send(method: str, params: dict) -> dict: + return {} + + state = ClaudeSharedSession( + work_dir=tmp_path, model="", agent="kirocrew", session_key="", channel_id="" + ) + state.bind_started("s-1", "0.94.0", send_request=_send, close_session=_close) + asyncio.run(state._kill_process(force=True)) + assert closed == ["closed"] + + +class _RuntimeStub: + """The members ``terminate_session`` reads, with a harness that records its calls.""" + + def __init__(self, harness: Any, state: Any) -> None: + self._harness = harness + self._session_harness_states = {"s-1": state} + self._record_keeping_sessions: set[str] = set() + self._unclaimed_new_sessions: set[str] = set() + self._unconfirmed_teardowns: set[str] = set() + self._dead = False + self._process = object() + self.sent: list[tuple[str, dict]] = [] + self.unregistered: list[str] = [] + + async def _send_and_await(self, method: str, params: dict, **_kw: Any) -> dict: + self.sent.append((method, params)) + return {} + + def unregister_session(self, session_id: str) -> None: + self.unregistered.append(session_id) + + +def test_the_session_teardown_closes_it_and_ends_its_state(harness, tmp_path): + state = asyncio.run(_prepare(harness, tmp_path)) + runtime = _RuntimeStub(harness, state) + asyncio.run(terminate_session(runtime, "s-1")) # type: ignore[arg-type] + assert runtime.sent == [(METHOD_SESSION_CLOSE, {"sessionId": "s-1"})] + assert runtime.unregistered == ["s-1"] + assert runtime._session_harness_states == {} + assert not _seed(tmp_path).exists() + + +def test_a_host_without_session_state_skips_every_seam(): + for backend in ("", "kas", "codex"): + assert harness_for(backend).per_session_state is False + + +# ── The shared runtime's session start, with the control plane recorded ── + + +class _Plane: + """The requests one claude session start puts on the shared connection.""" + + def __init__( + self, + new_response: dict[str, Any], + *, + refuse: str = "", + refusal: BaseException | None = None, + ) -> None: + self._new_response = new_response + self._refuse = refuse + self._refusal = refusal + self.sent: list[tuple[str, dict[str, Any]]] = [] + + async def send_and_await(self, method: str, params: dict, timeout: Any = None) -> dict: + self.sent.append((method, params)) + if method == self._refuse: + raise self._refusal or AcpRuntimeError(f"{method} refused") + if method == "session/new": + return self._new_response + return {} + + def methods(self) -> list[str]: + return [m for m, _ in self.sent] + + +def _claude_runtime(plane: _Plane) -> Any: + from unittest.mock import MagicMock + + from kiro_crew.acp.runtime import AcpRuntime + + rt = AcpRuntime(work_dir="/tmp", acp_backend=ACP_BACKEND_CLAUDE, expect_mcp_reports=False) + proc = MagicMock() + proc.stdout = None + proc.stdin = MagicMock() + proc.returncode = None + # Above every pid_max, so no cleanup path can signal a real process. + proc.pid = UNALLOCATABLE_PID + rt._process = proc + rt._pid = UNALLOCATABLE_PID + rt._initialized = True + rt._agent_version = "0.94.0" + rt._send_and_await = plane.send_and_await # type: ignore[method-assign] + return rt + + +def test_a_session_start_seeds_its_folder_and_sends_its_envelope(harness, tmp_path): + plane = _Plane({"sessionId": "s-1", "modes": {"currentModeId": "default"}}) + rt = _claude_runtime(plane) + + async def _run() -> Any: + return await rt.create_session(cwd=str(tmp_path), agent="kirocrew") + + handle = asyncio.run(_run()) + assert handle.session_id == "s-1" + new_params = [p for m, p in plane.sent if m == "session/new"] + assert len(new_params) == 1 + assert "claudeCode" in new_params[0].get("_meta", {}) + assert _seed(tmp_path).exists() + assert set(rt._session_harness_states) == {"s-1"} + # Ending the session closes it on the host and takes its seed with it. + asyncio.run(rt.terminate_session("s-1")) + assert plane.methods()[-1] == METHOD_SESSION_CLOSE + assert rt._session_harness_states == {} + assert not _seed(tmp_path).exists() + + +def test_a_start_the_host_refuses_leaves_no_seed(harness, tmp_path): + plane = _Plane({}, refuse="session/new") + rt = _claude_runtime(plane) + with pytest.raises(Exception): + asyncio.run(rt.create_session(cwd=str(tmp_path), agent="kirocrew")) + assert not _seed(tmp_path).exists() + assert rt._session_harness_states == {} + + +@pytest.mark.parametrize("failure", _SHARED_PIN_FAILURES) +def test_a_failed_pin_closes_that_session_and_keeps_the_process( + harness, tmp_path, monkeypatch, failure +): + from kiro_crew.acp import client_claude_session + + monkeypatch.setattr(client_claude_session, "resolve_cc_pin_inherited_mode", lambda: True) + plane = _Plane( + {"sessionId": "s-2", "modes": {"currentModeId": "bypassPermissions"}}, + refuse=METHOD_SET_MODE, + refusal=failure, + ) + rt = _claude_runtime(plane) + # A session carrying one of Crew's servers, which is what the pin applies to. + crew_server = {"name": "kirocrew-core", "command": "kirocrew", "args": [], "env": []} + with pytest.raises(AcpError, match="pin the asking permission mode"): + asyncio.run( + rt.create_session(cwd=str(tmp_path), agent="kirocrew", mcp_servers=[crew_server]) + ) + assert ("session/close", {"sessionId": "s-2"}) in plane.sent + assert rt._process is not None and not rt._dead + proc_kill = getattr(rt._process, "kill") + assert not proc_kill.called + assert not _seed(tmp_path).exists() + assert rt._session_harness_states == {} + + +def test_a_start_cancelled_during_its_pin_closes_that_session(harness, tmp_path, monkeypatch): + """A cancel the pin does not catch still reaches the start's shielded close.""" + from kiro_crew.acp import client_claude_session + + monkeypatch.setattr(client_claude_session, "resolve_cc_pin_inherited_mode", lambda: True) + plane = _Plane( + {"sessionId": "s-3", "modes": {"currentModeId": "bypassPermissions"}}, + refuse=METHOD_SET_MODE, + refusal=asyncio.CancelledError(), + ) + rt = _claude_runtime(plane) + crew_server = {"name": "kirocrew-core", "command": "kirocrew", "args": [], "env": []} + with pytest.raises(asyncio.CancelledError): + asyncio.run( + rt.create_session(cwd=str(tmp_path), agent="kirocrew", mcp_servers=[crew_server]) + ) + assert ("session/close", {"sessionId": "s-3"}) in plane.sent + assert rt._session_harness_states == {} + + +class _LoadPlane(_Plane): + """A host that resumes the session it is asked to load.""" + + def __init__(self) -> None: + super().__init__({"sessionId": "unused"}) + + async def send_and_await(self, method: str, params: dict, timeout: Any = None) -> dict: + resp = await super().send_and_await(method, params, timeout) + return {"modes": {"currentModeId": "default"}} if method == "session/load" else resp + + +def test_a_resumed_session_sends_its_own_envelope(harness, tmp_path): + """session/load carries the per-session envelope, as session/new does.""" + plane = _LoadPlane() + rt = _claude_runtime(plane) + rt._can_load_session = True + handle = asyncio.run(rt.load_session("", "s-5", cwd=str(tmp_path), agent="kirocrew")) + assert handle.session_id == "s-5" + loads = [p for m, p in plane.sent if m == "session/load"] + assert len(loads) == 1 + assert "claudeCode" in loads[0].get("_meta", {}) + assert _seed(tmp_path).exists() + asyncio.run(rt.terminate_session("s-5")) + assert not _seed(tmp_path).exists() + + +def test_the_kiro_start_never_reaches_the_per_session_seams(monkeypatch): + """harness-parity H13: kiro-cli reads the flag and goes on.""" + from kiro_crew.acp.runtime import AcpRuntime + + async def _boom(*_a: Any, **_k: Any) -> Any: + raise AssertionError("the kiro start reached the per-session seams") + + monkeypatch.setattr(AcpRuntime, "_create_session_with_harness_state", _boom) + monkeypatch.setattr(AcpRuntime, "_load_session_with_harness_state", _boom) + rt = AcpRuntime(work_dir="/tmp") + assert rt._harness.per_session_state is False diff --git a/test/test_runtime_bindings.py b/test/test_runtime_bindings.py index e11cd447f8a5..1144cde20703 100644 --- a/test/test_runtime_bindings.py +++ b/test/test_runtime_bindings.py @@ -58,6 +58,18 @@ #: Member -> (kind, coroutine, signature digest, owning module). Frozen at the split: the #: kind, coroutine flag and signature are BASE's; the owner is where the member lives now. _MEMBERS: dict[str, tuple[str, object, str, str]] = { + "_create_session_with_harness_state": ( + "function", + True, + "e3d37eb50120", + "runtime_session_create", + ), + "_load_session_with_harness_state": ( + "function", + True, + "56b8e5999417", + "runtime_session_load", + ), "_DESCENDANT_RESCAN_DELAY": ("data", False, "", "runtime_class"), "_EXIT_DRAIN_GRACE": ("data", False, "", "runtime_class"), "_EXIT_DRAIN_MAX": ("data", False, "", "runtime_class"), @@ -130,7 +142,7 @@ "ead9c31b8aca", "runtime_session_setup", ), - "_mirrored_session_mcp": ("function", True, "2db14e85d828", "runtime_session_setup"), + "_mirrored_session_mcp": ("function", True, "1a8f8533ecff", "runtime_session_setup"), "_mirrored_spec_check_needed": ("function", False, "3cd7cb3cf81a", "runtime_session_setup"), "_mode_available": ("staticmethod", False, "08e0d5cbf178", "runtime_mode_activation"), "_mount_member_panel": ("function", True, "bcc6c7135aaa", "runtime_session_setup"), @@ -216,7 +228,7 @@ "agent_version": ("property", False, "bb418bb7ece8", "runtime_class"), "begin_mcp_reattempt": ("function", False, "dc7c165669b1", "runtime_host_requests"), "begin_mcp_sign_in": ("function", False, "dc7c165669b1", "runtime_host_requests"), - "create_session": ("function", True, "76e4a6b519f6", "runtime_session_create"), + "create_session": ("function", True, "55fcebd687f6", "runtime_session_create"), "death_summary": ("function", False, "f21e39ec5ffb", "runtime_liveness"), "entitlement_probe_result_at": ("property", False, "59162e39f6f1", "runtime_class"), "evict_session": ("function", True, "c284282f8a1d", "runtime_session_registry"), @@ -228,7 +240,7 @@ "is_cloud_sandbox": ("property", False, "a6632a57e602", "runtime_class"), "keep_record_on_teardown": ("function", False, "4f730038263e", "runtime_session_registry"), "kill": ("function", True, "4f9ced5c4b86", "runtime_tree_kill"), - "load_session": ("function", True, "4f88ef29453b", "runtime_session_load"), + "load_session": ("function", True, "2f38edd6fbd1", "runtime_session_load"), "mark_turn_active": ("function", False, "a3b3a732c817", "runtime_session_registry"), "mcp_sign_in_holds": ("function", False, "dc7c165669b1", "runtime_host_requests"), "pid": ("property", False, "8dc15be1dfda", "runtime_class"), From eb28aa7f09503a3a8fc4ca8b3c71360e766c36c4 Mon Sep 17 00:00:00 2001 From: Raymond Chen Date: Sun, 15 Nov 2026 07:15:43 +0000 Subject: [PATCH 2/2] test(acp): fakes carry the per-session harness state and the permission-surface seam --- src/kiro_crew/acp/harness/claude.py | 9 ++------- test/test_acp_codex_harness.py | 3 ++- test/test_codex_zero_tools.py | 3 ++- test/test_kas_mcp_live_reinject.py | 2 ++ 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/kiro_crew/acp/harness/claude.py b/src/kiro_crew/acp/harness/claude.py index e36a9bc3cb7a..70aa6c940171 100644 --- a/src/kiro_crew/acp/harness/claude.py +++ b/src/kiro_crew/acp/harness/claude.py @@ -483,16 +483,11 @@ def _apply_claude_env_defaults(env: dict[str, str], backend: str, work_dir: Path """ if backend in ACP_BACKENDS_PLAN_CHECKLIST: env.setdefault(CLAUDE_TODO_TOOLS_ENV, "1") - if ( - backend not in ACP_BACKENDS_SUMMARIZED_THINKING - or CLAUDE_THINKING_DISPLAY_ENV in env - ): + if backend not in ACP_BACKENDS_SUMMARIZED_THINKING or CLAUDE_THINKING_DISPLAY_ENV in env: return # The child's own config directory when the environment names one. config_dir = env.get("CLAUDE_CONFIG_DIR") - if not a_source_decides_thinking( - work_dir, config_dir=Path(config_dir) if config_dir else None - ): + if not a_source_decides_thinking(work_dir, config_dir=Path(config_dir) if config_dir else None): env[CLAUDE_THINKING_DISPLAY_ENV] = CLAUDE_THINKING_DISPLAY_DEFAULT diff --git a/test/test_acp_codex_harness.py b/test/test_acp_codex_harness.py index 7f9e919c99e8..50be1b8702a1 100644 --- a/test/test_acp_codex_harness.py +++ b/test/test_acp_codex_harness.py @@ -1571,7 +1571,8 @@ class TestTheRuntimeCarriesTheProjectionOntoTheSession: @staticmethod def _projection(servers: list[dict], denied: set[tuple[str, str]]): - async def _mirrored(agent, *, work_dir, session_key, channel_id): + async def _mirrored(agent, *, work_dir, session_key, channel_id, permission_surface_owned): + assert permission_surface_owned is False return _MirroredSessionMcp( servers=list(servers), denied_tools=frozenset(denied), diff --git a/test/test_codex_zero_tools.py b/test/test_codex_zero_tools.py index dfe661c8e3f6..3d221a7ed0a7 100644 --- a/test/test_codex_zero_tools.py +++ b/test/test_codex_zero_tools.py @@ -360,7 +360,8 @@ def _codex_runtime() -> AcpRuntime: def _projection(*, zero_tools: bool): - async def _mirrored(agent, *, work_dir, session_key, channel_id): + async def _mirrored(agent, *, work_dir, session_key, channel_id, permission_surface_owned): + assert permission_surface_owned is False return _MirroredSessionMcp( servers=[], denied_tools=frozenset(), diff --git a/test/test_kas_mcp_live_reinject.py b/test/test_kas_mcp_live_reinject.py index f624f325e70a..977bbce915cd 100644 --- a/test/test_kas_mcp_live_reinject.py +++ b/test/test_kas_mcp_live_reinject.py @@ -494,6 +494,7 @@ def _runtime() -> object: # The harness resolves from the backend id; KAS's teardown verb is the # record-deleting one this scope exists to avoid. runtime._acp_backend = ACP_BACKEND_KAS + runtime._session_harness_states = {} runtime.unregister_session = MagicMock() # type: ignore[method-assign] return runtime @@ -565,6 +566,7 @@ async def _send(method: str, params: dict, timeout: float = 0.0) -> dict: return {} runtime._send_and_await = _send # type: ignore[method-assign] + runtime._session_harness_states = {} runtime.unregister_session = MagicMock() # type: ignore[method-assign] await AcpRuntime.evict_session(runtime, _SID) assert sent == [(METHOD_SESSION_CLOSE, {"sessionId": _SID})]