Coverage for app / inference / engines / graph_based.py: 89%

809 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2GraphBasedEngine — shared base for all LangGraph-backed execution types. 

3 

4Provides: 

5 _run_unified_graph() batch execution via compiled.ainvoke() 

6 _do_infer_stream() streaming execution via compiled.astream_events() 

7 _initial_state() GraphState construction from an InferenceContext 

8 _collect_usage() delta-input token accounting across message lists 

9 _collect_citations() citation extraction from completed tool messages 

10 

11Subclasses (AgentEngine, SkillEngine, GraphEngine) implement 

12_build_builder() to supply the appropriate AgentGraphBuilder, then inherit 

13both batch and streaming paths for free. 

14""" 

15 

16from __future__ import annotations 

17 

18import json 

19import time as _time 

20import uuid 

21from abc import abstractmethod 

22from typing import Any, AsyncIterator 

23 

24from langgraph.checkpoint.memory import MemorySaver 

25from langgraph.errors import GraphBubbleUp, GraphInterrupt 

26from langgraph.types import Command 

27 

28from app.agents.graph import ( 

29 ANSWERED_BY_KEY, 

30 GATE_NODE_ID, 

31 PLANNING_NODE_ID, 

32 RETRIEVAL_NODE_ID, 

33 INTERNAL_RETRIEVAL_NODE_ID, 

34 EXTERNAL_RETRIEVAL_NODE_ID, 

35 TOOL_RETRIEVAL_NODE_ID, 

36 KNOWLEDGE_PLAN_NODE_ID, 

37 LANE_FIELDS, 

38 LANE_NODE_IDS, 

39 RETRIEVAL_JOIN_NODE_ID, 

40 SYNTHESIS_NODE_ID, 

41 EVALUATOR_NODE_ID, 

42 CLARIFY_NODE_ID, 

43 HITL_NODE_ID, 

44 MEMORY_READ_NODE_ID, 

45 RECALL_LEFT_OUT_KEY, 

46 MEMORY_WRITE_NODE_ID, 

47 SYSTEM_NODE_IDS, 

48 RunRejected, 

49 _result_text, 

50) 

51from app.agents.checkpoint import CheckpointSerializer 

52from app.agents.source_ledger import ( 

53 message_citations, 

54 result_citations, 

55 tidy_answer, 

56 tool_failed, 

57 tool_kind, 

58 with_kind, 

59) 

60from app.inference import output_shape 

61from app.inference.context import InferenceContext 

62from app.agents import answer_sources 

63from app.knowledge import turn_report 

64from app.knowledge import categories as knowledge_categories 

65from app.knowledge.mix import MIX_KEY 

66from app.util.knowledge_categories import LABELS as KIND_LABELS 

67from app.util.knowledge_categories import KnowledgeCategory 

68from app.services import model_errors, reply_formats 

69from app.util import attachments as attachment_util 

70from app.util import source_registry 

71from app.util import web_search_report 

72from app.services.model_errors import ModelUnavailableError 

73from app.tools.clarify import SOURCE_TOOL 

74from app.services.structured_output import STRUCTURED_OUTPUT_TAG 

75from app.inference.engine import DbEngineMixin, InferenceEngine, _sse 

76from app.models.spec import ExecuteResponse 

77from app.util.logger import get_logger, set_correlation_id 

78 

79logger = get_logger(__name__) 

80 

81# ── LangGraph runtime singletons ────────────────────────────────────────────── 

82# MemorySaver stores checkpoints in-process for HITL pause/resume. 

83# Swap for AsyncPostgresSaver to persist across restarts. The serializer 

84# allows svc-ai's own state types and cannot fail a write (agents/checkpoint.py). 

85_checkpointer = MemorySaver(serde=CheckpointSerializer()) 

86 

87 

88async def _evict_checkpoint_thread(thread_id: str) -> None: 

89 """Drop a finished thread's checkpoints from the in-process MemorySaver. 

90 

91 Checkpoints exist solely so a HITL interrupt can resume mid-graph. Once 

92 an execution ends — finished, failed, rejected or stopped — the history 

93 has no further use, and MemorySaver retains every superstep snapshot 

94 (full message lists and state) in RAM — without eviction the process 

95 grows unboundedly with each invocation, and a stopped turn's snapshot 

96 seeds the conversation's next turn, which runs on the same thread. 

97 Interrupted executions skip eviction so resume still works. 

98 """ 

99 if not thread_id: 

100 return 

101 try: 

102 await _checkpointer.adelete_thread(thread_id) 

103 except Exception: # noqa: BLE001 — eviction must never break a response 

104 logger.warning("[graph_based] checkpoint eviction failed for %s", thread_id) 

105 

106 

107# PostgresMemoryStore persists cross-conversation agent memories to the 

108# agent_memories table so they survive process restarts. 

109from app.db.postgres.memory_store import PostgresMemoryStore # noqa: E402 

110 

111_store = PostgresMemoryStore() 

112 

113 

114def _memory_store(ctx: InferenceContext) -> PostgresMemoryStore | None: 

115 """The memory store for this run, or None when it keeps no memory — no 

116 memory nodes are built then, so nothing is recalled and nothing is 

117 written: 

118 

119 * the caller asked for a run without memory (``ExecuteRequest.memory``); 

120 * the run names no agent (``external_agent_id``). Memory is an agent's 

121 memory of a person. A run with no agent — a stored skill run, a model 

122 evaluated with tools — used a namespace of the person alone, which 

123 wrote their workflow runs into it and recalled what every one of their 

124 agents remembered, from every workspace, into whatever ran. 

125 """ 

126 if getattr(ctx.request, "memory", True) is False: 

127 return None 

128 if not getattr(ctx.request, "external_agent_id", None): 

129 return None 

130 return _store 

131 

132 

133def _may_ask(ctx: InferenceContext) -> bool: 

134 """Whether anyone can answer this run's questions 

135 (``ExecuteRequest.may_ask``): False for an unattended caller, whose graph 

136 then never offers ``ask_user`` nor runs the scope check.""" 

137 return getattr(ctx.request, "may_ask", True) is not False 

138 

139 

140def _memory_redaction(engine: Any, ctx: InferenceContext) -> Any: 

141 """What the run's rules redact from what memory keeps (its audit rules', 

142 as they redact the answer) and from what it recalls (its policy rules', 

143 as they redact the prompt).""" 

144 from app.memory.service import Redaction 

145 

146 rules = getattr(engine, "rules", None) 

147 if rules is None: 

148 return None 

149 context = engine._rule_context(ctx) 

150 return Redaction( 

151 stored=rules.output_redactor(context), recalled=rules.input_redactor(context) 

152 ) 

153 

154 

155def _withholding(engine: Any) -> bool: 

156 """Whether an Output rule that can withhold the answer governs the run 

157 (``RulesEnforcer.may_withhold``): then the graph keeps nothing of the 

158 answer — memory keeps the request alone, the trace no tool's arguments.""" 

159 rules = getattr(engine, "rules", None) 

160 return bool(getattr(rules, "may_withhold", False)) 

161 

162 

163def _task_shape_result(strategy: Any) -> dict[str, Any]: 

164 """Triage's task shape as the gate's frame carries it — complexity, 

165 skill graph, tools, notes, where it came from (``triage`` or the 

166 ``default`` a failed triage leaves), and the scope check when one was 

167 asked for. Empty on a trivial turn, which has none.""" 

168 if not isinstance(strategy, dict) or not strategy: 

169 return {} 

170 shape: dict[str, Any] = { 

171 "complexity": str(strategy.get("complexity", "moderate")), 

172 "use_skill_graph": bool(strategy.get("use_skill_graph", True)), 

173 "relevant_tools": list(strategy.get("relevant_tools") or []), 

174 "resource_notes": str(strategy.get("resource_notes", "")), 

175 "source": str(strategy.get("source", "")), 

176 } 

177 scope_check = strategy.get("scope_check") 

178 if scope_check and scope_check != "off": 

179 shape["scope_check"] = scope_check 

180 if strategy.get("ambiguity_reason"): 

181 shape["ambiguity_reason"] = str(strategy["ambiguity_reason"]) 

182 return shape 

183 

184 

185#: The graph's own: one list of what a system node is. 

186_SYSTEM_NODE_IDS: frozenset[str] = SYSTEM_NODE_IDS 

187 

188#: Each lane's node, by its id. 

189_LANE_OF_NODE: dict[str, KnowledgeCategory] = { 

190 node_id: category for category, node_id in LANE_NODE_IDS.items() 

191} 

192 

193_NODE_STATUS_LABELS: dict[str, str] = { 

194 GATE_NODE_ID: "Triaging the request…", 

195 PLANNING_NODE_ID: "Planning execution…", 

196 RETRIEVAL_NODE_ID: "Retrieving knowledge…", 

197 INTERNAL_RETRIEVAL_NODE_ID: "Retrieving knowledge…", 

198 EXTERNAL_RETRIEVAL_NODE_ID: "Searching the web…", 

199 TOOL_RETRIEVAL_NODE_ID: "Running tools…", 

200 KNOWLEDGE_PLAN_NODE_ID: "Planning the knowledge search…", 

201 **{ 

202 node_id: f"Searching {KIND_LABELS[category].lower()} knowledge…" 

203 for category, node_id in LANE_NODE_IDS.items() 

204 }, 

205 RETRIEVAL_JOIN_NODE_ID: "Combining what was found…", 

206 SYNTHESIS_NODE_ID: "Synthesising final response…", 

207 EVALUATOR_NODE_ID: "Evaluating response quality…", 

208 HITL_NODE_ID: "Awaiting your review…", 

209 CLARIFY_NODE_ID: "Checking what you need…", 

210 MEMORY_READ_NODE_ID: "Recalling memories…", 

211 MEMORY_WRITE_NODE_ID: "Saving to memory…", 

212} 

213 

214 

215# ── Execution plan (pipeline pre-announcement) ──────────────────────────────── 

216 

217 

218def _ordered_skill_nodes(builder: Any) -> list[str]: 

219 """Breadth-first ordering of a builder's skill nodes from its start node. 

220 

221 Mirrors the order the skill graph will execute in so the UI can lay the 

222 pipeline out left-to-right before anything has run. Nodes unreachable 

223 from the start node (only reachable via conditional routing the builder 

224 does not express as plain edges) are appended in declaration order. 

225 """ 

226 adjacency: dict[str, list[str]] = {} 

227 for from_node, to_node in builder.edges: 

228 if to_node in builder.nodes: 

229 adjacency.setdefault(from_node, []).append(to_node) 

230 

231 ordered: list[str] = [] 

232 seen: set[str] = set() 

233 queue: list[str] = [builder.start_node] if builder.start_node else [] 

234 while queue: 

235 node_id = queue.pop(0) 

236 if node_id in seen or node_id not in builder.nodes: 

237 continue 

238 seen.add(node_id) 

239 ordered.append(node_id) 

240 queue.extend(adjacency.get(node_id, [])) 

241 

242 ordered.extend(node_id for node_id in builder.nodes if node_id not in seen) 

243 return ordered 

244 

245 

246def build_graph_plan( 

247 builder: Any, knowledge_bases: list[dict[str, Any]] | None = None 

248) -> list[dict[str, Any]]: 

