Coverage for src/ai_shell/acp.py: 91%

461 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-17 21:40 +0000

1"""ACP proxy: run an ACP agent in the dev container for an ACP client on the host. 

2 

3ACP (Agent Client Protocol) is JSON-RPC over stdio between a client (JetBrains 

4Air, Zed) and an agent. The client and the agent see the project at different 

5paths: the client sends the host path (``C:\\Users\\me\\projects\\x``), and the 

6agent runs in the dev container, where the project is ``/root/projects/x``. 

7Every path in the protocol is absolute, so this proxy swaps the project root in 

8both directions. The bind mount keeps everything below the root the same. 

9 

10The proxy also keeps the agent inside the container: 

11 

12- It removes the client's ``fs``, ``terminal`` and terminal-auth capabilities 

13 from ``initialize``, so the agent never asks the client to read, write or run 

14 anything on the host. 

15- It drops the MCP servers the client offers in ``session/new``. They are host 

16 commands (JetBrains sends ``idea64.exe stdioMcpServer``) and cannot run in the 

17 container. ai-shell adds its own servers (the Chrome DevTools MCP) instead. 

18 

19The client sends ``initialize`` before it names a project, and it starts the 

20agent in its own data folder, not the project. So the proxy answers 

21``initialize`` from a short run of the adapter in the image (``probe``), and 

22starts one backend (``docker exec -i`` of the adapter) per project, when a 

23``session/new`` names that project's folder. Each backend gets the client's 

24``initialize`` replayed first. 

25 

26Nothing here knows about Click or the container manager; the CLI module wires 

27the backend factory and the probe. 

28""" 

29 

30from __future__ import annotations 

31 

32import copy 

33import json 

34import logging 

35import re 

36import subprocess 

37import sys 

38import threading 

39from collections.abc import Callable, Iterator 

40from dataclasses import dataclass, field 

41from typing import IO, Any 

42from urllib.parse import quote, unquote 

43 

44logger = logging.getLogger(__name__) 

45 

46JsonObj = dict[str, Any] 

47 

48# JSON-RPC error codes the proxy answers with. 

49INVALID_PARAMS = -32602 

50INTERNAL_ERROR = -32603 

51# ACP's ``authRequired``: the client offers the agent's auth methods and retries. 

52AUTH_REQUIRED = -32000 

53 

54BACKEND_START_TIMEOUT = 180.0 

55 

56_DRIVE_RE = re.compile(r"^[A-Za-z]:[\\/]") 

57_FILE_URI_RE = re.compile(r"^file://", re.IGNORECASE) 

58 

59 

60# ============================================================================= 

61# Path mapping 

62# ============================================================================= 

63 

64 

65def _is_windows_path(path: str) -> bool: 

66 return bool(_DRIVE_RE.match(path)) or path.startswith("\\\\") 

67 

68 

69@dataclass(frozen=True) 

70class PathMap: 

71 """One project root on the host and the same folder in the container.""" 

72 

73 host_root: str 

74 container_root: str 

75 

76 @property 

77 def _windows(self) -> bool: 

78 return _is_windows_path(self.host_root) 

79 

80 def _host_rest(self, value: str) -> str | None: 

81 """The part of *value* below the host root, with ``/`` separators.""" 

82 root = self.host_root.rstrip("\\/") 

83 if self._windows: 

84 norm_value = value.replace("/", "\\") 

85 norm_root = root.replace("/", "\\") 

86 if norm_value.lower() == norm_root.lower(): 

87 return "" 

88 if norm_value.lower().startswith(norm_root.lower() + "\\"): 

89 return norm_value[len(norm_root) + 1 :].replace("\\", "/") 

90 return None 

91 if value == root: 

92 return "" 

93 if value.startswith(root + "/"): 

94 return value[len(root) + 1 :] 

95 return None 

96 

97 def _container_rest(self, value: str) -> str | None: 

98 root = self.container_root.rstrip("/") 

99 if value == root: 

100 return "" 

101 if value.startswith(root + "/"): 

102 return value[len(root) + 1 :] 

103 return None 

104 

105 def host_to_container(self, value: str) -> str | None: 

