noah-code 2.0.0__py3-none-any.whl → 2.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. noah_code/__init__.py +1 -1
  2. noah_code/acp.py +305 -54
  3. noah_code/agent.py +87 -22
  4. noah_code/budget.py +103 -27
  5. noah_code/checkpoints.py +443 -66
  6. noah_code/cli.py +386 -14
  7. noah_code/codex_client.py +266 -124
  8. noah_code/codex_rpc.py +76 -21
  9. noah_code/composer.py +32 -1
  10. noah_code/credentials.py +26 -0
  11. noah_code/event_bridge.py +13 -2
  12. noah_code/hooks.py +3 -0
  13. noah_code/host.py +562 -1334
  14. noah_code/host_commands.py +1247 -0
  15. noah_code/llm.py +99 -6
  16. noah_code/llm_replies.py +67 -1
  17. noah_code/macos_sandbox.py +127 -0
  18. noah_code/mcp_setup.py +279 -3
  19. noah_code/model_streaming.py +276 -39
  20. noah_code/nooa_compat.py +64 -1
  21. noah_code/permissions.py +235 -57
  22. noah_code/runtime_state.py +111 -38
  23. noah_code/service.py +124 -9
  24. noah_code/sessions.py +55 -11
  25. noah_code/skills_setup.py +202 -6
  26. noah_code/snapshots.py +207 -43
  27. noah_code/summarization.py +272 -13
  28. noah_code/telemetry.py +115 -9
  29. noah_code/tool_contracts.py +15 -0
  30. noah_code/tools/lsp_tools.py +561 -30
  31. noah_code/tools/process_tools.py +77 -39
  32. noah_code/tools/task_tools.py +395 -43
  33. noah_code/tools/workspace_tools.py +169 -25
  34. noah_code/ui/clipboard.py +342 -0
  35. noah_code/ui/diff_screen.py +558 -0
  36. noah_code/ui/modals.py +1882 -0
  37. noah_code/ui/textual_app.py +379 -2451
  38. noah_code/usage.py +17 -1
  39. noah_code/verification.py +250 -25
  40. noah_code/worktree.py +159 -7
  41. {noah_code-2.0.0.dist-info → noah_code-2.1.0.dist-info}/METADATA +3 -2
  42. noah_code-2.1.0.dist-info/RECORD +82 -0
  43. noah_code-2.0.0.dist-info/RECORD +0 -78
  44. {noah_code-2.0.0.dist-info → noah_code-2.1.0.dist-info}/WHEEL +0 -0
  45. {noah_code-2.0.0.dist-info → noah_code-2.1.0.dist-info}/entry_points.txt +0 -0
noah_code/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
1
  """Noah Code: terminal coding agent on NVIDIA OO Agents."""
2
2
 
3
- __version__ = "2.0.0"
3
+ __version__ = "2.1.0"
noah_code/acp.py CHANGED
@@ -7,20 +7,27 @@ https://github.com/agentclientprotocol/agent-client-protocol/blob/main/schema/v1
7
7
  from __future__ import annotations
8
8
 
9
9
  import asyncio
10
+ import base64
10
11
  import contextlib
11
12
  import json
12
13
  import sys
14
+ import time
13
15
  import uuid
14
- from collections.abc import Callable
15
- from typing import Any
16
+ from collections.abc import Callable, Mapping
17
+ from pathlib import Path
18
+ from typing import Any, Literal
19
+ from urllib.parse import urlparse
16
20
 
17
21
  from noah_code import __version__
18
22
  from noah_code.approvals import ApprovalChoice, ApprovalRequest
23
+ from noah_code.permissions import PermissionDecision
19
24
  from noah_code.redaction import safe_error_message
20
25
  from noah_code.service import AgentService, ServiceError, ServiceSession
21
26
 
22
27
  MAX_FRAME_BYTES = 1_048_576
23
28
 
29
+ ToolKind = Literal["read", "edit", "search", "execute", "fetch", "think", "other"]
30
+
24
31
 
25
32
  class RPCError(Exception):
26
33
  def __init__(self, code: int, message: str) -> None:
@@ -35,6 +42,55 @@ def _string(params: dict[str, Any], name: str) -> str:
35
42
  return value
36
43
 
37
44
 