249 """Describe, as an ordered list of stages, the pipeline ``builder`` compiles. 

250 

251 Emitted once up-front as a ``graph_plan`` frame so a client can render the 

252 whole pipeline — CI-style — with every stage visible before execution 

253 starts, rather than growing the view one node at a time. 

254 

255 A stage holds one or more ``node_ids``. The retrieval stage is a fork and 

256 a join: ``fork`` (``__knowledge_plan__``) starts its ``branches`` side by 

257 side — a lane per kind of knowledge the agent holds (every kind when the 

258 caller does not say, a resume), the web and the tools — and every branch 

259 meets in ``join`` (``__retrieval_join__``). At most a subset runs: the 

260 route and the turn's mix decide which. ``node_ids`` lists all of them. 

261 ``optional`` marks a stage that routing may legitimately bypass — the 

262 client greys those out rather than flagging them as failures. 

263 

264 Stage order matches ``AgentGraphBuilder.build``'s topology; it is a 

265 prediction, not a guarantee, since routers decide the real path at runtime. 

266 """ 

267 use_memory = getattr(builder, "store", None) is not None 

268 stages: list[dict[str, Any]] = [ 

269 {"id": "gate", "node_ids": [GATE_NODE_ID], "optional": False}, 

270 ] 

271 if getattr(builder, "clarify_scope", False) is True: 

272 stages.append( 

273 {"id": "clarify", "node_ids": [CLARIFY_NODE_ID], "optional": True} 

274 ) 

275 if use_memory: 

276 stages.append( 

277 {"id": "memory_read", "node_ids": [MEMORY_READ_NODE_ID], "optional": True} 

278 ) 

279 stages.append({"id": "planning", "node_ids": [PLANNING_NODE_ID], "optional": True}) 

280 held = ( 

281 {knowledge_categories.category_of(kb) for kb in knowledge_bases} 

282 if knowledge_bases is not None 

283 else set(KnowledgeCategory) 

284 ) 

285 branches = [ 

286 *(node_id for category, node_id in LANE_NODE_IDS.items() if category in held), 

287 EXTERNAL_RETRIEVAL_NODE_ID, 

288 TOOL_RETRIEVAL_NODE_ID, 

289 ] 

290 stages.append( 

291 { 

292 "id": "retrieval", 

293 "node_ids": [KNOWLEDGE_PLAN_NODE_ID, *branches, RETRIEVAL_JOIN_NODE_ID], 

294 "fork": KNOWLEDGE_PLAN_NODE_ID, 

295 "branches": branches, 

296 "join": RETRIEVAL_JOIN_NODE_ID, 

297 "optional": True, 

298 } 

299 ) 

300 stages.extend( 

301 {"id": f"skill:{node_id}", "node_ids": [node_id], "optional": True} 

302 for node_id in _ordered_skill_nodes(builder) 

303 ) 

304 stages.append( 

305 {"id": "synthesis", "node_ids": [SYNTHESIS_NODE_ID], "optional": True} 

306 ) 

307 stages.append( 

308 {"id": "evaluator", "node_ids": [EVALUATOR_NODE_ID], "optional": True} 

309 ) 

310 if getattr(builder, "require_approval", False): 

311 stages.append({"id": "hitl", "node_ids": [HITL_NODE_ID], "optional": True}) 

312 if use_memory: 

313 stages.append( 

314 {"id": "memory_write", "node_ids": [MEMORY_WRITE_NODE_ID], "optional": True} 

315 ) 

316 

317 for stage in stages: 

318 stage["is_system_stage"] = all( 

319 node_id in _SYSTEM_NODE_IDS for node_id in stage["node_ids"] 

320 ) 

321 return stages 

322 

323 

324# ── Utility functions (package-internal) ────────────────────────────────────── 

325 

326 

327def collect_usage(messages: list) -> dict[str, Any]: 

328 """ 

329 A rough token count of a finished run's messages: output summed, input 

330 as the growth from one message to the next. 

331 

332 It under-counts input — every call is sent, and billed, its whole input — 

333 and the batch route replaces it with the meter's figures, which count 

334 every call (``routers/agent.py`` → ``metering.merge_into_usage``). It 

335 survives only for a run the meter saw no call of. The stream counts each 

336 call's full input (``_stream_graph``). 

337 """ 

338 prev_input = 0 

339 delta_input = 0 

340 output_tokens = 0 

341 for msg in messages: 

342 meta = getattr(msg, "usage_metadata", None) 

343 if meta: 

344 curr_input = meta.get("input_tokens", 0) 

345 delta_input += max(0, curr_input - prev_input) 

346 prev_input = curr_input 

347 output_tokens += meta.get("output_tokens", 0) 

348 return { 

349 "prompt_tokens": delta_input, 

350 "completion_tokens": output_tokens, 

351 "total_tokens": delta_input + output_tokens, 

352 } 

353 

354 

355#: Where the batch response's context carries the run's web searches. 

356WEB_SEARCHES_KEY = "web_searches" 

357 

358 

359def tool_report(tool: str, output: Any) -> dict[str, Any] | None: 

360 """The report a tool kept beside its text (its message's artifact): 

361 a web search's (``app/util/web_search_report.py``), or None.""" 

362 if tool != "web_search": 

363 return None 

364 report = web_search_report.SearchReport.read(getattr(output, "artifact", None)) 

365 return report.wire() if report is not None else None 

366 

367 

368def collect_web_searches(messages: list) -> list[dict[str, Any]]: 

369 """Every web search a completed run made, as its report, in order (the 

370 batch path; the stream sends each on its ``tool_call`` frame).""" 

371 return [ 

372 report 

373 for message in messages or [] 

374 if getattr(message, "tool_call_id", None) is not None 

375 and (report := tool_report(str(getattr(message, "name", "") or ""), message)) 

376 ] 

377 

378 

379def collect_citations(messages: list) -> list[dict[str, Any]]: 

380 """Every source a completed run's tool results cite, numbered from 1 in 

381 order (the batch path). Each tool's result is read by its parser 

382 (``source_ledger.CITATION_PARSERS``) and carries its ``kind``.""" 

383 return [ 

384 {"index": i, **c} for i, c in enumerate(message_citations(messages), start=1) 

385 ] 

386 

387 

388async def _citations_before_pause(compiled: Any, config: dict | None) -> list[dict]: 

389 """The sources a paused run had gathered — the documents attached to its 

390 conversation, its completed nodes' pipeline passages and tool results, as 

391 the checkpoint holds them — numbered from 1. A node the pause cut short 

392 runs again on resume and streams its own. Empty when the checkpoint 

393 cannot be read.""" 

394 try: 

395 snapshot = await compiled.aget_state(config or {}) 

396 except Exception as exc: # noqa: BLE001 — a resume still answers without them 

397 logger.warning("resume: the paused run's sources could not be read: %s", exc) 

398 return [] 

399 values = getattr(snapshot, "values", None) or {} 

400 if not isinstance(values, dict): 

401 return [] 

402 return merge_citations( 

403 [ 

404 *attachment_util.citations( 

405 attachment_util.of_state(values.get("attachments")) 

406 ), 

407 *(values.get("retrieval_citations") or []), 

408 ], 

409 collect_citations(values.get("messages") or []), 

410 ) 

411 

412 

413def _reads_listed_attachment( 

414 citation: dict[str, Any], listed: list[dict[str, Any]] 

415) -> bool: 

416 """True when ``citation`` is a tool's read of a document the person 

417 attached that ``listed`` already holds, by its id: the run lists the 

418 document once, not once per part an agent read.""" 

419 sid = citation.get("citation_id") 

420 return bool(sid) and any( 

421 c.get("citation_id") == sid and c.get("tool") == attachment_util.TOOL 

422 for c in listed 

423 ) 

424 

425 

426def merge_citations( 

427 retrieval_citations: list[dict[str, Any]], 

428 tool_citations: list[dict[str, Any]], 

429) -> list[dict[str, Any]]: 

430 """Combine pipeline citations (primary evidence) with tool-derived ones. 

431 

432 Retrieval-pipeline citations come first because their ``[S#]`` ids are the 

433 ones downstream agents were instructed to cite; tool citations follow, 

434 less a read of an attached document already listed. ``index`` is 

435 reassigned sequentially so the client sees one contiguous list, and every 

436 citation says what ``kind`` of source it is. 

437 """ 

438 merged: list[dict[str, Any]] = [] 

439 tool_citations = [ 

440 c 

441 for c in tool_citations 

442 if not _reads_listed_attachment(c, retrieval_citations) 

443 ] 

444 for c in [*retrieval_citations, *tool_citations]: 

445 entry = {k: v for k, v in c.items() if k != "index"} 

446 merged.append(with_kind({"index": len(merged) + 1, **entry})) 

447 return merged 

448 

449 

450def extract_citations(tool_name: str, tool_input: dict, tool_output: str) -> list[dict]: 

451 """The sources one tool result cites (the streaming path), by the tool's 

452 parser (``source_ledger.result_citations``). A knowledge search's also name 

453 the ``collection`` the call asked for — the tool's name when it named 

454 none.""" 

455 citations = result_citations(tool_name, tool_output) 

456 if citations and tool_kind(tool_name) == "knowledge": 

457 collection = ( 

458 tool_input.get("collection", tool_name) 

459 if isinstance(tool_input, dict) 

460 else tool_name 

461 ) 

462 citations = [{**c, "collection": collection} for c in citations] 

463 return citations 

464 

465 

466#: Sent when the text a node streamed since it started, or since its last 

467#: reset, is no longer the answer so far: a turn that called tools on a model 

468#: whose tool-turn text is what it was about to do, gpt-oss text that turned 

469#: out to be outside its envelope, a reasoning block that closed. svc-core 

470#: drops that text from what it keeps and fe-core from its preview. What 

471#: streams after the last reset is what the answer is (``reply_formats``). 

472TOKEN_RESET = "token_reset" 

473 

474 

475class NodeStreams: 

476 """What each node may stream, as its model calls arrive. 

477 

478 One ``reply_formats.StreamFilter`` per node run — not per call, because a 

479 reply cut off at the token cap is finished by a continuation, a new call 

480 whose text carries on the same answer — chosen from the model each call 

481 names in its event metadata (``ls_provider`` / ``ls_model_name``), so a 

482 node whose calls go to another model reads each by its own format. 

483 """ 

484 

485 def __init__(self) -> None: 

486 self._filters: dict[tuple[str, str], reply_formats.StreamFilter] = {} 

487 

488 def _filter(self, run: str, metadata: dict) -> reply_formats.StreamFilter: 

489 reader = reply_formats.of_traced( 

490 metadata.get("ls_provider"), metadata.get("ls_model_name") 

491 ) 

492 key = (run, reader.key) 

493 if key not in self._filters: 

494 self._filters[key] = reader.stream() 

495 return self._filters[key] 

496 

497 def feed(self, run: str, metadata: dict, content: Any) -> list: 

498 return self._filter(run, metadata).feed(content) 

499 

500 def end(self, run: str, metadata: dict, message: Any) -> list: 

501 from app.agents.base import _is_truncated 

502 

503 return self._filter(run, metadata).end( 

504 message, continues=message is not None and _is_truncated(message) 

505 ) 

506 

507 def close(self, run: str) -> None: 