106 """Map a host path or ``file://`` URI; ``None`` when it is outside the project.""" 

107 if _FILE_URI_RE.match(value): 

108 path = unquote(value[len("file://") :]) 

109 if re.match(r"^/[A-Za-z]:[\\/]", path): 

110 path = path[1:] 

111 rest = self._host_rest(path) 

112 if rest is None: 

113 return None 

114 mapped = self.container_root.rstrip("/") + ("/" + rest if rest else "") 

115 return "file://" + quote(mapped, safe="/") 

116 rest = self._host_rest(value) 

117 if rest is None: 

118 return None 

119 return self.container_root.rstrip("/") + ("/" + rest if rest else "") 

120 

121 def container_to_host(self, value: str) -> str | None: 

122 """Map a container path or ``file://`` URI; ``None`` when it is outside the project.""" 

123 if _FILE_URI_RE.match(value): 

124 rest = self._container_rest(unquote(value[len("file://") :])) 

125 if rest is None: 

126 return None 

127 host = self._join_host(rest).replace("\\", "/") 

128 prefix = "file:///" if self._windows else "file://" 

129 return prefix + quote(host.lstrip("/") if self._windows else host, safe="/:") 

130 rest = self._container_rest(value) 

131 if rest is None: 

132 return None 

133 return self._join_host(rest) 

134 

135 def _join_host(self, rest: str) -> str: 

136 root = self.host_root.rstrip("\\/") 

137 if not rest: 

138 return root 

139 if self._windows: 

140 return root + "\\" + rest.replace("/", "\\") 

141 return root + "/" + rest 

142 

143 def is_container_path(self, value: str) -> bool: 

144 return self._container_rest(value) is not None 

145 

146 

147def map_strings(value: Any, fn: Callable[[str], str | None]) -> Any: 

148 """Return *value* with every string that *fn* maps replaced; other values unchanged.""" 

149 if isinstance(value, str): 

150 mapped = fn(value) 

151 return value if mapped is None else mapped 

152 if isinstance(value, list): 

153 return [map_strings(item, fn) for item in value] 

154 if isinstance(value, dict): 

155 return {key: map_strings(item, fn) for key, item in value.items()} 

156 return value 

157 

158 

159# ============================================================================= 

160# Message filters 

161# ============================================================================= 

162 

163 

164def sandbox_client_capabilities(params: JsonObj) -> JsonObj: 

165 """``initialize`` params with the host-side client capabilities turned off.""" 

166 out = copy.deepcopy(params) 

167 caps = out.get("clientCapabilities") 

168 if not isinstance(caps, dict): 

169 return out 

170 caps["fs"] = {"readTextFile": False, "writeTextFile": False} 

171 caps["terminal"] = False 

172 auth = caps.get("auth") 

173 if isinstance(auth, dict): 

174 auth.pop("terminal", None) 

175 meta = caps.get("_meta") 

176 if isinstance(meta, dict): 

177 # The adapter would offer a sign-in that the client runs in a host terminal. 

178 meta.pop("terminal-auth", None) 

179 return out 

180 

181 

182def client_runs_terminal_auth(params: JsonObj) -> bool: 

183 """True when the client runs an auth method's command in a terminal on the host.""" 

184 caps = params.get("clientCapabilities") 

185 if not isinstance(caps, dict): 

186 return False 

187 auth = caps.get("auth") 

188 meta = caps.get("_meta") 

189 return (isinstance(auth, dict) and auth.get("terminal") is True) or ( 

190 isinstance(meta, dict) and meta.get("terminal-auth") is True 

191 ) 

192 

193 

194def terminal_login_method(method_id: str, name: str, command: str, args: list[str]) -> JsonObj: 

195 """An ACP ``terminal`` auth method, in both the spec form and JetBrains' ``_meta`` form. 

196 

197 In the spec form the client runs the agent's own command with *args*; that 

198 command is ``ai-shell`` here, so both forms run the same thing. 

199 """ 

200 return { 

201 "id": method_id, 

202 "name": name, 

203 "description": "Sign in to Claude in the dev container (opens only when the login expired)", 

204 "type": "terminal", 

205 "args": list(args), 

206 "_meta": {"terminal-auth": {"command": command, "args": list(args), "label": name}}, 

207 } 