45
+ def _infer_tool_kind(
46
+ title: str,
47
+ meta: Mapping[str, Any] | None = None,
48
+ *,
49
+ category: str = "",
50
+ ) -> ToolKind:
51
+ cat = category.strip().lower()
52
+ if cat == "edit":
53
+ return "edit"
54
+ if cat in {"read", "lsp"}:
55
+ return "read"
56
+ if cat == "bash":
57
+ return "execute"
58
+ if cat == "websearch":
59
+ return "search"
60
+ if cat == "webfetch":
61
+ return "fetch"
62
+
63
+ segments = [seg.strip() for seg in title.split("·") if seg.strip()]
64
+ verbs = [seg.split(None, 1)[0].rstrip(":").lower() for seg in segments if seg]
65
+ if any(v in {"edit", "write", "replace", "patch", "apply_patch"} for v in verbs):
66
+ return "edit"
67
+ if any(v in {"bash", "process", "run", "shell", "terminal"} for v in verbs):
68
+ return "execute"
69
+ if any(v in {"fetch", "webfetch"} for v in verbs):
70
+ return "fetch"
71
+ if any(v in {"grep", "glob", "search", "websearch", "find"} for v in verbs):
72
+ return "search"
73
+ if any(v in {"read", "inspect", "lsp", "git"} for v in verbs):
74
+ return "read"
75
+ if any(v in {"think", "todos", "plan", "reasoning"} for v in verbs):
76
+ return "think"
77
+
78
+ tool_name = str((meta or {}).get("tool") or title).strip().lower()
79
+ if tool_name in {"write", "write_file", "edit", "replace", "apply_patch", "apply_unified_diff"}:
80
+ return "edit"
81
+ if tool_name in {"read", "ws_read", "inspect"} or tool_name.startswith("lsp"):
82
+ return "read"
83
+ if tool_name in {"search", "grep", "glob", "list", "list_files", "websearch"}:
84
+ return "search"
85
+ if tool_name in {"fetch", "webfetch"}:
86
+ return "fetch"
87
+ if tool_name in {"bash", "sh", "run", "terminal_run"} or tool_name.startswith("process"):
88
+ return "execute"
89
+ if tool_name in {"think", "todos", "plan"}:
90
+ return "think"
91
+ return "other"
92
+
93
+
38
94
  def _prompt_text(blocks: Any) -> str:
39
95
  if not isinstance(blocks, list) or not blocks or len(blocks) > 100:
40
96
  raise RPCError(-32602, "prompt must contain 1 to 100 content blocks")
@@ -42,48 +98,132 @@ def _prompt_text(blocks: Any) -> str:
42
98
  for block in blocks:
43
99
  if not isinstance(block, dict):
44
100
  raise RPCError(-32602, "invalid prompt content block")
45
- if block.get("type") == "text":
101
+ btype = block.get("type")
102
+ if btype == "text":
46
103
  parts.append(_string(block, "text"))
47
- elif block.get("type") == "resource_link":
104
+ elif btype == "resource_link":
48
105
  # References stay references. Host tools perform any subsequent
49
106
  # reads/fetches with the existing path and network permission gates.
50
107
  parts.append(
51
108
  f"Referenced resource: {_string(block, 'name')}\nURI: {_string(block, 'uri')}"
52
109
  )
110
+ elif btype == "resource":
111
+ res = block.get("resource") if isinstance(block.get("resource"), dict) else block
112
+ if not isinstance(res, dict):
113
+ raise RPCError(-32602, "invalid resource content block")
114
+ uri = _string(res, "uri")
115
+ mime = res.get("mimeType")
116
+ mime_label = f", {mime.strip()}" if isinstance(mime, str) and mime.strip() else ""
117
+ res_text = res.get("text")
118
+ res_blob = res.get("blob")
119
+ if isinstance(res_text, str):
120
+ parts.append(f"Embedded resource ({uri}{mime_label}):\n{res_text[:120_000]}")
121
+ elif isinstance(res_blob, str) and res_blob.strip():
122
+ try:
123
+ raw = base64.b64decode(res_blob, validate=True)
124
+ except ValueError as exc:
125
+ raise RPCError(-32602, "invalid base64 resource blob") from exc
126
+ parts.append(
127
+ f"Embedded binary resource ({uri}{mime_label}, {len(raw)} bytes)"
128
+ )
129
+ else:
130
+ raise RPCError(-32602, "resource block must contain text or blob")
131
+ elif btype == "image":
132
+ mime_type = _string(block, "mimeType")
133
+ if not mime_type.lower().startswith("image/"):
134
+ raise RPCError(-32602, "image mimeType must start with 'image/'")
135
+ data = block.get("data")
136
+ image_uri = block.get("uri")
137
+ if isinstance(data, str) and data.strip():
138
+ try:
139
+ raw = base64.b64decode(data, validate=True)
140
+ except ValueError as exc:
141
+ raise RPCError(-32602, "invalid base64 image data") from exc
142
+ uri_note = (
143
+ f", uri={image_uri.strip()}"
144
+ if isinstance(image_uri, str) and image_uri.strip()
145
+ else ""
146
+ )
147
+ parts.append(f"[Image: {mime_type}, {len(raw)} bytes{uri_note}]")
148
+ elif isinstance(image_uri, str) and image_uri.strip():
149
+ parts.append(f"[Image: {mime_type}, uri={image_uri.strip()}]")
150
+ else:
151
+ raise RPCError(-32602, "image block requires base64 data or uri")
53
152
  else:
54
- raise RPCError(-32602, "only text and resource_link prompt blocks are supported")
153
+ raise RPCError(
154
+ -32602,
155
+ "only text, resource_link, resource, and image prompt blocks are supported",
156
+ )
55
157
  return "\n\n".join(parts)
56
158
 
57
159
 
58
160
  def _mcp_servers(params: dict[str, Any]) -> dict[str, dict[str, Any]]:
59
- from pathlib import Path
60
-
61
161
  servers = params.get("mcpServers")
62
162
  if not isinstance(servers, list) or len(servers) > 32:
63
- raise RPCError(-32602, "mcpServers must be an array of at most 32 stdio servers")
163
+ raise RPCError(-32602, "mcpServers must be an array of at most 32 servers")
64
164
  result: dict[str, dict[str, Any]] = {}
65
165
  for server in servers:
66
- if not isinstance(server, dict) or server.get("type") not in {None, "stdio"}:
67
- raise RPCError(-32602, "only stdio MCP servers are supported")
68
- name, command = _string(server, "name"), _string(server, "command")
69
- if name in result or not Path(command).is_absolute():
70
- raise RPCError(-32602, "MCP names must be unique and commands must be absolute paths")
71
- args, env = server.get("args"), server.get("env", [])
72
- if (
73
- not isinstance(args, list)
74
- or any(not isinstance(item, str) for item in args)
75
- or not isinstance(env, list)
76
- ):
77
- raise RPCError(-32602, "invalid stdio MCP args or env")
78
- environment: dict[str, str] = {}
79
- for item in env:
80
- if not isinstance(item, dict) or not isinstance(item.get("value"), str):
81
- raise RPCError(-32602, "invalid MCP environment variable")
82
- key = _string(item, "name")
83
- if "=" in key or "\0" in key or "\0" in item["value"]:
84
- raise RPCError(-32602, "invalid MCP environment variable")
85
- environment[key] = item["value"]
86
- result[name] = {"transport": "stdio", "command": command, "args": args, "env": environment}
166
+ if not isinstance(server, dict):
167
+ raise RPCError(-32602, "invalid MCP server entry")
168
+ stype = server.get("type")
169
+ name = _string(server, "name")
170
+ if name in result:
171
+ raise RPCError(-32602, "MCP names must be unique")
172
+ if stype in {None, "stdio"}:
173
+ command = _string(server, "command")
174
+ if not Path(command).is_absolute():
175
+ raise RPCError(-32602, "stdio MCP commands must be absolute paths")
176
+ args, env = server.get("args"), server.get("env", [])
177
+ if (
178
+ not isinstance(args, list)
179
+ or any(not isinstance(item, str) for item in args)
180
+ or not isinstance(env, list)
181
+ ):
182
+ raise RPCError(-32602, "invalid stdio MCP args or env")
183
+ environment: dict[str, str] = {}
184
+ for item in env:
185
+ if not isinstance(item, dict) or not isinstance(item.get("value"), str):
186
+ raise RPCError(-32602, "invalid MCP environment variable")
187
+ key = _string(item, "name")
188
+ if "=" in key or "\0" in key or "\0" in item["value"]:
189
+ raise RPCError(-32602, "invalid MCP environment variable")
190
+ environment[key] = item["value"]
191
+ result[name] = {
192
+ "transport": "stdio",
193
+ "command": command,
194
+ "args": args,
195
+ "env": environment,
196
+ "trusted": False,
197
+ }
198
+ elif stype in {"http", "sse"}:
199
+ url = _string(server, "url")
200
+ parsed = urlparse(url)
201
+ if (
202
+ parsed.scheme not in {"http", "https"}
203
+ or not parsed.netloc
204
+ or any(ch in url for ch in "\r\n\0")
205
+ ):
206
+ raise RPCError(-32602, "MCP URL must be an absolute http(s) endpoint")
207
+ raw_headers = server.get("headers", [])
208
+ if not isinstance(raw_headers, list):
209
+ raise RPCError(-32602, "invalid MCP HTTP headers")
210
+ headers: dict[str, str] = {}
211
+ for item in raw_headers:
212
+ if not isinstance(item, dict) or not isinstance(item.get("value"), str):
213
+ raise RPCError(-32602, "invalid MCP HTTP header")
214
+ hname = _string(item, "name")
215
+ hval = item["value"]
216
+ if any(ch in hname or ch in hval for ch in "\r\n\0"):
217
+ raise RPCError(-32602, "invalid MCP HTTP header")
218
+ headers[hname] = hval
219
+ result[name] = {
220
+ "transport": "streamable-http" if stype == "http" else "sse",
221
+ "url": url,
222
+ "headers": headers,
223
+ "trusted": False,
224
+ }
225
+ else:
226
+ raise RPCError(-32602, "only stdio, http, and sse MCP servers are supported")
87
227
  return result