508 for key in [k for k in self._filters if k[0] == run]: 

509 del self._filters[key] 

510 

511 

512def _retrieval_preview(context: object, error: str, label: str) -> str: 

513 """A retrieval node's output preview: what it handed on, else its error, 

514 else that it found nothing. An empty search read "retrieval error: ", 

515 though nothing had failed.""" 

516 if context: 

517 return str(context)[:300].replace("\n", " ") 

518 if error: 

519 return f"{label} error: {error[:80]}" 

520 return "nothing found" 

521 

522 

523def _unstreamed(event: dict) -> bool: 

524 """A call whose text is the pipeline's: a structured call's JSON, or a 

525 memory summary.""" 

526 tags = event.get("tags") or [] 

527 return STRUCTURED_OUTPUT_TAG in tags or reply_formats.UNSTREAMED_TAG in tags 

528 

529 

530def _node_run(parent_ids: list[str], node_by_run_id: dict[str, str]) -> str | None: 

531 """The run id of the graph node a call is made in.""" 

532 return next((pid for pid in parent_ids if pid in node_by_run_id), None) 

533 

534 

535def failed_tool_frame( 

536 error: object, *, tool: str, node_id: str, params: object 

537) -> dict[str, Any] | None: 

538 """The ``tool_call`` frame for a tool that raised, or None for a pause. 

539 

540 A tool that raises sends no ``on_tool_end``: ``ToolNode`` hands the model 

541 an error result, and nothing else saw the call — ``render_plot`` failed on 

542 every call and the trace, the decision record and the scenario export 

543 showed no call at all. ``ask_user``'s ``ClarificationRequested`` (a 

544 ``GraphBubbleUp``) is a pause, not a failure. The preview names the 

545 error's class only, never its text.""" 

546 if isinstance(error, GraphBubbleUp): 

547 return None 

548 kind = type(error).__name__ if isinstance(error, BaseException) else "error" 

549 return { 

550 "type": "tool_call", 

551 "node_id": node_id, 

552 "tool": tool, 

553 "params": params if isinstance(params, dict) else {}, 

554 "output_preview": f"failed ({kind})", 

555 "status": "error", 

556 } 

557 

558 

559def stream_frames(ops: list, node: str | None) -> list[dict]: 

560 """Stream ops as SSE frames, each naming its node.""" 

561 where = {"worker_agent_slug": node} if node else {} 

562 frames: list[dict] = [] 

563 for op in ops: 

564 if isinstance(op, reply_formats.Reset): 

565 frames.append({"type": TOKEN_RESET, **where}) 

566 elif op.text: 

567 frames.append({"type": "token", "token": op.text, **where}) 

568 return frames 

569 

570 

571def _msg_content(msg: Any) -> str: 

572 """A message's reply text (``reply_formats.text_of``), whether it is a 

573 message or a dict.""" 

574 raw = ( 

575 msg.content 

576 if hasattr(msg, "content") 

577 else msg.get("content", "") 

578 if isinstance(msg, dict) 

579 else "" 

580 ) 

581 if isinstance(raw, (str, list)): 

582 return reply_formats.text_of(raw) 

583 return str(raw) 

584 

585 

586def history_turns_omitted(out_data: Any) -> int | None: 

587 """The earlier turns a node's model could not be sent, from the state 

588 update it returned (``graph._history_figure``) — None when it was sent 

589 them all.""" 

590 context = out_data.get("context") if isinstance(out_data, dict) else None 

591 omitted = ( 

592 context.get("history_turns_omitted") if isinstance(context, dict) else None 

593 ) 

594 return omitted if isinstance(omitted, int) and omitted > 0 else None 

595 

596 

597def _extract_node_error(out_data: dict[str, Any], node_id: str) -> str: 

598 errors: list[str] = out_data.get("errors", []) or [] 

599 for err in reversed(errors): 

600 if node_id in str(err): 

601 return str(err)[:400] 

602 if errors: 

603 return str(errors[-1])[:400] 

604 msgs: list[Any] = out_data.get("messages", []) or [] 

605 for msg in reversed(msgs): 

606 content = _msg_content(msg) 

607 if any( 

608 kw in content.lower() for kw in ("error", "skipped", "failed", "exception") 

609 ): 

610 return content[:400] 

611 return "" 

612 

613 

614def _pass_of(raw: Any) -> int: 

615 """The graph pass a node starts on, from the state it was given: 0, 

616 then one more per revision after the quality check.""" 

617 value = ( 

618 raw.get("eval_retry_count") 

619 if isinstance(raw, dict) 

620 else getattr(raw, "eval_retry_count", None) 

621 ) 

622 return value if isinstance(value, int) else 0 

623 

624 

625def _knowledge_plan_result(out_data: dict[str, Any]) -> dict[str, Any]: 

626 """``__knowledge_plan__``'s frame: the mode, the turn's mix, each lane 

627 it starts (its kind, role, knowledge bases and the queries it runs), 

628 whether the query planner failed — and on a corrective pass the gaps it 

629 looks for. Never a passage.""" 

630 planned = out_data.get("knowledge_plan") or {} 

631 mix = planned.get("mix") or {} 

632 plan = planned.get("plan") or {} 

633 queries = list(plan.get("queries") or []) 

634 # Each lane's own, when the lanes were planned apart. 

635 own = plan.get("lane_queries") or {} 

636 by_kind = { 

637 lane.get("category"): lane 

638 for lane in mix.get("lanes") or [] 

639 if isinstance(lane, dict) 

640 } 

641 lanes = [] 

642 for kind in planned.get("lanes") or []: 

643 lane = by_kind.get(kind, {}) 

644 lanes.append( 

645 { 

646 "category": kind, 

647 "role": lane.get("role", ""), 

648 "kb_ids": list(lane.get("kb_ids") or []), 

649 "queries": list(own.get(kind) or []) 

650 or queries[: lane.get("max_queries") or len(queries)], 

651 } 

652 ) 

653 result: dict[str, Any] = { 

654 "mode": str(planned.get("mode") or ""), 

655 "mix": mix, 

656 "lanes": lanes, 

657 "planner_failure": str(plan.get("planner_failure") or ""), 

658 } 

659 if planned.get("gaps"): 

660 result["gaps"] = list(planned["gaps"]) 

661 if planned.get("error"): 

662 result["error"] = str(planned["error"]) 

663 return result 

664 

665 

666def _lane_result( 

667 category: KnowledgeCategory, out_data: dict[str, Any] 

668) -> dict[str, Any]: 

669 """A lane's frame: its kind, role, knowledge bases and queries, and what 

670 its search did — found, shown to its judge, ruled out by it, left out of 

671 the window, handed on to the join — with its judge's failure, the search 

672 legs it ran without and its stages' timings. Counts only, never a 

673 passage.""" 

674 lane = out_data.get(LANE_FIELDS[category]) or {} 

675 result: dict[str, Any] = { 

676 "category": category.value, 

677 "role": str(lane.get("role") or ""), 

678 "kb_ids": list(lane.get("kb_ids") or []), 

679 "queries": list(lane.get("queries") or []), 

680 "found": sum((lane.get("found") or {}).values()), 

681 "judged": int(lane.get("judged") or 0), 

682 "ruled_out": sum((lane.get("ruled_out") or {}).values()), 

683 "out_of_window": sum((lane.get("windowed") or {}).values()), 

684 "handed_on": len(lane.get("passages") or []) + len(lane.get("facts") or []), 

685 "judge_failure": str(lane.get("judge_failure") or ""), 

686 "degraded": list(lane.get("degraded") or []), 

687 "timings_ms": dict(lane.get("timings") or {}), 

688 } 

689 if lane.get("failure"): 

690 result["error"] = str(lane["failure"]) 

691 return result 

692 

693 

694def _extract_system_node_input(node_id: str, raw: Any) -> dict[str, Any]: 

695 def _g(field: str, default: Any = None) -> Any: 

696 if raw is None: 

697 return default 

698 val = ( 

699 raw.get(field, default) 

700 if isinstance(raw, dict) 

701 else getattr(raw, field, default) 

702 ) 

703 return val if val is not None else default 

704 

705 if node_id == GATE_NODE_ID: 

706 result: dict[str, Any] = {"input": str(_g("input", ""))[:500]} 

707 kb_meta = _g("kb_metadata", "") or "" 

708 if kb_meta: 

709 result["kb_metadata_preview"] = kb_meta[:600] 

710 return result 

711 

712 if node_id == PLANNING_NODE_ID: 

713 kbs = _g("knowledge_bases", []) 

714 memories = _g("memories", []) 

715 return { 

716 "input": str(_g("input", ""))[:500], 

717 "knowledge_base_count": len(kbs) if isinstance(kbs, list) else 0, 

718 "memory_count": len(memories) if isinstance(memories, list) else 0, 

719 } 

720 

721 if node_id in ( 

722 RETRIEVAL_NODE_ID, 

723 INTERNAL_RETRIEVAL_NODE_ID, 

724 KNOWLEDGE_PLAN_NODE_ID, 

725 ): 

726 plan = _g("execution_plan", {}) 

727 focus = plan.get("retrieval_focus", "") if isinstance(plan, dict) else "" 

728 return { 

729 "input": str(_g("input", ""))[:500], 

730 "retrieval_focus": str(focus)[:300], 

731 } 

732 

733 if node_id in _LANE_OF_NODE: 

734 return {"input": str(_g("input", ""))[:500]} 

735 

736 if node_id == RETRIEVAL_JOIN_NODE_ID: 

737 return { 

738 "input": str(_g("input", ""))[:500], 

739 "has_web_context": bool(_g("web_context", "")), 

740 "has_tool_context": bool(_g("tool_context", "")), 

741 } 

742 

743 if node_id == EXTERNAL_RETRIEVAL_NODE_ID: 

744 plan = _g("execution_plan", {}) 

745 ext_focus = ( 

746 plan.get("external_retrieval_focus", "") if isinstance(plan, dict) else "" 

747 ) 

748 return { 

749 "input": str(_g("input", ""))[:500], 

750 "external_retrieval_focus": str(ext_focus)[:300], 

751 "has_internal_context": bool(_g("retrieval_context", "")), 

752 } 

753 

754 if node_id == TOOL_RETRIEVAL_NODE_ID: 

755 plan = _g("execution_plan", {}) 

756 focus = plan.get("retrieval_focus", "") if isinstance(plan, dict) else "" 

757 return { 

758 "input": str(_g("input", ""))[:500], 

759 "retrieval_focus": str(focus)[:300], 

760 } 

761 

762 if node_id == SYNTHESIS_NODE_ID: 

763 results = _g("results", {}) 

764 return { 

765 "input": str(_g("input", ""))[:200], 

766 "skill_nodes": list(results.keys()) if isinstance(results, dict) else [], 

767 "has_retrieval_context": bool(_g("retrieval_context", "")), 

768 } 

769 

770 if node_id == EVALUATOR_NODE_ID: 

771 plan = _g("execution_plan", {}) or {} 

772 results = _g("results", {}) or {} 

773 skill_nodes = [k for k in results if not k.startswith("__")] 

774 return { 

775 "input": str(_g("input", ""))[:500], 

776 "route": str(_g("route", "")), 

777 "skill_nodes_evaluated": skill_nodes, 

778 "has_synthesis": SYNTHESIS_NODE_ID in results, 

779 } 