208 

209 

210SESSION_SETUP_METHODS = frozenset({"session/new", "session/load", "session/resume", "session/fork"}) 

211 

212 

213def prepare_session_params( 

214 params: JsonObj, 

215 pathmap: PathMap, 

216 extra_mcp_servers: list[JsonObj], 

217) -> JsonObj: 

218 """Map paths for the container and swap the client's MCP servers for ai-shell's.""" 

219 out = map_strings(params, pathmap.host_to_container) 

220 if not isinstance(out, dict): # pragma: no cover - params is always an object 

221 return params 

222 dropped = [ 

223 server.get("name", "?") 

224 for server in out.get("mcpServers") or [] 

225 if isinstance(server, dict) 

226 ] 

227 if dropped: 

228 logger.info("Not passing the client's MCP servers into the container: %s", dropped) 

229 out["mcpServers"] = copy.deepcopy(extra_mcp_servers) 

230 # Folders outside the project do not exist in the container. 

231 dirs = out.get("additionalDirectories") 

232 if isinstance(dirs, list): 

233 out["additionalDirectories"] = [ 

234 d for d in dirs if isinstance(d, str) and pathmap.is_container_path(d) 

235 ] 

236 meta = out.get("_meta") 

237 if isinstance(meta, dict) and isinstance(meta.get("additionalRoots"), list): 

238 meta["additionalRoots"] = [ 

239 d 

240 for d in meta["additionalRoots"] 

241 if isinstance(d, str) and pathmap.is_container_path(d) 

242 ] 

243 return out 

244 

245 

246def stdio_mcp_server(name: str, spec: JsonObj) -> JsonObj: 

247 """An ACP ``McpServer`` (stdio) from a Claude-style ``{command, args, env}`` spec.""" 

248 env = spec.get("env") or {} 

249 return { 

250 "name": name, 

251 "command": spec["command"], 

252 "args": list(spec.get("args") or []), 

253 "env": [{"name": k, "value": str(v)} for k, v in env.items()], 

254 } 

255 

256 

257# ============================================================================= 

258# Backends 

259# ============================================================================= 

260 

261 

262class Backend: 

263 """One adapter process in one dev container, for one project.""" 

264 

265 def __init__(self, label: str, pathmap: PathMap, extra_mcp_servers: list[JsonObj]) -> None: 

266 self.label = label 

267 self.pathmap = pathmap 

268 self.extra_mcp_servers = extra_mcp_servers 

269 self.alive = True 

270 # Returns True when the agent's login is missing or expired. None: never checked. 

271 self.needs_login: Callable[[], bool] | None = None 

272 # Runs before the first session setup that passed the login check, and 

273 # again after a sign-in (it may set extra_mcp_servers). 

274 self.prepare_session: Callable[[], None] | None = None 

275 self.session_prepared = False 

276 

277 def send(self, msg: JsonObj) -> None: # pragma: no cover - interface 

278 raise NotImplementedError 

279 

280 def close(self) -> None: # pragma: no cover - interface 

281 pass 

282 

283 

284class ProcessBackend(Backend): 

285 """A backend that talks to a subprocess (``docker exec -i ...``) over stdio.""" 

286 

287 def __init__( 

288 self, 

289 label: str, 

290 pathmap: PathMap, 

291 argv: list[str], 

292 extra_mcp_servers: list[JsonObj] | None = None, 

293 ) -> None: 

294 super().__init__(label, pathmap, extra_mcp_servers or []) 

295 logger.debug("acp backend %s: %s", label, " ".join(argv)) 

296 self.proc = subprocess.Popen( # noqa: S603 - argv built by ai-shell 

297 argv, 

298 stdin=subprocess.PIPE, 

299 stdout=subprocess.PIPE, 

300 stderr=sys.stderr, 

301 ) 

302 self._lock = threading.Lock() 

303 

304 def send(self, msg: JsonObj) -> None: 

305 data = (json.dumps(msg, ensure_ascii=False) + "\n").encode("utf-8") 

