Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docs/system-specs/modules/claude-code-provider.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions docs/system-specs/modules/providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
127 changes: 127 additions & 0 deletions src/kiro_crew/acp/claude_shared_session.py
Original file line number Diff line number Diff line change
@@ -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()
7 changes: 6 additions & 1 deletion src/kiro_crew/acp/harness/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -57,6 +57,7 @@
)

__all__ = [
"ClaudeHarness",
"ClaudeLaunch",
"CodexHarness",
"CopilotLaunch",
Expand Down Expand Up @@ -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,
}


Expand Down
64 changes: 64 additions & 0 deletions src/kiro_crew/acp/harness/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Loading
Loading