780 

781 if node_id == MEMORY_READ_NODE_ID: 

782 ctx = _g("context", {}) 

783 return {"user_id": str(ctx.get("user_id", "") if isinstance(ctx, dict) else "")} 

784 

785 if node_id == MEMORY_WRITE_NODE_ID: 

786 results = _g("results", {}) 

787 synthesis = ( 

788 results.get(SYNTHESIS_NODE_ID, "") if isinstance(results, dict) else "" 

789 ) 

790 return {"content_preview": str(synthesis)[:200]} 

791 

792 return {} 

793 

794 

795def hitl_pause_frame( 

796 payload: dict[str, Any], interrupt_type: str, node_id: str, thread_id: str 

797) -> dict[str, Any]: 

798 """The ``hitl_pause`` trace frame for an interrupt. 

799 

800 Carries what the person was shown — the questions, or the work an 

801 approval gate is holding — so the persisted trace alone records the 

802 pause. svc-core appends the matching ``hitl_resume`` frame once the 

803 person answers, with the answers and who gave them. 

804 """ 

805 from datetime import UTC, datetime 

806 

807 frame: dict[str, Any] = { 

808 "type": "hitl_pause", 

809 "node_id": node_id, 

810 "interrupt_type": interrupt_type, 

811 "thread_id": thread_id, 

812 "paused_at": datetime.now(UTC).isoformat(), 

813 } 

814 if interrupt_type == "clarification_request": 

815 for key in ("source", "title", "intro", "reason", "questions"): 

816 if payload.get(key) is not None: 

817 frame[key] = payload[key] 

818 else: 

819 frame["task"] = str(payload.get("task") or payload.get("message") or "") 

820 if payload.get("output") is not None: 

821 frame["output"] = str(payload["output"])[:2000] 

822 return frame 

823 

824 

825# ── Base class ───────────────────────────────────────────────────────────────── 

826 

827 

828class GraphBasedEngine(DbEngineMixin, InferenceEngine): 

829 """ 

830 Shared base for AgentEngine, SkillEngine and GraphEngine. 

831 

832 Subclasses must implement ``_build_builder(ctx)`` which returns a 

833 configured ``AgentGraphBuilder`` plus the metadata needed to run it. 

834 Subclasses that need different ``GraphState`` construction (extra state 

835 fields, a different context shape, a different default end node, or 

836 engine-level usage recording) override the small hooks below instead of 

837 ``_do_infer``/``_do_infer_stream`` themselves. 

838 """ 

839 

840 # Fallback terminal node id when the builder reports none (e.g. AgentEngine's 

841 # single-node graph, whose node is always named "agent"). 

842 _default_end_node: str = "" 

843 

844 # A turn's documents ride in graph state, apart from the person's words. 

845 takes_attachments = True 

846 

847 # ── Abstract interface for subclasses ───────────────────────────────────── 

848 

849 @abstractmethod 

850 def _build_builder( 

851 self, ctx: InferenceContext 

852 ) -> tuple[Any, list[dict], dict[str, Any]]: 

853 """ 

854 Build and return: 

855 (builder, knowledge_bases, extra_context) 

856 

857 builder — AgentGraphBuilder ready to compile. 

858 knowledge_bases — list of KB dicts to inject into GraphState. 

859 extra_context — additional fields merged into GraphState.context. 

860 """ 

861 

862 # ── Overridable state-construction hooks ──────────────────────────────── 

863 

864 @staticmethod 

865 def _initial_state_vars(builder: Any) -> dict[str, Any]: 

866 """State-variable defaults attached by SkillEngine (schema v2 graphs). 

867 

868 Type-guarded because test doubles (MagicMock builders) auto-create 

869 arbitrary attributes. 

870 """ 

871 seeded = getattr(builder, "_initial_state_vars", None) 

872 return seeded if isinstance(seeded, dict) else {} 

873 

874 def _extra_state_kwargs(self, builder: Any) -> dict[str, Any]: 

875 """Extra ``GraphState`` constructor kwargs. AgentEngine overrides this 

876 to thread conversation history in as LangChain ``messages``.""" 

877 return {} 

878 

879 def _base_state_context(self, ctx: InferenceContext) -> dict[str, Any]: 

880 """The engine-specific portion of ``GraphState.context``, before 

881 ``extra_context`` from ``_build_builder`` is merged on top.""" 

882 return { 

883 "user_id": ctx.request.user_id, 

884 # The agent the run answers as, when it is one — an agent whose 

885 # skill graph is on runs here (SkillEngine), and without its id 

886 # its memory had no agent to belong to. 

887 "agent_id": str(getattr(ctx.request, "external_agent_id", None) or ""), 

888 "conversation_id": ctx.request.conversation_id, 

889 "conversation_history": ctx.request.messages or [], 

890 } 

891 

892 def _record_usage(self, usage: dict[str, Any]) -> None: 

893 """Hook for engines that also track usage on ``self.monitor``.""" 

894 

895 def _initial_state( 

896 self, 

897 ctx: InferenceContext, 

898 builder: Any, 

899 knowledge_bases: list[dict], 

900 extra_context: dict[str, Any], 

901 ) -> Any: 

902 """The state a run starts from — the same for batch and stream.""" 

903 from app.agents.graph import GraphState 

904 

905 return GraphState( 

906 input=ctx.filtered_input, 

907 agent_name=extra_context.get("agent_name", ""), 

908 agent_system_prompt=extra_context.get("agent_system_prompt", ""), 

909 # Skill graphs (schema v2) declare state defaults; seeded here so 

910 # templates and operations can read keys before any node writes. 

911 state_vars=self._initial_state_vars(builder), 

912 context={**self._base_state_context(ctx), **extra_context}, 

913 knowledge_bases=knowledge_bases, 

914 attachments=ctx.attachments, 

915 retrieval_config=extra_context.get("retrieval_config") or {}, 

916 **self._extra_state_kwargs(builder), 

917 ) 

918 

919 @staticmethod 

920 def _skill_outputs( 

921 builder: Any, state_vars: dict[str, Any], results: dict[str, Any] 

922 ) -> dict[str, Any]: 

923 """Project the skill's declared ``interface.outputs`` from final state.""" 

924 interface = getattr(builder, "skill_interface", None) 

925 return project_skill_outputs( 

926 interface if isinstance(interface, dict) else None, state_vars, results 

927 ) 

928 

929 # ── Batch execution ─────────────────────────────────────────────────────── 

930 

931 @staticmethod 

932 async def _resume_command(compiled: Any, lc_config: dict, resume: Any) -> Any: 

933 """The ``Command`` that continues a paused run from its checkpoint. 

934 

935 Checkpoints live in this process (``MemorySaver``). One that is gone — 

936 svc-ai restarted, or another replica paused the run — cannot be 

937 resumed, and invoking a Command against nothing would quietly start a 

938 fresh, empty run. So it is refused, with a reason the caller can show. 

939 """ 

940 

941 snapshot = await compiled.aget_state(lc_config) 

942 if not snapshot or not getattr(snapshot, "next", None): 

943 raise ValueError( 

944 "This run can no longer be resumed: its paused state is gone " 

945 "(the AI service restarted since it paused)." 

946 ) 

947 return Command( 

948 resume={ 

949 "approved": resume.approved, 

950 "feedback": resume.feedback, 

951 "answers": resume.answers or {}, 

952 } 

953 ) 

954 

955 @staticmethod 

956 def _rejected(ctx: InferenceContext, exc: "RunRejected") -> ExecuteResponse: 

957 """The response for a run a person stopped at an approval gate.""" 

958 logger.info("[graph_based] rejected at node=%s", exc.node_id) 

959 note = f"Stopped before “{exc.node_id}”: the reviewer did not approve it." 

960 if exc.feedback: 

961 note += f"\n\nReviewer's note: {exc.feedback}" 

962 return ExecuteResponse( 

963 output=note, 

964 session_id=ctx.request.session_id, 

965 context={"rejected": exc.payload()}, 

966 ) 

967 

968 @staticmethod 

969 def _interrupted( 

970 ctx: InferenceContext, thread_id: str, value: Any 

971 ) -> ExecuteResponse: 

972 """The response for a run that paused, with what it paused on.""" 

973 payload = dict(value) if isinstance(value, dict) else {} 

974 payload = { 

975 **payload, 

976 "interrupt_type": payload.get("type") or "approval_request", 

977 "thread_id": thread_id, 

978 } 

979 logger.info( 

980 "[graph_based] interrupt thread_id=%s kind=%s", 

981 thread_id, 

982 payload["interrupt_type"], 

983 ) 

984 return ExecuteResponse( 

985 output="", 

986 session_id=ctx.request.session_id, 

987 interrupt=payload, 

988 ) 

989 

990 async def _do_infer(self, ctx: InferenceContext) -> ExecuteResponse: 

991 import litellm 

992 

993 builder, knowledge_bases, extra_context = self._build_builder(ctx) 

994 builder.store = _memory_store(ctx) 

995 builder.memory_redaction = _memory_redaction(self, ctx) 

996 builder.withholding = _withholding(self) 

997 builder.may_ask = _may_ask(ctx) 

998 compiled = builder.build(checkpointer=_checkpointer) 

999 

1000 resume = getattr(ctx.request, "resume", None) 

1001 thread_id = ( 

1002 (resume.thread_id if resume else None) 

1003 or ctx.request.session_id 

1004 or str(uuid.uuid4()) 

1005 ) 

1006 lc_config = builder.run_config(thread_id) 

1007 registry = source_registry.of_config(lc_config) 

1008 

1009 initial_state = self._initial_state( 

1010 ctx, builder, knowledge_bases, extra_context 

1011 ) 

1012 

1013 graph_input: Any = initial_state 

1014 if resume is not None: 

1015 graph_input = await self._resume_command(compiled, lc_config, resume) 

1016 # A resumed run's sources keep the ids its first segment handed 

1017 # out — the attached documents' among them. The batch path never 

1018 # seeded them, so a resumed answer's [S1] could name another 

1019 # source than the one it was shown as. 

1020 before = await _citations_before_pause(compiled, lc_config) 

1021 if registry is not None and before: 

1022 registry.seed(before) 

1023 else: 

1024 # The documents' ids first: every later source numbers on. 

1025 attachment_util.seed(registry, initial_state.attachments) 

1026 

1027 # Only a pause keeps its checkpoint. A run that failed, or whose 

1028 # request was dropped (cancelled), is evicted like a finished one: 

1029 # the next turn of the conversation reuses the thread, and would 

1030 # start from what this one left (see ``_stream_graph``). 

1031 paused = False 

1032 try: 

1033 try: 

1034 result = await compiled.ainvoke(graph_input, config=lc_config) 

1035 except GraphInterrupt as exc: 

1036 paused = True 

1037 value = exc.args[0][0].value if exc.args and exc.args[0] else {} 

1038 return self._interrupted(ctx, thread_id, value) 

1039 except RunRejected as exc: 

1040 return self._rejected(ctx, exc) 

1041 

1042 # LangGraph 1.x reports a pause by *returning* it under 

1043 # ``__interrupt__`` rather than raising — the except above only 

1044 # ever saw older versions. Without this, a batch caller of a run 