306 with self._lock: 

307 assert self.proc.stdin is not None 

308 self.proc.stdin.write(data) 

309 self.proc.stdin.flush() 

310 

311 def lines(self) -> Iterator[bytes]: 

312 assert self.proc.stdout is not None 

313 yield from self.proc.stdout 

314 

315 def close(self) -> None: 

316 self.alive = False 

317 try: 

318 if self.proc.stdin: 

319 self.proc.stdin.close() 

320 except OSError: 

321 pass 

322 try: 

323 self.proc.terminate() 

324 except OSError: 

325 pass 

326 

327 

328def probe_initialize(argv: list[str], params: JsonObj, timeout: float = 120.0) -> JsonObj: 

329 """Run the adapter once (``argv``), send ``initialize``, return its result. 

330 

331 The result of ``initialize`` names the adapter's capabilities; it does not 

332 depend on the project, so a run without one answers it. 

333 """ 

334 proc = subprocess.Popen( # noqa: S603 - argv built by ai-shell 

335 argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=sys.stderr 

336 ) 

337 result: dict[str, Any] = {} 

338 

339 def read() -> None: 

340 assert proc.stdout is not None 

341 for raw in proc.stdout: 

342 try: 

343 msg = json.loads(raw) 

344 except ValueError: 

345 continue 

346 if isinstance(msg, dict) and msg.get("id") == "probe-init": 

347 result["msg"] = msg 

348 return 

349 

350 reader = threading.Thread(target=read, daemon=True) 

351 reader.start() 

352 try: 

353 assert proc.stdin is not None 

354 request = {"jsonrpc": "2.0", "id": "probe-init", "method": "initialize", "params": params} 

355 proc.stdin.write((json.dumps(request) + "\n").encode("utf-8")) 

356 proc.stdin.flush() 

357 reader.join(timeout) 

358 finally: 

359 try: 

360 if proc.stdin: 

361 proc.stdin.close() 

362 except OSError: 

363 pass 

364 proc.kill() 

365 msg = result.get("msg") 

366 if msg is None: 

367 raise RuntimeError("the agent did not answer initialize") 

368 if "error" in msg: 

369 raise RuntimeError(f"the agent refused initialize: {msg['error']}") 

370 return dict(msg.get("result") or {}) 

371 

372 

373# ============================================================================= 

374# Router 

375# ============================================================================= 

376 

377 

378@dataclass 

379class _Pending: 

380 backend: Backend 

381 method: str 

382 

383 

384@dataclass 

385class AcpProxy: 

386 """Routes one ACP client to one backend per project. 

387 

388 *write_client* sends a message to the client. *backend_factory* starts the 

389 backend for a host folder (the ``cwd`` of a session). *probe* answers 

390 ``initialize`` before any backend exists. 

391 """ 

392 

393 write_client: Callable[[JsonObj], None] 

394 backend_factory: Callable[[str], Backend] 

395 probe: Callable[[JsonObj], JsonObj] 

396 folder_key: Callable[[str], str] = field(default=lambda p: p) 

397 # An ACP auth method that the client runs on the host (a terminal command). 

398 # It is offered only to clients that run terminal sign-ins. 

399 login_method: JsonObj | None = None 

400 

401 def __post_init__(self) -> None: 

402 self._lock = threading.RLock() 

403 self._init_params: JsonObj | None = None 

404 self._backends: dict[str, Backend] = {} 

405 self._start_locks: dict[str, threading.Lock] = {} 

406 self._sessions: dict[str, Backend] = {} 

407 self._pending: dict[Any, _Pending] = {} 

408 # Agent-to-client requests get proxy ids, so two backends never collide. 

409 self._agent_requests: dict[str, tuple[Backend, Any]] = {} 

410 self._next_agent_id = 0 

411 self._init_waiters: dict[int, threading.Event] = {} 

412 self._init_results: dict[int, JsonObj] = {} 

413 self._last_backend: Backend | None = None 

414 self._login_backend: Backend | None = None 

415 

416 # -- client side ---------------------------------------------------------- 

417 

418 def handle_client(self, msg: JsonObj) -> None: 