88
228
 
89
229
 
@@ -99,6 +239,7 @@ class ACPConnection:
99
239
  self._permission_responses: dict[str, asyncio.Future[dict[str, Any]]] = {}
100
240
  self._tasks: set[asyncio.Task[Any]] = set()
101
241
  self._loading: set[str] = set()
242
+ self._streamed_reasoning: dict[str, set[str]] = {}
102
243
 
103
244
  async def send(self, value: dict[str, Any]) -> None:
104
245
  data = (
@@ -132,6 +273,12 @@ class ACPConnection:
132
273
  future: asyncio.Future[dict[str, Any]] = asyncio.get_running_loop().create_future()
133
274
  self._permission_responses[request_id] = future
134
275
  decision = request.decision
276
+ title = f"{decision.category}: {decision.target}"[:8000]
277
+ tool_kind = _infer_tool_kind(
278
+ title,
279
+ {"tool": getattr(decision, "tool", "")},
280
+ category=str(decision.category),
281
+ )
135
282
  try:
136
283
  await self.send(
137
284
  {
@@ -141,8 +288,8 @@ class ACPConnection:
141
288
  "sessionId": session_id,
142
289
  "toolCall": {
143
290
  "toolCallId": request.id,
144
- "title": f"{decision.category}: {decision.target}"[:8000],
145
- "kind": "other",
291
+ "title": title,
292
+ "kind": tool_kind,
146
293
  "status": "pending",
147
294
  },
148
295
  "options": [
@@ -220,13 +367,14 @@ class ACPConnection:
220
367
  result = payload.get("result")
221
368
  result = result if isinstance(result, dict) else {}
222
369
  failed = result.get("result_status") in {"failed", "error", "fail"}
370
+ title = str(payload.get("name", "Recorded tool call"))
223
371
  await self.update(
224
372
  session.meta.session_id,
225
373
  {
226
374
  "sessionUpdate": "tool_call",
227
375
  "toolCallId": row.event_id,
228
- "title": str(payload.get("name", "Recorded tool call")),
229
- "kind": "other",
376
+ "title": title,
377
+ "kind": _infer_tool_kind(title, {"tool": title}),
230
378
  "status": "failed" if failed else "completed",
231
379
  },
232
380
  )
@@ -235,7 +383,22 @@ class ACPConnection:
235
383
  kind, text = event["kind"], event.get("text", "")
236
384
  if kind == "message":
237
385
  await self._message(session_id, text)
386
+ elif kind == "model_stream":
387
+ meta = event.get("meta")
388
+ if not isinstance(meta, dict):
389
+ return
390
+ phase = meta.get("phase")
391
+ call_id = str(meta.get("call_id") or "_active")
392
+ if phase == "reasoning" and text:
393
+ self._streamed_reasoning.setdefault(session_id, set()).add(call_id)
394
+ await self._message(session_id, text, kind="agent_thought_chunk")
395
+ elif phase in {"error", "cancel"}:
396
+ self._streamed_reasoning.get(session_id, set()).discard(call_id)
238
397
  elif kind == "reasoning":
398
+ streamed = self._streamed_reasoning.get(session_id)
399
+ if streamed:
400
+ streamed.pop()
401
+ return
239
402
  await self._message(session_id, text, kind="agent_thought_chunk")
240
403
  elif kind == "error" and text.strip():
241
404
  await self._message(session_id, f"Error: {text}")
@@ -251,7 +414,7 @@ class ACPConnection:
251
414
  "sessionUpdate": "tool_call",
252
415
  "toolCallId": tool_id,
253
416
  "title": text,
254
- "kind": "other",
417
+ "kind": _infer_tool_kind(text, meta),
255
418
  "status": "in_progress",
256
419
  },
257
420
  )
@@ -275,8 +438,9 @@ class ACPConnection:
275
438
  },
276
439
  )