1045 # that paused on ``ask_user`` or an approval gate got "No output" 

1046 # and the checkpoint it would resume from was evicted. 

1047 pending = result.get("__interrupt__") if isinstance(result, dict) else None 

1048 if pending: 

1049 paused = True 

1050 first = pending[0] 

1051 return self._interrupted(ctx, thread_id, getattr(first, "value", first)) 

1052 finally: 

1053 if not paused: 

1054 await _evict_checkpoint_thread(thread_id) 

1055 

1056 results = result.get("results", {}) 

1057 eval_raw = results.get(EVALUATOR_NODE_ID) 

1058 if eval_raw is not None and hasattr(eval_raw, "final_output"): 

1059 raw_output: Any = eval_raw.final_output 

1060 elif isinstance(eval_raw, dict) and eval_raw.get("final_output"): 

1061 raw_output = eval_raw["final_output"] 

1062 else: 

1063 raw_output = results.get(SYNTHESIS_NODE_ID, "") 

1064 # The evaluator normalised its draft's citation markers; a run that 

1065 # skipped it (or a synthesis fallback) is normalised here. 

1066 written = tidy_answer(_result_text(raw_output)) if raw_output else "No output" 

1067 # Asked for as JSON, the answer is held to that shape before the 

1068 # run's audit rules read it (``output_shape``); what it cites is read 

1069 # from the answer as it was written. 

1070 output_str, format_problem = ( 

1071 await output_shape.shape_answer(output_shape.of_builder(builder), written) 

1072 if raw_output 

1073 else (written, None) 

1074 ) 

1075 raw_messages = result.get("messages", []) 

1076 usage = collect_usage(raw_messages) 

1077 

1078 try: 

1079 model_cfg = getattr(ctx.request.spec, "model", None) 

1080 if ( 

1081 model_cfg 

1082 and hasattr(model_cfg, "provider") 

1083 and hasattr(model_cfg, "model") 

1084 ): 

1085 model_str = f"{model_cfg.provider}/{model_cfg.model}" 

1086 prompt_cost, completion_cost = litellm.cost_per_token( 

1087 model=model_str, 

1088 prompt_tokens=usage.get("prompt_tokens", 0), 

1089 completion_tokens=usage.get("completion_tokens", 0), 

1090 ) 

1091 usage["estimated_cost_usd"] = prompt_cost + completion_cost 

1092 except Exception: 

1093 pass 

1094 

1095 self._record_usage(usage) 

1096 

1097 # Surface the user-visible skill state so callers can inspect how 

1098 # state evolved across graph nodes (schema v2 skill graphs). 

1099 response_context = dict(result.get("context", {})) 

1100 state_vars = result.get("state_vars") or {} 

1101 if state_vars: 

1102 response_context["skill_state"] = state_vars 

1103 skill_outputs = self._skill_outputs(builder, state_vars, results) 

1104 if skill_outputs: 

1105 response_context["skill_outputs"] = skill_outputs 

1106 if format_problem: 

1107 response_context[output_shape.ERROR_KEY] = format_problem 

1108 web_searches = collect_web_searches(raw_messages) 

1109 if web_searches: 

1110 response_context[WEB_SEARCHES_KEY] = web_searches 

1111 # What the turn asked of its knowledge and what each source gave: 

1112 # svc-core keeps it as the retrieval record. 

1113 knowledge = turn_report.assemble(result) 

1114 if knowledge is not None: 

1115 response_context[turn_report.KEY] = knowledge 

1116 else: 

1117 response_context.pop(turn_report.KEY, None) 

1118 

1119 citations = merge_citations( 

1120 [ 

1121 *attachment_util.citations( 

1122 attachment_util.of_state(result.get("attachments")) 

1123 ), 

1124 *(result.get("retrieval_citations") or []), 

1125 ], 

1126 collect_citations(raw_messages), 

1127 ) 

1128 return ExecuteResponse( 

1129 output=output_str, 

1130 usage=usage, 

1131 session_id=ctx.request.session_id, 

1132 messages=[ 

1133 m.model_dump() if hasattr(m, "model_dump") else m for m in raw_messages 

1134 ], 

1135 context=response_context, 

1136 citations=citations, 

1137 # What the answer itself cites, as the stream's done frame says: 

1138 # a batch caller shows these as its sources, not everything the 

1139 # run retrieved. 

1140 cited_citations=answer_sources.delivered_citations( 

1141 eval_raw, citations, source_registry.of_config(lc_config), written 

1142 ), 

1143 ) 

1144 

1145 # ── Streaming execution ─────────────────────────────────────────────────── 

1146 

1147 async def _do_infer_stream(self, ctx: InferenceContext) -> AsyncIterator[str]: 

1148 """ 

1149 Yield SSE data lines from a LangGraph execution using astream_events. 

1150 

1151 Emits: 

1152 graph_plan — ordered stage plan for the whole pipeline (first frame) 

1153 node_start — node begins (with input summary for system nodes) 

1154 status — human-readable step label 

1155 token — LLM content chunk 

1156 tool_call — tool execution result 

1157 citations — source citations from tool outputs 

1158 system_node_result — structured output from system pipeline nodes 

1159 node_end — node completes (with tokens + duration) 

1160 hitl_interrupt — graph paused awaiting human approval 

1161 done — final output + aggregate usage 

1162 error — unhandled exception 

1163 """ 

1164 

1165 # Building the graph builds its models, and a model this backend 

1166 # cannot serve is refused there (``inference_routes.resolve``), before 

1167 # the run's own error handling below. Said once, as a frame: an 

1168 # exception here used to end the stream with no frame at all, so the 

1169 # person saw an empty answer and only the trace said why. 

1170 try: 

1171 builder, knowledge_bases, extra_context = self._build_builder(ctx) 

1172 builder.store = _memory_store(ctx) 

1173 builder.memory_redaction = _memory_redaction(self, ctx) 

1174 builder.withholding = _withholding(self) 

1175 builder.may_ask = _may_ask(ctx) 

1176 compiled = builder.build(checkpointer=_checkpointer) 

1177 except ModelUnavailableError as exc: 

1178 logger.error("[stream] model unavailable: %s", model_errors.describe(exc)) 

1179 yield _sse({"type": "error", **exc.payload()}) 

1180 return 

1181 except Exception: 

1182 logger.exception("[stream] Error building the graph") 

1183 yield _sse({"type": "error", "message": "An internal error has occurred."}) 

1184 return 

1185 node_ids: set[str] = set(builder.nodes.keys()) 

1186 

1187 # Determine the terminal node from builder metadata 

1188 end_node = ( 

1189 next(iter(builder.end_nodes), self._default_end_node) 

1190 if builder.end_nodes 

1191 else self._default_end_node 

1192 ) 

1193 

1194 thread_id = ctx.request.session_id or str(uuid.uuid4()) 

1195 if thread_id: 

1196 set_correlation_id(thread_id) 

1197 

1198 stream_config = builder.run_config(thread_id) 

1199 initial_state = self._initial_state( 

1200 ctx, builder, knowledge_bases, extra_context 

1201 ) 

1202 

1203 async for frame in _stream_graph( 

1204 compiled=compiled, 

1205 initial_state=initial_state, 

1206 node_ids=node_ids, 

1207 end_node=end_node, 

1208 thread_id=thread_id, 

1209 config=stream_config, 

1210 skill_interface=getattr(builder, "skill_interface", None), 

1211 graph_plan=build_graph_plan(builder, knowledge_bases), 

1212 answer_shape=output_shape.of_builder(builder), 

1213 ): 

1214 yield frame 

1215 

1216 

1217def project_skill_outputs( 

1218 interface: dict[str, Any] | None, 

1219 state_vars: dict[str, Any] | None, 

1220 results: dict[str, Any] | None, 

1221) -> dict[str, Any]: 

1222 """Project a skill's declared ``interface.outputs`` from its final state. 

1223 

1224 Each output is ``{"name": ..., "from": "<state_key or node.path>"}`` 

1225 (``from`` defaults to the name); unresolvable paths yield ``None`` so the 

1226 caller always sees the complete contract. 

1227 """ 

1228 from app.agents.conditions import resolve_path 

1229 

1230 outputs = (interface or {}).get("outputs") or [] 

1231 if not outputs: 

1232 return {} 

1233 variables: dict[str, Any] = {} 

1234 for node_id, result in (results or {}).items(): 

1235 variables[node_id] = ( 

1236 result.model_dump() if hasattr(result, "model_dump") else result 

1237 ) 

1238 variables.update(state_vars or {}) 

1239 projected: dict[str, Any] = {} 

1240 for entry in outputs: 

1241 if not isinstance(entry, dict) or not entry.get("name"): 

1242 continue 

1243 source = str(entry.get("from") or entry["name"]) 

1244 found, value = resolve_path(source, variables) 

1245 projected[entry["name"]] = value if found else None 

1246 return projected 

1247 

1248 

1249# ── Core streaming implementation ───────────────────────────────────────────── 

1250 

1251 

1252async def _stream_graph( 

1253 compiled: Any, 

1254 initial_state: Any, 

1255 node_ids: set[str], 

1256 end_node: str, 

1257 thread_id: str = "", 

1258 config: dict | None = None, 

1259 skill_interface: dict[str, Any] | None = None, 

1260 graph_plan: list[dict[str, Any]] | None = None, 

1261 answer_shape: output_shape.AnswerShape | None = None, 

1262) -> AsyncIterator[str]: 

1263 """ 

1264 Core LangGraph streaming function. Yields SSE data lines. 

1265 

1266 Accepts a pre-compiled graph and pre-built initial state so both 

1267 GraphBasedEngine._do_infer_stream and the HITL resume endpoint can reuse it. 

1268 

1269 ``graph_plan`` (see :func:`build_graph_plan`) is announced as the first 

1270 frame when supplied, so the client can render every pipeline stage before 

1271 the first node starts. 

1272 

1273 ``answer_shape`` (``output_shape.of_builder``) holds the done frame's 

1274 answer to the JSON shape the request asked for, before the run's audit 

1275 rules read the frame. 

1276 """ 

1277 all_node_ids = node_ids | _SYSTEM_NODE_IDS 

1278 # Every node frame says when, from the stream's start (``t_ms``), so a 

1279 # client can draw branches that ran side by side as they ran. 

1280 stream_start = _time.monotonic() 

1281 

1282 if graph_plan: 

1283 yield _sse({"type": "graph_plan", "stages": graph_plan}) 

1284 

1285 final_output = "" 

1286 answered = False 

1287 final_state_vars: dict = {} 

1288 final_results: dict = {} 

1289 final_verdict: Any = None 

1290 answered_by: dict | None = None 

1291 knowledge_report: dict | None = None 

1292 synthesis_output_cache = "" 

1293 # A resumed run's sources from before its pause are in its checkpoint, 

1294 # not in this stream, and the answer may cite them: without them, a 

1295 # paused answer's [S1] credited nothing, and svc-core stored that. 

1296 # A fresh run's first sources are the documents attached to its 

1297 # conversation, under the ids the boundary gave them. 

1298 citations_all: list[dict] = ( 

1299 await _citations_before_pause(compiled, config) 

1300 if isinstance(initial_state, Command) 

1301 else merge_citations( 

1302 attachment_util.citations( 

1303 attachment_util.of_state(getattr(initial_state, "attachments", None)) 

1304 ), 

1305 [], 

1306 ) 

1307 ) 