419 method = msg.get("method") 

420 has_id = "id" in msg 

421 if method is None and has_id: 

422 self._client_response(msg) 

423 return 

424 if method is None: 

425 return 

426 try: 

427 if method == "initialize" and has_id: 

428 self._initialize(msg) 

429 return 

430 if method == "authenticate" and has_id and self._is_own_login(msg): 

431 self._authenticate(msg) 

432 return 

433 backend = self._route(method, msg.get("params") or {}) 

434 if ( 

435 backend is not None 

436 and has_id 

437 and method in SESSION_SETUP_METHODS 

438 and backend.needs_login is not None 

439 and backend.needs_login() 

440 ): 

441 with self._lock: 

442 self._login_backend = backend 

443 self._error( 

444 msg["id"], 

445 AUTH_REQUIRED, 

446 f"ai-shell: {backend.label} needs a sign-in. {self._login_hint()}", 

447 ) 

448 return 

449 if ( 

450 backend is not None 

451 and method in SESSION_SETUP_METHODS 

452 and backend.prepare_session is not None 

453 and not backend.session_prepared 

454 ): 

455 backend.prepare_session() 

456 backend.session_prepared = True 

457 except Exception as exc: # noqa: BLE001 - every failure goes back to the client 

458 logger.warning("acp: %s failed: %s", method, exc) 

459 if has_id: 

460 self._error(msg["id"], INTERNAL_ERROR, f"ai-shell: {exc}") 

461 return 

462 if backend is None: 

463 if has_id: 

464 self._error( 

465 msg["id"], INVALID_PARAMS, f"ai-shell: no session for {method}; open one first" 

466 ) 

467 return 

468 params = msg.get("params") 

469 if method in SESSION_SETUP_METHODS and isinstance(params, dict): 

470 params = prepare_session_params(params, backend.pathmap, backend.extra_mcp_servers) 

471 else: 

472 params = map_strings(params, backend.pathmap.host_to_container) 

473 out = dict(msg) 

474 if params is not None: 

475 out["params"] = params 

476 if has_id: 

477 with self._lock: 

478 self._pending[msg["id"]] = _Pending(backend, method) 

479 if method in {"session/load", "session/resume"} and isinstance(params, dict): 

480 sid = params.get("sessionId") 

481 if isinstance(sid, str): 

482 with self._lock: 

483 self._sessions[sid] = backend 

484 backend.send(out) 

485 

486 def _initialize(self, msg: JsonObj) -> None: 

487 raw = msg.get("params") or {} 

488 params = sandbox_client_capabilities(raw) 

489 with self._lock: 

490 self._init_params = params 

491 result = dict(self.probe(params)) 

492 if self.login_method is not None and client_runs_terminal_auth(raw): 

493 # The adapter's own sign-ins would run its container command on 

494 # the host; the client was told it cannot, so only ai-shell's is offered. 

495 result["authMethods"] = [copy.deepcopy(self.login_method)] 

496 self.write_client({"jsonrpc": "2.0", "id": msg["id"], "result": result}) 

497 

498 def _is_own_login(self, msg: JsonObj) -> bool: 

499 params = msg.get("params") 

500 return ( 

501 self.login_method is not None 

502 and isinstance(params, dict) 

503 and params.get("methodId") == self.login_method.get("id") 

504 ) 

505 

506 def _login_hint(self) -> str: 

507 if self.login_method is None: 

508 return "Sign in from a terminal." 

509 meta = (self.login_method.get("_meta") or {}).get("terminal-auth") or {} 

510 command = " ".join([str(meta.get("command", "ai-shell")), *map(str, meta.get("args", []))]) 

511 return f"Sign in, or run in a terminal: {command}" 

512 

513 def _authenticate(self, msg: JsonObj) -> None: 

514 """The client ran ai-shell's sign-in; answer whether the login is good now.""" 

515 with self._lock: 

516 backend = self._login_backend or self._last_backend 

517 if backend is not None and backend.needs_login is not None and backend.needs_login(): 

518 self._error( 

519 msg["id"], AUTH_REQUIRED, f"ai-shell: {backend.label} is still not signed in" 

520 ) 