277
440
  elif kind == "replay_gap":
278
- raise RPCError(
279
- -32603, "client could not keep up with session updates; reload the session"
441
+ await self._message(
442
+ session_id,
443
+ "[Note: some intermediate stream updates were skipped due to high output volume.]",
280
444
  )
281
445
 
282
446
  async def handle(self, method: str, params: dict[str, Any]) -> dict[str, Any] | None:
@@ -293,19 +457,17 @@ class ACPConnection:
293
457
  "agentCapabilities": {
294
458
  "loadSession": True,
295
459
  "promptCapabilities": {
296
- "image": False,
460
+ "image": True,
297
461
  "audio": False,
298
- "embeddedContext": False,
462
+ "embeddedContext": True,
299
463
  },
300
- "mcpCapabilities": {"http": False, "sse": False},
464
+ "mcpCapabilities": {"http": True, "sse": True},
301
465
  },
302
466
  "authMethods": [],
303
467
  }
304
468
  if not self.initialized:
305
469
  raise RPCError(-32600, "initialize must be called first")
306
470
  if method in {"session/new", "session/load"}:
307
- from pathlib import Path
308
-
309
471
  from noah_code.workspace import open_workspace
310
472
 
311
473
  cwd = _string(params, "cwd")
@@ -314,6 +476,7 @@ class ACPConnection:
314
476
  -32602, "cwd must be absolute; additional directories are unsupported"
315
477
  )
316
478
  session_id = _string(params, "sessionId") if method == "session/load" else None
479
+ mcp_servers = _mcp_servers(params)
317
480
  workspace_root = open_workspace(cwd).root
318
481
  for existing in list(self.service.sessions.values()):
319
482
  same_session = session_id is not None and existing.meta.session_id == session_id
@@ -322,10 +485,50 @@ class ACPConnection:
322
485
  if existing.active or existing.meta.session_id in self._loading:
323
486
  raise RPCError(-32000, "session is busy")
324
487
  await self.service.close_session(existing.meta.session_id)
488
+ approved_mcp: set[str] = set()
489
+
490
+ async def _open_approval(sid: str, request: ApprovalRequest) -> ApprovalChoice:
491
+ choice = await self._approval(sid, request)
492
+ if choice != ApprovalChoice.REJECT:
493
+ approved_mcp.add(str(request.decision.target))
494
+ return choice
495
+
325
496
  session = await self.service.open_session(
326
- cwd=cwd, session_id=session_id, mcp_servers=_mcp_servers(params)
497
+ cwd=cwd,
498
+ session_id=session_id,
499
+ mcp_servers=mcp_servers,
500
+ approval_handler=_open_approval,
327
501
  )
328
502
  self._bind_ui(session)
503
+ host_cfg = getattr(session.host, "config", self.service.config)
504
+ if not (getattr(host_cfg, "auto_approve", False) or getattr(host_cfg, "yolo", False)):
505
+ for srv_name, srv_spec in mcp_servers.items():
506
+ if (
507
+ srv_spec.get("transport") == "stdio"
508
+ and srv_spec.get("trusted") is False
509
+ and srv_name not in approved_mcp
510
+ ):
511
+ decision = PermissionDecision(
512
+ "mcp",
513
+ f"{srv_name} ({srv_spec.get('command', '')})",
514
+ "ask",
515
+ None,
516
+ "client-supplied stdio MCP server requires approval",
517
+ srv_name,
518
+ tool="mcp",
519
+ )
520
+ req = ApprovalRequest(
521
+ f"mcp-{uuid.uuid4().hex}",
522
+ decision,
523
+ time.time(),
524
+ asyncio.get_running_loop().create_future(),
525
+ )
526
+ choice = await self._approval(session.meta.session_id, req)
527
+ if choice == ApprovalChoice.REJECT:
528
+ await self.service.close_session(session.meta.session_id)
529
+ raise RPCError(
530
+ -32000, f"rejected client-supplied stdio MCP server: {srv_name}"
531
+ )
329
532
  if method == "session/load":