1308 citation_index = len(citations_all) 

1309 # A resumed run's sources keep the ids its first segment handed out, and 

1310 # new ones carry on from them (``util/source_registry``). 

1311 _registry = source_registry.of_config(config) 

1312 if _registry is not None and citations_all: 

1313 _registry.seed(citations_all) 

1314 if citations_all and not isinstance(initial_state, Command): 

1315 yield _sse({"type": "citations", "citations": citations_all}) 

1316 input_tokens = 0 

1317 output_tokens = 0 

1318 cost_total: float = 0.0 

1319 

1320 node_by_run_id: dict[str, str] = {} 

1321 node_start_time: dict[str, float] = {} 

1322 node_tokens: dict[str, dict] = {} 

1323 node_input_data: dict[str, dict] = {} 

1324 node_models: dict[str, str] = {} # run_id → last ls_model_name seen 

1325 node_providers: dict[str, str] = {} # run_id → last ls_provider seen 

1326 # What each node may stream (``NodeStreams``). 

1327 node_streams = NodeStreams() 

1328 # LangGraph 1.x does not raise GraphInterrupt out of astream_events: a 

1329 # pause arrives as an ``__interrupt__`` chunk on the graph's own stream 

1330 # and the run then ends normally. Without catching it here a paused turn 

1331 # was reported as finished — an empty ``done`` — and its checkpoint 

1332 # evicted, so nothing could ever answer it. 

1333 pending_interrupts: tuple[Any, ...] = () 

1334 # Only a pause keeps its checkpoint (see the ``finally`` below). 

1335 paused = False 

1336 events = compiled.astream_events(initial_state, version="v2", config=config or {}) 

1337 

1338 try: 

1339 async for event in events: 

1340 kind: str = event["event"] 

1341 name: str = event.get("name", "") 

1342 run_id: str = event.get("run_id", "") 

1343 parent_ids: list[str] = event.get("parent_ids", []) 

1344 

1345 # ── Node entering ───────────────────────────────────────────── 

1346 if kind == "on_chain_start" and name in all_node_ids: 

1347 node_by_run_id[run_id] = name 

1348 started = _time.monotonic() 

1349 node_start_time[run_id] = started 

1350 node_tokens[run_id] = {"input": 0, "output": 0} 

1351 is_system = name in _SYSTEM_NODE_IDS 

1352 if is_system: 

1353 node_input_data[run_id] = _extract_system_node_input( 

1354 name, event["data"].get("input") 

1355 ) 

1356 yield _sse( 

1357 { 

1358 "type": "node_start", 

1359 "node_id": name, 

1360 "is_system_node": is_system, 

1361 "t_ms": int((started - stream_start) * 1000), 

1362 # The graph pass it runs on: 0, then one more per 

1363 # revision after the quality check. 

1364 "pass": _pass_of(event["data"].get("input")), 

1365 **({"input": node_input_data[run_id]} if is_system else {}), 

1366 } 

1367 ) 

1368 status_label = _NODE_STATUS_LABELS.get(name, f"Running {name}…") 

1369 yield _sse({"type": "status", "message": status_label}) 

1370 

1371 # ── Tool starting ───────────────────────────────────────────── 

1372 elif kind == "on_tool_start": 

1373 yield _sse({"type": "status", "message": f"Using tool: {name}…"}) 

1374 

1375 # ── LLM token chunk ─────────────────────────────────────────── 

1376 # A structured call's reply is JSON for the pipeline, never words 

1377 # for the person: natively decoded, it streams as text. 

1378 # A memory summary's text is memory's (``UNSTREAMED_TAG``). Every 

1379 # other call streams through its node's filter 

1380 # (``NodeStreams``): only what is answer so far, never its 

1381 # reasoning, preamble or text outside an envelope. 

1382 elif kind == "on_chat_model_stream" and not _unstreamed(event): 

1383 chunk = event["data"].get("chunk") 

1384 if chunk: 

1385 node_run = _node_run(parent_ids, node_by_run_id) or run_id 

1386 for frame in stream_frames( 

1387 node_streams.feed( 

1388 node_run, event.get("metadata") or {}, chunk.content 

1389 ), 

1390 node_by_run_id.get(node_run), 

1391 ): 

1392 yield _sse(frame) 

1393 

1394 # ── LLM call finished — accumulate tokens globally + per node ─ 

1395 elif kind == "on_chat_model_end": 

1396 output_msg = event["data"].get("output") 

1397 if not _unstreamed(event): 

1398 node_run = _node_run(parent_ids, node_by_run_id) or run_id 

1399 for frame in stream_frames( 

1400 node_streams.end( 

1401 node_run, event.get("metadata") or {}, output_msg 

1402 ), 

1403 node_by_run_id.get(node_run), 

1404 ): 

1405 yield _sse(frame) 

1406 meta = getattr(output_msg, "usage_metadata", None) 

1407 if meta: 

1408 # Every call is sent — and billed — its whole input, so a 

1409 # node's input is the sum of its calls' inputs. This was 

1410 # a delta against whatever call ran just before, which 

1411 # read 0 for any node whose prompt was no longer than 

1412 # its predecessor's (the quality check's "0 in"). 

1413 in_t = meta.get("input_tokens", 0) 

1414 out_t = meta.get("output_tokens", 0) 

1415 input_tokens += in_t 

1416 output_tokens += out_t 

1417 for pid in parent_ids: 

1418 if pid in node_by_run_id: 

1419 node_tokens[pid]["input"] += in_t 

1420 node_tokens[pid]["output"] += out_t 

1421 break 

1422 try: 

1423 import litellm as _litellm 

1424 

1425 _event_meta = event.get("metadata", {}) 

1426 _ls_model = _event_meta.get("ls_model_name", "") 

1427 _ls_provider = _event_meta.get("ls_provider", "") 

1428 if _ls_model: 

1429 for pid in parent_ids: 

1430 if pid in node_by_run_id: 

1431 node_models[pid] = _ls_model 

1432 if _ls_provider: 

1433 node_providers[pid] = _ls_provider 

1434 break 

1435 _model_str = ( 

1436 f"{_ls_provider}/{_ls_model}" 

1437 if _ls_provider 

1438 else _ls_model 

1439 ) 

1440 _p, _c = _litellm.cost_per_token( 

1441 model=_model_str, 

1442 prompt_tokens=in_t, 

1443 completion_tokens=out_t, 

1444 ) 

1445 cost_total += _p + _c 

1446 except Exception: 

1447 pass 

1448 

1449 # ── Tool completed ──────────────────────────────────────────── 

1450 elif kind == "on_tool_end": 

1451 raw_output = event["data"].get("output", "") 

1452 if hasattr(raw_output, "content"): 

1453 output_str = raw_output.content 

1454 elif isinstance(raw_output, str): 

1455 output_str = raw_output 

1456 else: 

1457 output_str = str(raw_output) 

1458 

1459 tool_input = event["data"].get("input", {}) 

1460 new_citations = [ 

1461 c 

1462 for c in extract_citations(name, tool_input, output_str) 

1463 if not _reads_listed_attachment(c, citations_all) 

1464 ] 

1465 if new_citations: 

1466 indexed = [] 

1467 for c in new_citations: 

1468 citation_index += 1 

1469 entry = with_kind({"index": citation_index, **c}) 

1470 indexed.append(entry) 

1471 citations_all.append(entry) 

1472 yield _sse({"type": "citations", "citations": indexed}) 

1473 

1474 node_run = _node_run(parent_ids, node_by_run_id) 

1475 node_id_for_tool = node_by_run_id[node_run] if node_run else "" 

1476 is_error = tool_failed(output_str) 

1477 # A web search's report: what the engines said and what each 

1478 # check removed — for svc-core and the trace, never a model. 

1479 report = tool_report(name, raw_output) 

1480 yield _sse( 

1481 { 

1482 "type": "tool_call", 

1483 "node_id": node_id_for_tool, 

1484 "tool": name, 

1485 "params": tool_input if isinstance(tool_input, dict) else {}, 

1486 "output_preview": output_str[:300].replace("\n", " "), 

1487 "status": "error" if is_error else "success", 

1488 **({"report": report} if report is not None else {}), 

1489 } 

1490 ) 

1491 

1492 # ── Tool raised (``failed_tool_frame``) ─────────────────────── 

1493 elif kind == "on_tool_error": 

1494 node_run = _node_run(parent_ids, node_by_run_id) 

1495 frame = failed_tool_frame( 

1496 event["data"].get("error"), 

1497 tool=name, 

1498 node_id=node_by_run_id[node_run] if node_run else "", 

1499 params=event["data"].get("input", {}), 

1500 ) 

1501 if frame is not None: 

1502 yield _sse(frame) 

1503 

1504 # ── Node finished ───────────────────────────────────────────── 

1505 elif kind == "on_chain_end" and run_id in node_by_run_id: 

1506 node_id = node_by_run_id.pop(run_id) 

1507 start_t = node_start_time.pop(run_id, None) 

1508 duration_ms = ( 

1509 int((_time.monotonic() - start_t) * 1000) 

1510 if start_t is not None 

1511 else 0 

1512 ) 

1513 tokens = node_tokens.pop(run_id, {"input": 0, "output": 0}) 

1514 node_streams.close(run_id) 

1515 node_input = node_input_data.pop(run_id, {}) 

1516 node_model = node_models.pop(run_id, "") 

1517 node_provider = node_providers.pop(run_id, "") 

1518 

1519 raw_out = event["data"].get("output") 

1520 if raw_out is None: 

1521 out_data: dict[str, Any] = {} 

1522 elif isinstance(raw_out, dict): 

1523 out_data = raw_out 

1524 elif hasattr(raw_out, "model_dump"): 

1525 out_data = raw_out.model_dump() 

1526 else: 

1527 out_data = {} 

1528 

1529 is_system = node_id in _SYSTEM_NODE_IDS 

1530 output_preview = "" 

1531 

1532 if node_id == GATE_NODE_ID: 

1533 route = out_data.get("route", "") 

1534 gate_result = out_data.get("results", {}).get(SYNTHESIS_NODE_ID, "") 

1535 shape = _task_shape_result(out_data.get("resource_strategy")) 

1536 output_preview = ( 

1537 str(gate_result)[:300].replace("\n", " ") 

1538 if gate_result 

1539 else f"route → {route}" 

1540 + ( 

1541 f" complexity={shape['complexity']} skill_graph=" 

1542 f"{'yes' if shape['use_skill_graph'] else 'no'}" 

1543 if shape 

1544 else "" 

1545 ) 

1546 ) 

1547 gate_result_dict: dict[str, Any] = { 

1548 "route": route, 

1549 "retrieval_type": out_data.get("retrieval_type", ""), 

1550 "trivial_output": str(gate_result) if gate_result else "", 

1551 # The task's shape, decided in the same triage call 

1552 # (it was __recon__'s frame). 

1553 **shape, 

1554 } 

1555 kb_meta_str = out_data.get("kb_metadata", "") 

1556 if kb_meta_str: 

1557 gate_result_dict["kb_metadata"] = kb_meta_str 

1558 # Whether the inventory was read in full: shown wherever 