521 return 

522 with self._lock: 

523 self._login_backend = None 

524 # The sign-in may have closed the debug-port Chrome; attach it again. 

525 for each in self._backends.values(): 

526 each.session_prepared = False 

527 self.write_client({"jsonrpc": "2.0", "id": msg["id"], "result": {}}) 

528 

529 def _route(self, method: str, params: JsonObj) -> Backend | None: 

530 cwd = params.get("cwd") if isinstance(params, dict) else None 

531 if method in SESSION_SETUP_METHODS or (method == "session/list" and cwd): 

532 if not isinstance(cwd, str) or not cwd: 

533 raise ValueError(f"{method} needs a cwd") 

534 return self._backend_for(cwd) 

535 sid = params.get("sessionId") if isinstance(params, dict) else None 

536 with self._lock: 

537 if isinstance(sid, str): 

538 return self._sessions.get(sid) 

539 if method == "$/cancel_request": 

540 pending = self._pending.get(params.get("requestId")) 

541 return pending.backend if pending else None 

542 return self._last_backend 

543 

544 def _backend_for(self, cwd: str) -> Backend: 

545 key = self.folder_key(cwd) 

546 with self._lock: 

547 start_lock = self._start_locks.setdefault(key, threading.Lock()) 

548 # One start per folder at a time: two sessions opened together share it. 

549 with start_lock: 

550 with self._lock: 

551 backend = self._backends.get(key) 

552 if backend is not None and backend.alive: 

553 self._last_backend = backend 

554 return backend 

555 init_params = self._init_params 

556 if init_params is None: 

557 raise ValueError("initialize must come first") 

558 backend = self.backend_factory(cwd) 

559 self._replay_initialize(backend, init_params) 

560 with self._lock: 

561 self._backends[key] = backend 

562 self._last_backend = backend 

563 return backend 

564 

565 def _replay_initialize(self, backend: Backend, params: JsonObj) -> None: 

566 with self._lock: 

567 self._next_agent_id += 1 

568 ident = self._next_agent_id 

569 event = threading.Event() 

570 self._init_waiters[ident] = event 

571 backend.send( 

572 { 

573 "jsonrpc": "2.0", 

574 "id": f"ai-shell-init-{ident}", 

575 "method": "initialize", 

576 "params": params, 

577 } 

578 ) 

579 if not event.wait(BACKEND_START_TIMEOUT): 

580 backend.close() 

581 raise RuntimeError(f"{backend.label}: the agent did not answer initialize") 

582 with self._lock: 

583 result = self._init_results.pop(ident, {}) 

584 if not result: 

585 backend.close() 

586 raise RuntimeError(f"{backend.label}: the agent stopped before it answered initialize") 

587 if "error" in result: 

588 backend.close() 

589 raise RuntimeError(f"{backend.label}: initialize failed: {result['error']}") 

590 

591 def _client_response(self, msg: JsonObj) -> None: 

592 with self._lock: 

593 entry = self._agent_requests.pop(str(msg["id"]), None) 

594 if entry is None: 

595 return 

596 backend, original_id = entry 

597 out = map_strings(msg, backend.pathmap.host_to_container) 

598 out["id"] = original_id 

599 backend.send(out) 

600 

601 def _error(self, ident: Any, code: int, message: str) -> None: 

602 self.write_client( 

603 {"jsonrpc": "2.0", "id": ident, "error": {"code": code, "message": message}} 

604 ) 

605 

606 # -- agent side ----------------------------------------------------------- 

607 

608 def handle_backend(self, backend: Backend, msg: JsonObj) -> None: 

609 method = msg.get("method") 

610 ident = msg.get("id") 

611 if method is None and ident is not None: 

612 if isinstance(ident, str) and ident.startswith("ai-shell-init-"): 

613 num = int(ident.rsplit("-", 1)[1]) 

614 with self._lock: 

615 self._init_results[num] = msg 

616 waiter = self._init_waiters.pop(num, None) 

617 if waiter: 

618 waiter.set() 

619 return 

620 with self._lock: 

621 pending = self._pending.pop(ident, None) 

622 if pending is None: 

623 return 