330
533
  session_id = session.meta.session_id
331
534
  if session.active or session_id in self._loading:
@@ -337,6 +540,48 @@ class ACPConnection:
337
540
  self._loading.discard(session_id)
338
541
  return {}
339
542
  return {"sessionId": session.meta.session_id}
543
+ if method == "session/set_mode":
544
+ session_id = _string(params, "sessionId")
545
+ raw_mode = params.get("modeId") if "modeId" in params else params.get("mode")
546
+ if not isinstance(raw_mode, str) or raw_mode.strip().lower() not in {"build", "plan"}:
547
+ raise RPCError(-32602, "modeId must be 'build' or 'plan'")
548
+ mode = raw_mode.strip().lower()
549
+ session = self.service.get(session_id)
550
+ async with session.lock:
551
+ if session.active:
552
+ raise RPCError(-32000, "session is busy")
553
+ if getattr(session.host, "_agent", None) is not None:
554
+ session.host.agent.set_mode(mode)
555
+ session.meta.mode = mode
556
+ if getattr(session.host, "meta", None) is not None:
557
+ session.host.meta.mode = mode
558
+ await asyncio.to_thread(self.service.store.save_meta, session.meta)
559
+ return {}
560
+ if method == "session/set_model":
561
+ session_id = _string(params, "sessionId")
562
+ raw_model = params.get("modelId") if "modelId" in params else params.get("model")
563
+ if (
564
+ not isinstance(raw_model, str)
565
+ or not raw_model.strip()
566
+ or any(ch.isspace() for ch in raw_model.strip())
567
+ ):
568
+ raise RPCError(-32602, "modelId must be a nonempty model identifier")
569
+ model = raw_model.strip()
570
+ session = self.service.get(session_id)
571
+ async with session.lock:
572
+ if session.active:
573
+ raise RPCError(-32000, "session is busy")
574
+ switch_fn = getattr(session.host, "_switch_model", None)
575
+ if callable(switch_fn) and getattr(session.host, "_agent", None) is not None:
576
+ await switch_fn(model)
577
+ else:
578
+ session.meta.model = model
579
+ if getattr(session.host, "meta", None) is not None:
580
+ session.host.meta.model = model
581
+ if hasattr(session.host, "config"):
582
+ session.host.config.model = model
583
+ await asyncio.to_thread(self.service.store.save_meta, session.meta)
584
+ return {}
340
585
  if method == "session/cancel":
341
586
  await self.service.cancel(_string(params, "sessionId"))
342
587
  return None
@@ -346,19 +591,25 @@ class ACPConnection:
346
591
  raise RPCError(-32000, "session history is still loading")
347
592
  session = self.service.get(session_id)
348
593
  after = session.ui.sequence
594
+ self._streamed_reasoning.pop(session_id, None)
349
595
  receipt = self.service.submit(session_id, _prompt_text(params.get("prompt")))
350
- async for event in session.ui.stream(after):
351
- if (
352
- event["kind"] == "turn_complete"
353
- and event["request_id"] == receipt["request_id"]
354
- ):
355
- result = event["result"]
356
- if result["status"] == "failed":
357
- raise RPCError(-32000, safe_error_message(result["explanation"]))
358
- return {
359
- "stopReason": "cancelled" if result["status"] == "cancelled" else "end_turn"
360
- }
361
- await self._event(session_id, event)
596
+ try:
597
+ async for event in session.ui.stream(after):
598
+ if (
599
+ event["kind"] == "turn_complete"
600
+ and event["request_id"] == receipt["request_id"]
601
+ ):
602
+ result = event["result"]
603
+ if result["status"] == "failed":
604
+ raise RPCError(-32000, safe_error_message(result["explanation"]))
605
+ return {
606
+ "stopReason": (
607
+ "cancelled" if result["status"] == "cancelled" else "end_turn"
608
+ )
609
+ }
610
+ await self._event(session_id, event)
611
+ finally:
612
+ self._streamed_reasoning.pop(session_id, None)
362
613
  raise RPCError(-32000, "session closed during prompt")
363
614
  raise RPCError(-32601, "method not found")
364
615