1559 # there is one, and wherever one could not be built. 

1560 complete = out_data.get("kb_inventory_complete") 

1561 if kb_meta_str or complete is False: 

1562 gate_result_dict["kb_inventory_complete"] = bool(complete) 

1563 # What triage chose before the gate's rules changed it, 

1564 # and each change (absent on a trivial turn). 

1565 triage = out_data.get("triage_route") 

1566 if triage: 

1567 gate_result_dict["triage"] = triage 

1568 # Which kinds of knowledge the request searches, in what 

1569 # role, and what it leaves out (``knowledge.mix``). 

1570 knowledge = (out_data.get("context") or {}).get(MIX_KEY) 

1571 if knowledge: 

1572 gate_result_dict["knowledge_mix"] = knowledge 

1573 # How the agent is shown each attached document: whole, 

1574 # listed for the attachment tools, or unavailable. 

1575 planned = out_data.get("attachment_plan") 

1576 if planned: 

1577 gate_result_dict["attachments"] = planned 

1578 yield _sse( 

1579 { 

1580 "type": "system_node_result", 

1581 "node_id": node_id, 

1582 "input": node_input, 

1583 "result": gate_result_dict, 

1584 } 

1585 ) 

1586 

1587 elif node_id == PLANNING_NODE_ID: 

1588 plan = out_data.get("execution_plan", {}) 

1589 plan_error = ( 

1590 _extract_node_error(out_data, node_id) if not plan else "" 

1591 ) 

1592 if plan: 

1593 output_preview = ( 

1594 f"overall_goal: {plan.get('overall_goal', '')}"[ 

1595 :300 

1596 ].replace("\n", " ") 

1597 ) 

1598 else: 

1599 note = next( 

1600 ( 

1601 _msg_content(m) 

1602 for m in out_data.get("messages") or [] 

1603 if _msg_content(m) 

1604 ), 

1605 "", 

1606 ) 

1607 output_preview = ( 

1608 f"planning error: {plan_error[:100]}" 

1609 if plan_error 

1610 else note or "planning returned empty plan" 

1611 ) 

1612 result_dict: dict[str, Any] = { 

1613 "task_summary": plan.get("task_summary", ""), 

1614 "overall_goal": plan.get("overall_goal", ""), 

1615 "retrieval_focus": plan.get("retrieval_focus", ""), 

1616 "node_plans": plan.get("node_plans", []), 

1617 # The authoritative dispatch list (the planner may plan 

1618 # for a node without selecting it). Lets a client mark 

1619 # the skill stages that will not run as skipped the 

1620 # moment planning lands, instead of waiting them out. 

1621 "active_node_ids": list(out_data.get("active_node_ids") or []), 

1622 } 

1623 if plan_error: 

1624 result_dict["plan_error"] = plan_error 

1625 yield _sse( 

1626 { 

1627 "type": "system_node_result", 

1628 "node_id": node_id, 

1629 "input": node_input, 

1630 "result": result_dict, 

1631 } 

1632 ) 

1633 

1634 elif node_id == KNOWLEDGE_PLAN_NODE_ID: 

1635 plan_result = _knowledge_plan_result(out_data) 

1636 output_preview = ( 

1637 f"{plan_result['mode']}: " 

1638 + ( 

1639 ", ".join( 

1640 f"{lane['category']} ({lane['role']})" 

1641 for lane in plan_result["lanes"] 

1642 ) 

1643 or "no lanes" 

1644 ) 

1645 )[:300] 

1646 yield _sse( 

1647 { 

1648 "type": "system_node_result", 

1649 "node_id": node_id, 

1650 "input": node_input, 

1651 "result": plan_result, 

1652 } 

1653 ) 

1654 

1655 elif node_id in _LANE_OF_NODE: 

1656 lane_result = _lane_result(_LANE_OF_NODE[node_id], out_data) 

1657 output_preview = ( 

1658 f"{lane_result['role'] or 'lane'}: found " 

1659 f"{lane_result['found']}, handed on {lane_result['handed_on']}" 

1660 ) 

1661 yield _sse( 

1662 { 

1663 "type": "system_node_result", 

1664 "node_id": node_id, 

1665 "input": node_input, 

1666 "result": lane_result, 

1667 } 

1668 ) 

1669 

1670 elif node_id in ( 

1671 RETRIEVAL_NODE_ID, 

1672 INTERNAL_RETRIEVAL_NODE_ID, 

1673 RETRIEVAL_JOIN_NODE_ID, 

1674 ): 

1675 pipeline_cites = out_data.get("retrieval_citations") or [] 

1676 if pipeline_cites: 

1677 indexed_cites = [] 

1678 for c in pipeline_cites: 

1679 citation_index += 1 

1680 # A passage is ``knowledge``, a graph fact 

1681 # ``graph`` — by its tool, as every citation. 

1682 entry = with_kind( 

1683 { 

1684 "index": citation_index, 

1685 **{k: v for k, v in c.items() if k != "index"}, 

1686 } 

1687 ) 

1688 indexed_cites.append(entry) 

1689 citations_all.append(entry) 

1690 yield _sse({"type": "citations", "citations": indexed_cites}) 

1691 retrieval_ctx = out_data.get("retrieval_context", "") 

1692 retrieval_error = ( 

1693 _extract_node_error(out_data, node_id) 

1694 if not retrieval_ctx 

1695 else "" 

1696 ) 

1697 output_preview = _retrieval_preview( 

1698 retrieval_ctx, retrieval_error, "retrieval" 

1699 ) 

1700 retrieval_result: dict[str, Any] = { 

1701 "retrieval_context": retrieval_ctx 

1702 } 

1703 if retrieval_error: 

1704 retrieval_result["error"] = retrieval_error 

1705 # The frameworks it found, packed apart from the evidence 

1706 # (reasoning knowledge): the stage shows both. 

1707 if out_data.get("frameworks_context"): 

1708 retrieval_result["frameworks_context"] = out_data[ 

1709 "frameworks_context" 

1710 ] 

1711 # What the pipeline ran without (a failed query planner 

1712 # or relevance judge, a search leg that could not run), 

1713 # when it has anything to say — and how each lane fared 

1714 # in packing. 

1715 report = dict(out_data.get("retrieval_report") or {}) 

1716 lanes_packed = report.pop("lanes", None) 

1717 if any(report.values()): 

1718 retrieval_result["report"] = report 

1719 if lanes_packed: 

1720 retrieval_result["lanes"] = lanes_packed 

1721 yield _sse( 

1722 { 

1723 "type": "system_node_result", 

1724 "node_id": node_id, 

1725 "input": node_input, 

1726 "result": retrieval_result, 

1727 } 

1728 ) 

1729 

1730 elif node_id == EXTERNAL_RETRIEVAL_NODE_ID: 

1731 ext_ctx = out_data.get("web_context", "") 

1732 ext_error = ( 

1733 _extract_node_error(out_data, node_id) if not ext_ctx else "" 

1734 ) 

1735 output_preview = _retrieval_preview( 

1736 ext_ctx, ext_error, "external retrieval" 

1737 ) 

1738 ext_result: dict[str, Any] = {"retrieval_context": ext_ctx} 

1739 if ext_error: 

1740 ext_result["error"] = ext_error 

1741 yield _sse( 

1742 { 

1743 "type": "system_node_result", 

1744 "node_id": node_id, 

1745 "input": node_input, 

1746 "result": ext_result, 

1747 } 

1748 ) 

1749 

1750 elif node_id == TOOL_RETRIEVAL_NODE_ID: 

1751 tool_ctx = out_data.get("tool_context", "") 

1752 tool_error = ( 

1753 _extract_node_error(out_data, node_id) if not tool_ctx else "" 

1754 ) 

1755 output_preview = _retrieval_preview( 

1756 tool_ctx, tool_error, "tool retrieval" 

1757 ) 

1758 tool_result: dict[str, Any] = {"retrieval_context": tool_ctx} 

1759 if tool_error: 

1760 tool_result["error"] = tool_error 

1761 yield _sse( 

1762 { 

1763 "type": "system_node_result", 

1764 "node_id": node_id, 

1765 "input": node_input, 

1766 "result": tool_result, 

1767 } 

1768 ) 

1769 

1770 elif node_id == MEMORY_READ_NODE_ID: 

1771 memories: list = out_data.get("memories", []) 

1772 output_preview = f"Recalled {len(memories)} memor{'y' if len(memories) == 1 else 'ies'}" 

1773 # The kinds recall left out, and why: a request for 

1774 # current information recalls no earlier exchange. 

1775 left_out = (out_data.get("context") or {}).get(RECALL_LEFT_OUT_KEY) 

1776 yield _sse( 

1777 { 

1778 "type": "system_node_result", 

1779 "node_id": node_id, 

1780 "input": node_input, 

1781 "result": { 

1782 "memories": memories, 

1783 **({"left_out": left_out} if left_out else {}), 

1784 }, 

1785 } 

1786 ) 

1787 

1788 elif node_id == MEMORY_WRITE_NODE_ID: 

1789 content: str = out_data.get("memory_write_result", "") 

1790 output_preview = "Memory stored" if content else "Nothing stored" 

1791 yield _sse( 

1792 { 

1793 "type": "system_node_result", 

1794 "node_id": node_id, 

1795 "input": node_input, 

1796 "result": {"stored": bool(content), "content": content}, 

1797 } 

1798 ) 

1799 

1800 elif node_id == EVALUATOR_NODE_ID: 

1801 eval_raw = out_data.get("results", {}).get(EVALUATOR_NODE_ID, None) 

1802 if hasattr(eval_raw, "model_dump"): 

1803 eval_dict: dict[str, Any] = eval_raw.model_dump() 

1804 elif isinstance(eval_raw, dict): 

1805 eval_dict = eval_raw 

1806 else: 

1807 eval_dict = {} 

1808 final_out = eval_dict.get("final_output", "") 

1809 passed = eval_dict.get("passed", True) 

1810 # None when no check ran — never a default that reads 

1811 # as a mark. ``outcome`` says what became of the answer. 

1812 score = eval_dict.get("score") 

1813 outcome = eval_dict.get("outcome", "unavailable") 

1814 gaps: list = eval_dict.get("gaps", []) 

1815 output_preview = ( 

1816 f"{outcome}" 

1817 + (f" score={score}" if score is not None else "") 

1818 + (f" gaps: {'; '.join(gaps[:2])}" if gaps else "") 

1819 + ( 

1820 f" {final_out[:120].replace(chr(10), ' ')}" 

1821 if final_out 

1822 else "" 

1823 ) 

1824 )[:300] 

1825 yield _sse( 

1826 { 

1827 "type": "system_node_result", 

1828 "node_id": node_id, 

1829 "input": node_input, 

1830 "result": { 

1831 "passed": passed, 

1832 "score": score, 

1833 "outcome": outcome, 

1834 "gaps": gaps, 

1835 # Each gap's kind, in order, for review. 

1836 "gap_kinds": eval_dict.get("gap_kinds") or [], 

1837 # What the check named and did not fail on. 

1838 "set_aside": eval_dict.get("set_aside") or [], 

1839 "critique": eval_dict.get("critique", ""), 

1840 "final_output": final_out, 

1841 }, 

1842 } 

1843 ) 

1844 