624 out = map_strings(msg, backend.pathmap.container_to_host) 

625 if pending.method in {"session/new", "session/fork"}: 

626 sid = (msg.get("result") or {}).get("sessionId") 

627 if isinstance(sid, str): 

628 with self._lock: 

629 self._sessions[sid] = backend 

630 self.write_client(out) 

631 return 

632 out = map_strings(msg, backend.pathmap.container_to_host) 

633 if ident is not None: 

634 with self._lock: 

635 self._next_agent_id += 1 

636 proxy_id = f"ai-shell-{self._next_agent_id}" 

637 self._agent_requests[proxy_id] = (backend, ident) 

638 out["id"] = proxy_id 

639 self.write_client(out) 

640 

641 def backend_exited(self, backend: Backend) -> None: 

642 """Fail what the backend still owed and forget it, so the next session restarts it.""" 

643 backend.alive = False 

644 with self._lock: 

645 owed = [ident for ident, p in self._pending.items() if p.backend is backend] 

646 for ident in owed: 

647 del self._pending[ident] 

648 for sid in [s for s, b in self._sessions.items() if b is backend]: 

649 del self._sessions[sid] 

650 for key in [k for k, b in self._backends.items() if b is backend]: 

651 del self._backends[key] 

652 for pid in [p for p, (b, _) in self._agent_requests.items() if b is backend]: 

653 del self._agent_requests[pid] 

654 if self._last_backend is backend: 

655 self._last_backend = None 

656 waiters = list(self._init_waiters.values()) 

657 for ident in owed: 

658 self._error(ident, INTERNAL_ERROR, f"ai-shell: the agent in {backend.label} stopped") 

659 for waiter in waiters: 

660 waiter.set() 

661 

662 def close(self) -> None: 

663 with self._lock: 

664 backends = list(self._backends.values()) 

665 for backend in backends: 

666 backend.close() 

667 

668 

669# ============================================================================= 

670# stdio loop 

671# ============================================================================= 

672 

673 

674def _decode(raw: bytes | str) -> JsonObj | None: 

675 try: 

676 msg = json.loads(raw) 

677 except ValueError: 

678 logger.warning("acp: ignoring a line that is not JSON") 

679 return None 

680 return msg if isinstance(msg, dict) else None 

681 

682 

683def run_stdio( 

684 proxy_factory: Callable[[Callable[[JsonObj], None]], AcpProxy], 

685 client_in: IO[bytes], 

686 client_out: IO[bytes], 

687) -> None: 

688 """Serve one ACP client on *client_in*/*client_out* until it closes stdin.""" 

689 write_lock = threading.Lock() 

690 

691 def write_client(msg: JsonObj) -> None: 

692 data = (json.dumps(msg, ensure_ascii=False) + "\n").encode("utf-8") 

693 with write_lock: 

694 client_out.write(data) 

695 client_out.flush() 

696 

697 proxy = proxy_factory(write_client) 

698 try: 

699 for raw in client_in: 

700 if not raw.strip(): 

701 continue 

702 msg = _decode(raw) 

703 if msg is None: 

704 continue 

705 # A session setup may start a container, so it runs on its own 

706 # thread and the client's other messages (cancel, answers) keep 

707 # flowing. Everything else is handled in order. 

708 if msg.get("method") in SESSION_SETUP_METHODS or msg.get("method") == "session/list": 

709 threading.Thread(target=proxy.handle_client, args=(msg,), daemon=True).start() 

710 else: 

711 proxy.handle_client(msg) 

712 finally: 

713 proxy.close() 

714 

715 

716def pump_backend(proxy: AcpProxy, backend: ProcessBackend) -> threading.Thread: 

717 """Forward the backend's stdout to the proxy on a daemon thread.""" 

718 

719 def run() -> None: 

720 for raw in backend.lines(): 

721 if not raw.strip(): 

722 continue 

723 msg = _decode(raw) 

724 if msg is not None: 

725 proxy.handle_backend(backend, msg) 

726 proxy.backend_exited(backend) 

727 

728 thread = threading.Thread(target=run, daemon=True) 

729 thread.start() 

730 return thread