1845 elif node_id == CLARIFY_NODE_ID: 

1846 asked = (out_data.get("clarifications") or [{}])[-1] 

1847 skipped = bool(asked.get("skipped")) 

1848 # The scope check before work, or a step's question mid-task. 

1849 what = ( 

1850 "clarification" 

1851 if asked.get("source") == SOURCE_TOOL 

1852 else "scope clarification" 

1853 ) 

1854 output_preview = ( 

1855 f"{what} skipped" 

1856 if skipped 

1857 else f"{what}: {len(asked.get('answers') or {})} answer(s)" 

1858 ) 

1859 yield _sse( 

1860 { 

1861 "type": "system_node_result", 

1862 "node_id": node_id, 

1863 "input": node_input, 

1864 "result": { 

1865 "reason": asked.get("reason") or "", 

1866 "questions": asked.get("questions") or [], 

1867 "answers": asked.get("answers") or {}, 

1868 "skipped": skipped, 

1869 }, 

1870 } 

1871 ) 

1872 

1873 elif node_id == SYNTHESIS_NODE_ID: 

1874 raw = out_data.get("results", {}).get(SYNTHESIS_NODE_ID, "") 

1875 synthesis_error = ( 

1876 _extract_node_error(out_data, node_id) if not raw else "" 

1877 ) 

1878 output_preview = ( 

1879 str(raw)[:300].replace("\n", " ") 

1880 if raw 

1881 else f"synthesis error: {synthesis_error[:80]}" 

1882 ) 

1883 if raw: 

1884 synthesis_output_cache = str(raw) 

1885 synth_result: dict[str, Any] = {"output": str(raw) if raw else ""} 

1886 if synthesis_error: 

1887 synth_result["error"] = synthesis_error 

1888 yield _sse( 

1889 { 

1890 "type": "system_node_result", 

1891 "node_id": node_id, 

1892 "input": node_input, 

1893 "result": synth_result, 

1894 } 

1895 ) 

1896 

1897 else: 

1898 node_result = out_data.get("results", {}).get(node_id, "") 

1899 if hasattr(node_result, "model_dump_json"): 

1900 output_preview = node_result.model_dump_json()[:300] 

1901 elif isinstance(node_result, (dict, list)): 

1902 # Structured worker / compose transform — JSON preview 

1903 output_preview = json.dumps( 

1904 node_result, ensure_ascii=False, default=str 

1905 )[:300] 

1906 elif node_result: 

1907 output_preview = str(node_result)[:300].replace("\n", " ") 

1908 else: 

1909 err = _extract_node_error(out_data, node_id) 

1910 output_preview = f"error: {err[:280]}" if err else "" 

1911 

1912 node_end_event: dict[str, Any] = { 

1913 "type": "node_end", 

1914 "node_id": node_id, 

1915 "is_system_node": is_system, 

1916 "output_preview": output_preview, 

1917 "tokens": tokens, 

1918 "duration_ms": duration_ms, 

1919 "t_ms": int((_time.monotonic() - stream_start) * 1000), 

1920 } 

1921 if node_model: 

1922 node_end_event["model_name"] = node_model 

1923 if node_provider: 

1924 node_end_event["provider"] = node_provider 

1925 # Skill state written by this node (output_key binding) — lets 

1926 # clients show state evolving across the graph in real time. 

1927 state_update = out_data.get("state_vars") or {} 

1928 if state_update: 

1929 node_end_event["state_update"] = state_update 

1930 # Earlier turns the node's model could not be sent 

1931 # (``token_budget``) — the decision record's step says so. 

1932 omitted = history_turns_omitted(out_data) 

1933 if omitted: 

1934 node_end_event["history_turns_omitted"] = omitted 

1935 yield _sse(node_end_event) 

1936 

1937 # ── Graph paused on interrupt() ──────────────────────────────── 

1938 elif kind == "on_chain_stream" and name == "LangGraph": 

1939 chunk = event["data"].get("chunk") 

1940 if isinstance(chunk, dict) and chunk.get("__interrupt__"): 

1941 pending_interrupts = tuple(chunk["__interrupt__"]) 

1942 

1943 # ── Top-level graph finished ─────────────────────────────────── 

1944 elif kind == "on_chain_end" and name == "LangGraph": 

1945 output = event["data"].get("output") or {} 

1946 results = output.get("results", {}) 

1947 final_results = results 

1948 final_state_vars = output.get("state_vars") or {} 

1949 answered_by = (output.get("context") or {}).get(ANSWERED_BY_KEY) 

1950 knowledge_report = turn_report.assemble(output) 

1951 # Prefer evaluator's curated final_output over raw synthesis. 

1952 eval_raw = results.get(EVALUATOR_NODE_ID) 

1953 final_verdict = eval_raw 

1954 if eval_raw is not None and hasattr(eval_raw, "final_output"): 

1955 raw = eval_raw.final_output 

1956 elif isinstance(eval_raw, dict) and eval_raw.get("final_output"): 

1957 raw = eval_raw["final_output"] 

1958 else: 

1959 raw = ( 

1960 results.get(SYNTHESIS_NODE_ID) 

1961 or results.get(end_node, "") 

1962 or synthesis_output_cache 

1963 ) 

1964 # Idempotent over the evaluator's own normalisation: what the 

1965 # done frame carries, and what its sources are read from, is 

1966 # the answer with its markers written ``[n]``. 

1967 final_output = tidy_answer(_result_text(raw)) if raw else "No output" 

1968 answered = bool(raw) 

1969 

1970 if pending_interrupts: 

1971 # Same path an older LangGraph's raised interrupt takes. 

1972 raise GraphInterrupt(pending_interrupts) 

1973 

1974 usage: dict = { 

1975 "prompt_tokens": input_tokens, 

1976 "completion_tokens": output_tokens, 

1977 "total_tokens": input_tokens + output_tokens, 

1978 } 

1979 if cost_total: 

1980 usage["estimated_cost_usd"] = cost_total 

1981 # Asked for as JSON, the answer is held to that shape here 

1982 # (``output_shape``); its sources are read from it as it was written. 

1983 delivered, format_problem = ( 

1984 await output_shape.shape_answer(answer_shape, final_output) 

1985 if answered 

1986 else (final_output, None) 

1987 ) 

1988 done_frame: dict[str, Any] = { 

1989 "type": "done", 

1990 "output": delivered, 

1991 "usage": usage, 

1992 # Everything the run retrieved — a skill run's record keeps it. 

1993 "citations": citations_all, 

1994 # What the answer itself cites: the sources its Sources block 

1995 # lists, each with its marker (``answer_sources``). The 

1996 # ``citations`` frames streamed every passage as it was 

1997 # retrieved, used or not. 

1998 "cited_citations": answer_sources.delivered_citations( 

1999 final_verdict, 

2000 citations_all, 

2001 source_registry.of_config(config), 

2002 final_output, 

2003 ), 

2004 } 

2005 if final_state_vars: 

2006 done_frame["skill_state"] = final_state_vars 

2007 if answered_by: 

2008 # A model other than the agent's own wrote the answer (an Economy 

2009 # profile's lighter model, for a request triage called simple). 

2010 done_frame[ANSWERED_BY_KEY] = answered_by 

2011 if knowledge_report is not None: 

2012 # What the turn asked of its knowledge and what each source 

2013 # gave: svc-core keeps it as the retrieval record. 

2014 done_frame[turn_report.KEY] = knowledge_report 

2015 skill_outputs = project_skill_outputs( 

2016 skill_interface, final_state_vars, final_results 

2017 ) 

2018 if skill_outputs: 

2019 done_frame["skill_outputs"] = skill_outputs 

2020 if format_problem: 

2021 done_frame[output_shape.ERROR_KEY] = format_problem 

2022 yield _sse(done_frame) 

2023 

2024 except GraphInterrupt as exc: 

2025 paused = True 

2026 payload = exc.args[0][0].value if exc.args and exc.args[0] else {} 

2027 interrupt_type = payload.get("type") or "approval_request" 

2028 logger.info( 

2029 "[stream] interrupt thread_id=%s kind=%s payload_keys=%s", 

2030 thread_id, 

2031 interrupt_type, 

2032 list(payload.keys()), 

2033 ) 

2034 # A trace frame first, so every trace view — live and persisted — 

2035 # shows *where* the run stopped for a person and what it asked, 

2036 # rather than a node that started and never finished. The node is 

2037 # the innermost one still open: the one whose code called 

2038 # interrupt() (a skill node's ask_user, an approval gate, __clarify__). 

2039 paused_node = payload.get("node_id") or next( 

2040 reversed(list(node_by_run_id.values())), "" 

2041 ) 

2042 yield _sse(hitl_pause_frame(payload, interrupt_type, paused_node, thread_id)) 

2043 # Spread the payload FIRST: its own "type" (approval_request / 

2044 # clarification_request) must not overwrite the SSE frame type, or the 

2045 # frame stops being recognisable as an interrupt at all. The payload's 

2046 # kind is preserved separately as "interrupt_type". 

2047 yield _sse( 

2048 { 

2049 **payload, 

2050 "type": "hitl_interrupt", 

2051 "interrupt_type": interrupt_type, 

2052 "thread_id": thread_id, 

2053 "node_id": paused_node, 

2054 } 

2055 ) 

2056 

2057 except RunRejected as exc: 

2058 # A reviewer said no at a gate: the run ends there, as a result. 

2059 note = f"Stopped before “{exc.node_id}”: the reviewer did not approve it." 

2060 if exc.feedback: 

2061 note += f"\n\nReviewer's note: {exc.feedback}" 

2062 yield _sse({"type": "done", "output": note, "rejected": exc.payload()}) 

2063 

2064 except ModelUnavailableError as exc: 

2065 # Credentials, model access or quota: no node could work around it, 

2066 # so the run stopped at the first call and says why — once. 

2067 logger.error("[stream] model unavailable: %s", model_errors.describe(exc)) 

2068 yield _sse({"type": "error", **exc.payload()}) 

2069 

2070 except Exception: 

2071 logger.exception("[stream] Error streaming LangGraph execution") 

2072 yield _sse({"type": "error", "message": "An internal error has occurred."}) 

2073 

2074 finally: 

2075 # Every run but a paused one ends here, its checkpoint with it: one 

2076 # that finished, failed or was rejected, and one that was stopped — 

2077 # cancelled mid-run (svc-core's Stop drops the stream) or closed at a 

2078 # frame. Only finished and failed runs used to be evicted, and the 

2079 # next turn of the conversation (whose id is the thread's) started 

2080 # from a stopped turn's checkpoint with every merging channel kept: 

2081 # its retrieved knowledge, its judge failure, its web results, the 

2082 # passages it had cited. 

2083 # 

2084 # The run is stopped first: closed at a frame, the event stream's 

2085 # graph task is still running, and what it writes on its way out 

2086 # must not land after the eviction. The eviction never suspends 

2087 # (``MemorySaver.adelete_thread``), so it completes inside a 

2088 # cancelled task or a generator being closed, even when closing the 

2089 # stream is itself cut short. 

2090 try: 

2091 aclose = getattr(events, "aclose", None) 

2092 if aclose is not None: 

2093 await aclose() 

2094 finally: 

2095 if not paused: 

2096 await _evict_checkpoint_thread(thread_id)