Coverage for app / router / app / agents / transformers.py: 89%

324 statements  

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

1import logging 

2from collections.abc import Callable 

3from datetime import datetime, timedelta 

4from time import perf_counter 

5from typing import Any 

6from uuid import UUID, uuid4 

7 

8from sqlalchemy.orm import Session 

9 

10from app.db.postgres.crud_schemas import Schema 

11from app.db.postgres.enums import HistoryEnum, MessageEnum, UsageEnum 

12from app.db.postgres.models import ( 

13 Agent, 

14 AgentRepository, 

15 AgentSkillset, 

16 ChatMessage, 

17 ChatMessageSegment, 

18 Conversation, 

19 Knowledge, 

20 KnowledgeRepository, 

21 RepositoryKnowledge, 

22 Skill, 

23 SkillsetSkill, 

24) 

25from app.services import history as history_service 

26from app.services import retrieval as retrieval_service 

27from app.services import governance_activity as activity_service 

28from app.services import review as review_service 

29from app.services import rule_engine 

30from app.services import usage as usage_service 

31from app.services import agent_spec, spend_limits, web_search_summary 

32from app.services import attachments as attachments_service 

33from app.services.knowledge import citations as citations_service 

34from app.services.knowledge import retrievals as retrievals_service 

35from app.services.knowledge import repositories 

36from app.services.ai_client import ( 

37 AIServiceError, 

38 ModelNotAvailableError, 

39 ModelRefusedError, 

40 execute_agent_request, 

41 get_model, 

42 in_turn_governance, 

43 list_models, 

44 usage_capture, 

45) 

46from app.services.rules import scopes as rule_scopes 

47from app.util.knowledge_report import KnowledgeReport 

48from app.util import cost_profiles, history_window 

49from app.util.time import aware_utcnow 

50 

51logger = logging.getLogger(__name__) 

52 

53 

54# --------------------------------------------------------------------------- 

55# Helpers 

56# --------------------------------------------------------------------------- 

57 

58 

59def _resolve_model(db: Session, agent: Agent) -> dict: 

60 """ 

61 Resolve the LLM model for this agent. 

62 

63 Tries the agent's assigned model first, falls back to the default model. 

64 Raises RuntimeError if no model is available at all. 

65 

66 "Not available" covers a model this deployment cannot run as well as one 

67 svc-ai does not know: an agent assigned GPT-4o before the switch to 

68 Bedrock still names a catalogue row, but svc-ai refuses every call to it. 

69 A turn that falls back says so (``model_substitution``). 

70 """ 

71 model_info = None 

72 if agent.ai_model_id: 

73 try: 

74 model_info = get_model(agent.ai_model_id) 

75 except ModelNotAvailableError: 

76 logger.warning( 

77 "Assigned model %s for agent %s not available", 

78 agent.ai_model_id, 

79 agent.id, 

80 ) 

81 except AIServiceError as exc: 

82 logger.error( 

83 "Error fetching model %s from svc-ai: %s", agent.ai_model_id, exc 

84 ) 

85 if model_info is not None and model_info.get("is_available") is False: 

86 logger.warning( 

87 "Assigned model %s/%s for agent %s cannot run on this " 

88 "deployment; falling back to the default model", 

89 (model_info.get("provider") or {}).get("name"), 

90 model_info.get("model_name"), 

91 agent.id, 

92 ) 

93 model_info = None 

94 

95 if model_info is None: 

96 logger.info("Agent %s: falling back to default model", agent.id) 

97 available = list_models(is_available=True, is_default=True) 

98 if not available: 

99 raise RuntimeError("No default models available in svc-ai") 

100 model_info = available[0] 

101 

102 return model_info 

103 

104 

105def model_substitution(agent: Agent, model_info: dict) -> str | None: 

106 """What to tell the person when the agent's own model could not answer 

107 and the default did, or None when the agent's model answered.""" 

108 if not agent.ai_model_id or str(model_info.get("id")) == str(agent.ai_model_id): 

109 return None 

110 name = ( 

111 model_info.get("display_name") 

112 or model_info.get("model_name") 

113 or "the default model" 

114 ) 

115 return f"{agent.name}'s model is not available here; answering with {name}." 

116 

117 

118def _load_agent_skills(db: Session, agent: Agent) -> list[Skill]: 

119 """Return all Skills linked to this agent via an attached skillset. 

120 

121 Agents only ever integrate skills through a skillset (never 

122 individually) — mirroring how agents only ever integrate knowledge 

123 through a whole repository. 

124 

125 Ordered oldest-first so callers that execute ``skills[0]`` pick the same 

126 skill on every invocation — an unordered query hands execution to an 

127 arbitrary skill whenever an agent has more than one attached. A skill 

128 belonging to more than one attached skillset is deduplicated. 

129 """ 

130 rows = ( 

131 db.query(Skill) 

132 .join(SkillsetSkill, SkillsetSkill.skill_id == Skill.id) 

133 .join(AgentSkillset, AgentSkillset.skillset_id == SkillsetSkill.skillset_id) 

134 .filter(AgentSkillset.agent_id == agent.id) 

135 .all() 

136 ) 

137 by_id: dict[UUID, Skill] = {} 

138 for skill in rows: 

139 by_id.setdefault(skill.id, skill) 

140 return sorted(by_id.values(), key=lambda s: (s.created_at, s.id)) 

141 

142 

143def _reachable_by(agent: Agent, db: Session): 

144 """Knowledge the agent's workspace has, checked when it runs. 

145 

146 Grants are checked when they are made, but ownership, membership and 

147 what a project inherits change after that. So an agent reads only 

148 what its own workspace holds (``app/services/workspace.py``): its own 

149 sources; for a project's agent, the sources the project inherits from 

150 its parent; and every agent the built-ins. A personal agent no longer 

151 reaches its owner's organisations' sources — that would serve them to 

152 anyone a personal project shares the agent with. 

153 """ 

154 from app.services import workspace as workspace_service 

155 

156 home = workspace_service.home_of(db, agent) 

157 if home is None: 

158 # A built-in agent reads built-in knowledge only. 

159 return Knowledge.is_system.is_(True) 

160 return workspace_service.in_scope(Knowledge, home) 

161 

162 

163def _load_agent_knowledge_bases(db: Session, agent: Agent) -> list[dict]: 

164 """Return a list of knowledge base descriptors for all KBs granted to this agent. 

165 

166 Agents only ever integrate whole knowledge repositories (never individual 

167 sources), so this expands each attached repository to its member 

168 knowledge bases. A knowledge base belonging to more than one attached 

169 repository is deduplicated, taking the config of whichever repository 

170 grant is returned first. 

171 

172 Each dict has the fields expected by svc-ai's KnowledgeBaseSpec: 

173 id, name, description, source_type, config, category 

174 

175 ``category`` is the kind of the repositories the agent reaches it 

176 through, which decides how svc-ai uses it (``repositories.one_category``: 

177 a source joins repositories of one kind only, so they agree, but for a 

178 mix stored before categories existed, read as ``domain``). 

179 """ 

180 repo_rows = ( 

181 db.query( 

182 Knowledge, 

183 AgentRepository.config, 

184 KnowledgeRepository.category, 

185 KnowledgeRepository.name, 

186 ) 

187 .join(RepositoryKnowledge, RepositoryKnowledge.knowledge_id == Knowledge.id) 

188 .join( 

189 AgentRepository, 

190 AgentRepository.repository_id == RepositoryKnowledge.repository_id, 

191 ) 

192 .join( 

193 KnowledgeRepository, 

194 KnowledgeRepository.id == RepositoryKnowledge.repository_id, 

195 ) 

196 .filter(AgentRepository.agent_id == agent.id, _reachable_by(agent, db)) 

197 .all() 

198 ) 

199 

200 granted: dict[str, tuple[Knowledge, dict | None]] = {} 

201 kinds: dict[str, set[str]] = {} 

202 names: dict[str, set[str]] = {} 

203 for kb, cfg, category, repository_name in repo_rows: 

204 granted.setdefault(str(kb.id), (kb, cfg)) 

205 kinds.setdefault(str(kb.id), set()).add(category) 

206 names.setdefault(str(kb.id), set()).add(repository_name) 

207 specs: dict[str, dict] = { 

208 kid: retrieval_service.knowledge_spec( 

209 kb, 

210 cfg, 

211 category=repositories.one_category(kid, kinds[kid]), 

212 repositories=names[kid], 

213 ) 

214 for kid, (kb, cfg) in granted.items() 

215 } 

216 # Attach the document manifest of every vector KB so svc-ai can resolve a 

217 # file the user names even when indexing is pending or the vector store 

218 # is unreachable. 

219 manifests = retrieval_service.load_document_manifests( 

220 db, [kid for kid, spec in specs.items() if spec["source_type"] != "graph"] 

221 ) 

222 for kid, docs in manifests.items(): 

223 if kid in specs: 

224 specs[kid]["documents"] = docs 

225 return list(specs.values()) 

226 

227 

228def _load_agent_retrieval_config(agent: Agent) -> dict: 

229 """Return the agent's retrieval-pipeline overrides (svc-ai ``RetrievalConfig``). 

230 

231 Stored under ``agent.config["retrieval"]`` so users can tune retrieval per 

232 agent (mode, top_k, lexical search, reranking, context budget, …) without 

233 a schema change. Unknown or non-dict values yield ``{}`` so svc-ai applies 

234 its defaults. 

235 """ 

236 config = agent.config if isinstance(agent.config, dict) else {} 

237 retrieval = config.get("retrieval") 

238 return dict(retrieval) if isinstance(retrieval, dict) else {} 

239 

240 

241def _load_conversation( 

242 db: Session, 

243 conversation_id: UUID | None, 

244) -> tuple[Conversation | None, list[dict]]: 

245 """ 

246 Load an existing conversation and format its messages for svc-ai. 

247 

248 Returns (conversation_orm | None, formatted_history). 

249 """ 

250 conversation = None 

251 history: list[dict] = [] 

252 if conversation_id: 

253 conversation = db.get(Conversation, conversation_id) 

254 if conversation: 

255 # The newest messages within the outer bound (``history_window``) 

256 # — svc-ai fits them to the model; a long chat no longer ships its 

257 # whole past on every turn. 

258 for msg in history_window.newest( 

259 list(conversation.messages), 

260 role=lambda m: str(m.role.value), 

261 content=lambda m: m.content, 

262 ): 

263 entry: dict = {"role": str(msg.role.value), "content": msg.content} 

264 # The documents a message attached, by name: svc-ai reads the 

265 # message as its words and what it carried, and has the 

266 # documents themselves beside the turn (``attachments``). 

267 if msg.role == MessageEnum.Role.USER and ( 

268 refs := attachments_service.stored_refs(msg.meta) 

269 ): 

270 entry["attachments"] = [str(ref["name"]) for ref in refs] 

271 # Pass evaluator quality metadata on assistant messages so svc-ai's 

272 # planning node can avoid repeating gaps from the previous turn. 

273 if msg.role == MessageEnum.Role.ASSISTANT and msg.meta: 

274 eval_score = msg.meta.get("eval_score") 

275 eval_critique = msg.meta.get("eval_critique") 

276 eval_gaps = msg.meta.get("eval_gaps") 

277 if eval_score is not None or eval_critique or eval_gaps: 

278 entry["eval"] = { 

279 k: v 

280 for k, v in [ 

281 ("score", eval_score), 

282 ("critique", eval_critique), 

283 ("gaps", eval_gaps), 

284 ] 

285 if v is not None 

286 } 

287 history.append(entry) 

288 return conversation, history 

289 

290 

291#: What an answer keeps of each source it cites (``meta.cited_sources``): 

292#: what fe-core draws a citation from. The passage text (``snippet``), the 

293#: retrieval ``score`` and the ``chunk_span`` stay out: the UI reads none of 

294#: them, and the text is the knowledge base's to serve, not the message's. 

295CITED_SOURCE_KEYS: tuple[str, ...] = ( 

296 "index", 

297 # The number the answer cites it by: ``[2]`` in the text, and the entry 

298 # of its Sources block (svc-ai ``answer_sources``). 

299 "marker", 

300 "kind", 

301 "tool", 

302 "title", 

303 "source", 

304 "url", 

305 "kb_name", 

306 # The source a passage came from, when svc-ai names it (graph facts do; 

307 # a document's source is read from the document). The citations record 

308 # counts by it (``services/knowledge/citations.py``). 

309 "kb_id", 

310 "citation_id", 

311 "document_id", 

312 "page_number", 

313 "published", 

314 "author", 

315 "attribution", 

316 "licence_url", 

317 "fetched_at", 

318 "links", 

319 "via", 

320 "collection", 

321) 

322#: The fields of a source a person reads, redacted like the answer's text. 

323#: Ids, kinds, page numbers and dates are kept as svc-ai sent them: a 

324#: detector can match a UUID's digits (one in a few thousand reads as a phone 

325#: number or a card), which would corrupt the id and protect nothing. 

326_REDACTED_SOURCE_KEYS = frozenset( 

327 { 

328 "title", 

329 "source", 

330 "url", 

331 "kb_name", 

332 "collection", 

333 "author", 

334 "attribution", 

335 "licence_url", 

336 "links", 

337 "via", 

338 } 

339) 

340 

341 

342def cited_sources_meta(citations: list | None) -> list[dict]: 

343 """The answer's own citations (svc-ai's ``cited_citations``) as the answer 

344 stores them: each one's :data:`CITED_SOURCE_KEYS` that hold a value.""" 

345 return [ 

346 {key: c[key] for key in CITED_SOURCE_KEYS if c.get(key) is not None} 

347 for c in citations or [] 

348 if isinstance(c, dict) 

349 ] 

350 

351 

352def stored_cited_sources(cited: Any, output_rules: Any) -> list[dict] | None: 

353 """What an answer stores as its sources (``meta.cited_sources``). 

354 

355 ``cited`` is the list svc-ai sent — the stream's final ``citations`` 

356 frame, or ``cited_citations`` on a batch response — and anything else 

357 (an svc-ai that sent none) is None: nothing is stored, and a reloaded 

358 chat falls back to what it showed. An empty list is kept: the answer 

359 cites nothing. Every field a person reads (:data:`_REDACTED_SOURCE_KEYS`) 

360 goes through the turn's audit redaction (``RulePass.redact``), as the 

361 answer's text did, so a value a ``redact_pii`` rule hid in the answer is 

362 hidden in a source's title or URL behind the same placeholder. 

363 """ 

364 if not isinstance(cited, list): 

365 return None 

366 sources = cited_sources_meta(cited) 

367 if isinstance(output_rules, rule_engine.RulePass): 

368 sources = [ 

369 { 

370 key: output_rules.redact(value) 

371 if key in _REDACTED_SOURCE_KEYS 

372 else value 

373 for key, value in source.items() 

374 } 

375 for source in sources 

376 ] 

377 return sources 

378 

379 

380def _persist_conversation( 

381 db: Session, 

382 agent: Agent, 

383 conversation: Conversation | None, 

384 prompt: str, 

385 response: str, 

386 sent_at: datetime, 

387 in_tokens: int = 0, 

388 out_tokens: int = 0, 

389 user_id: str | None = None, 

390 trace: list[dict] | None = None, 

391 segments: list[dict] | None = None, 

392 output_format: str | None = None, 

393 output_schema: str | None = None, 

394 conversation_id: UUID | None = None, 

395 model_name: str | None = None, 

396 provider: str | None = None, 

397 eval_result: dict | None = None, 

398 status: MessageEnum.Status = MessageEnum.Status.COMPLETED, 

399 rule_name: str | None = None, 

400 agent_version: int | None = None, 

401 hitl: list[dict] | None = None, 

402 workspace: Any = None, 

403 user_meta: dict | None = None, 

404 stopped: bool = False, 

405 invocation_id: str | UUID | None = None, 

406 lighter: dict | None = None, 

407 cost_profile: str | None = None, 

408 cited_sources: list[dict] | None = None, 

409 withheld: dict | None = None, 

410 web_search: dict | None = None, 

411 knowledge_report: KnowledgeReport | None = None, 

412) -> Conversation: 

413 """ 

414 Persist user + assistant messages to the conversation, creating one if needed. 

415 

416 ``invocation_id`` is the turn's id (``rule_engine.new_invocation_id``), 

417 stamped on both messages: the key of the answer's decision record. 

418 

419 ``cited_sources`` is what the answer cites (``stored_cited_sources``: 

420 projected and redacted), stored as ``meta.cited_sources`` — an empty 

421 list included, which says the answer cites nothing — so a reloaded chat 

422 and Activity show the answer's own sources. None stores nothing (an 

423 svc-ai that sent none), and a blocked turn never stores any. 

424 

425 ``stopped`` marks an answer the person stopped (``meta.stopped``): what it 

426 had written, which a chat shows as stopped rather than as an error. 

427 

428 ``knowledge_report`` is what the turn asked of the agent's knowledge and 

429 what each source gave, as stored (``retrievals.prepared``: redacted, and 

430 without the person's words for a withheld answer), kept beside the 

431 citations as the retrieval record (``services/knowledge/retrievals.py``). 

432 None for an agent with no knowledge, or an svc-ai that sent none. 

433 

434 ``web_search`` is what the turn's web searches came to 

435 (``web_search_summary.summarise``), stored as ``meta.web_search``: the 

436 outcome, what the engines failed with, what each check removed and what 

437 each Tools rule did. None when the turn made no search. 

438 

439 ``withheld`` marks an answer an Output rule withheld (``meta.withheld``, 

440 ``rule_engine.Withheld.meta``): ``response`` is then the rule's message, 

441 and the answer's sources are not stored — the answer itself went only to 

442 its review item. 

443 

444 ``lighter`` says an Economy profile's lighter model wrote the answer 

445 (``meta.lighter_model``, ``services/lighter_model.py``) — its name is 

446 the answer's ``model_name``. ``cost_profile`` is the profile the agent 

447 ran under, stored when it is not the default (``meta.cost_profile``). 

448 

449 ``user_meta`` goes on the user's message: the chat command the turn ran 

450 (``app/services/chat_commands.py``), when it ran one. 

451 

452 A new conversation is stamped with the ``workspace`` it was had in 

453 (``app/services/workspace.py``) — or, with none, the agent's own — so a 

454 workspace lists its conversations. 

455 

456 ``segments`` is an ordered list of ``{worker_slug, content, sequence}`` dicts 

457 from multi-agent skill runs. Each becomes a ``ChatMessageSegment`` child row 

458 on the assistant ``ChatMessage``. 

459 

460 ``status`` records the outcome of this turn — COMPLETED for a normal 

461 response, BLOCKED when a policy rule fired, ERROR for any other failure. 

462 The user's message always keeps status COMPLETED (their prompt was 

463 genuinely received); only the assistant message reflects the outcome, so 

464 a blocked/errored turn is still visible in History/Activity instead of 

465 being dropped before it ever reaches the DB. ``rule_name`` is recorded in 

466 the assistant message's meta when the turn was blocked. 

467 """ 

468 assistant_meta: dict = {} 

469 if out_tokens > 0: 

470 assistant_meta["token_count"] = out_tokens 

471 if output_format and output_format != "markdown": 

472 assistant_meta["output_format"] = output_format 

473 if output_schema: 

474 assistant_meta["output_schema"] = output_schema 

475 if model_name: 

476 assistant_meta["model_name"] = model_name 

477 if provider: 

478 assistant_meta["provider"] = provider 

479 if rule_name: 

480 assistant_meta["rule"] = rule_name 

481 # Which revision of the agent answered. Resolved when the agent's 

482 # configuration was *read*, not when the turn finished, so an edit landing 

483 # mid-turn cannot make the record claim a version that never ran it. It 

484 # survives every later edit and resolves, through the agent's own 

485 # /history, to a full snapshot and a diff — which is what makes a result 

486 # traceable rather than merely attributed. 

487 if agent_version is not None: 

488 assistant_meta["agent_version"] = agent_version 

489 if agent is not None and getattr(agent, "id", None) is not None: 

490 assistant_meta["agent_id"] = str(agent.id) 

491 # Store evaluator quality signal so it can be passed back to svc-ai on the 

492 # next turn — the planning node uses it to avoid repeating quality gaps — 

493 # and so the answer shows what its quality check concluded. No score is 

494 # stored when no check ran (``quality_check.Outcome.unavailable``). 

495 if eval_result: 

496 if eval_result.get("outcome"): 

497 assistant_meta["eval_outcome"] = eval_result["outcome"] 

498 if eval_result.get("score") is not None: 

499 assistant_meta["eval_score"] = eval_result["score"] 

500 if eval_result.get("critique"): 

501 assistant_meta["eval_critique"] = eval_result["critique"] 

502 if eval_result.get("gaps"): 

503 assistant_meta["eval_gaps"] = eval_result["gaps"] 

504 # What the check named and set aside (the agent's own work, what was 

505 # not asked, presentation): for whoever reviews the check, never sent 

506 # back to svc-ai's planning. 

507 if eval_result.get("set_aside"): 

508 assistant_meta["eval_set_aside"] = eval_result["set_aside"] 

509 # Every time the turn stopped for the person — what it asked or held, 

510 # what they answered, who answered and when (``services/hitl.py``). 

511 # Kept on the message so the conversation itself is the audit record, 

512 # readable after the trace has been collapsed. 

513 if hitl: 

514 assistant_meta["hitl"] = hitl 

515 if stopped: 

516 assistant_meta["stopped"] = True 

517 if lighter: 

518 assistant_meta["lighter_model"] = lighter 

519 if cost_profile and cost_profile != cost_profiles.DEFAULT: 

520 assistant_meta["cost_profile"] = cost_profile 

521 # Its sources come from svc-ai's answer, and a blocked turn's reply is 

522 # the rule's message, which cites nothing — as is a withheld one's. 

523 if withheld: 

524 assistant_meta["withheld"] = withheld 

525 elif cited_sources is not None and status != MessageEnum.Status.BLOCKED: 

526 assistant_meta["cited_sources"] = cited_sources 

527 if web_search: 

528 assistant_meta["web_search"] = web_search 

529 

530 turn_invocation = _invocation_uuid(invocation_id) 

531 assistant_msg = ChatMessage( 

532 role=MessageEnum.Role.ASSISTANT, 

533 status=status, 

534 content=response, 

535 sent_at=sent_at, 

536 token_count=out_tokens or len(response.split()), 

537 trace=trace or None, 

538 meta=assistant_meta or None, 

539 invocation_id=turn_invocation, 

540 segments=[ 

541 ChatMessageSegment( 

542 worker_slug=seg["worker_slug"], 

543 content=seg["content"], 

544 sequence=seg["sequence"], 

545 ) 

546 for seg in (segments or []) 

547 ], 

548 ) 

549 

550 # Assign strictly increasing timestamps so ORDER BY sent_at always returns 

551 # user before assistant — equal timestamps would produce non-deterministic 

552 # ordering in PostgreSQL, which breaks conversation structure. 

553 user_msg = ChatMessage( 

554 role=MessageEnum.Role.USER, 

555 status=MessageEnum.Status.COMPLETED, 

556 content=prompt, 

557 sent_at=sent_at, 

558 token_count=len(prompt.split()), 

559 meta=user_meta or None, 

560 invocation_id=turn_invocation, 

561 ) 

562 assistant_msg.sent_at = sent_at + timedelta(microseconds=1) 

563 

564 new_messages: list[ChatMessage] = [user_msg, assistant_msg] 

565 

566 if conversation: 

567 conversation.messages.extend(new_messages) 

568 conversation.total_input_tokens += in_tokens 

569 conversation.total_output_tokens += out_tokens 

570 conversation.total_tokens += in_tokens + out_tokens 

571 logger.debug("Updated conversation %s", conversation.id) 

572 else: 

573 from uuid import UUID as _UUID 

574 

575 conversation = Conversation( 

576 **({"id": conversation_id} if conversation_id else {}), 

577 agent_id=agent.id, 

578 ai_model_id=None, 

579 owner_user_id=_UUID(user_id) if user_id else agent.owner_user_id, 

580 owner_organisation_id=None if user_id else agent.owner_organisation_id, 

581 owner_project_id=None if user_id else agent.owner_project_id, 

582 **_conversation_workspace(workspace, agent), 

583 messages=new_messages, 

584 total_input_tokens=in_tokens, 

585 total_output_tokens=out_tokens, 

586 total_tokens=in_tokens + out_tokens, 

587 ) 

588 db.add(conversation) 

589 logger.debug("Created new conversation for agent %s", agent.id) 

590 

591 # Which knowledge sources the answer cites, as rows a source's page can 

592 # count (``services/knowledge/citations.py``) — exactly the sources it 

593 # stores, so a withheld or blocked answer records none — and what its 

594 # knowledge gave (``services/knowledge/retrievals.py``). Each in a 

595 # savepoint: the answer is stored whatever its records do. 

596 cited = assistant_meta.get("cited_sources") 

597 if cited or knowledge_report is not None: 

598 db.flush() 

599 if cited: 

600 try: 

601 with db.begin_nested(): 

602 citations_service.record( 

603 db, assistant_msg, cited, agent=agent, conversation=conversation 

604 ) 

605 except Exception: # noqa: BLE001 — never costs the person their answer 

606 logger.warning( 

607 "Could not record the citations of message %s", assistant_msg.id 

608 ) 

609 if knowledge_report is not None: 

610 try: 

611 with db.begin_nested(): 

612 retrievals_service.record( 

613 db, 

614 assistant_msg, 

615 knowledge_report, 

616 agent=agent, 

617 conversation=conversation, 

618 cited=cited, 

619 ) 

620 except Exception: # noqa: BLE001 — never costs the person their answer 

621 logger.warning( 

622 "Could not record the retrievals of message %s", assistant_msg.id 

623 ) 

624 

625 db.commit() 

626 db.refresh(conversation) 

627 return conversation 

628 

629 

630def _invocation_uuid(invocation_id: str | UUID | None) -> UUID | None: 

631 """The turn's id as the column takes it; None when absent or malformed.""" 

632 if invocation_id is None or isinstance(invocation_id, UUID): 

633 return invocation_id 

634 try: 

635 return UUID(str(invocation_id)) 

636 except ValueError: 

637 return None 

638 

639 

640def _conversation_workspace(workspace: Any, agent: Agent) -> dict: 

641 """A new conversation's workspace columns.""" 

642 if workspace is not None: 

643 stamp = workspace.ledger_stamp() 

644 return { 

645 "workspace_organisation_id": stamp["owner_organisation_id"], 

646 "workspace_project_id": stamp["owner_project_id"], 

647 } 

648 return { 

649 "workspace_organisation_id": getattr(agent, "owner_organisation_id", None), 

650 "workspace_project_id": getattr(agent, "owner_project_id", None), 

651 } 

652 

653 

654def latest_assistant_message_id(conversation: Conversation | None): 

655 """The id of the assistant message just persisted onto ``conversation``. 

656 

657 ``_persist_conversation`` assigns strictly increasing ``sent_at`` values 

658 precisely so the turn's ordering is deterministic, which is what makes 

659 "the newest assistant message" the one this turn wrote. Used to point the 

660 governance activity log at the exact message its rules ran on. 

661 """ 

662 if conversation is None: 

663 return None 

664 assistant = [ 

665 message 

666 for message in (conversation.messages or []) 

667 if message.role == MessageEnum.Role.ASSISTANT 

668 ] 

669 if not assistant: 

670 return None 

671 return max(assistant, key=lambda message: message.sent_at).id 

672 

673 

674def persist_blocked_turn( 

675 db: Session, 

676 agent: Agent, 

677 conversation: Conversation | None, 

678 prompt: str, 

679 sent_at: datetime, 

680 rule_name: str, 

681 message: str, 

682 user_id: str | None = None, 

683 conversation_id: UUID | None = None, 

684 *, 

685 block: rule_engine.BlockLike | None = None, 

686 workspace: Any = None, 

687 user_meta: dict | None = None, 

688 invocation_id: str | UUID | None = None, 

689) -> Conversation: 

690 """Persist a turn that a governance policy rule blocked. 

691 

692 Pass ``block`` wherever the originating exception is in hand — a 

693 ``RuleBlock`` enforced here, or an ``ai_client.RuleBlockedError`` reported 

694 by svc-ai. The persisted trace then records which rule id and version 

695 blocked the turn, not just a name that may later be renamed or deleted. 

696 """ 

697 return _persist_conversation( 

698 db, 

699 agent, 

700 conversation, 

701 prompt, 

702 message, 

703 sent_at, 

704 user_id=user_id, 

705 conversation_id=conversation_id, 

706 trace=( 

707 rule_engine.build_block_trace_from_exc(block) 

708 if block is not None 

709 else rule_engine.build_block_trace(rule_name, message) 

710 ) 

711 or None, 

712 status=MessageEnum.Status.BLOCKED, 

713 rule_name=rule_name, 

714 workspace=workspace, 

715 user_meta=user_meta, 

716 invocation_id=invocation_id, 

717 # Stamped on a refused turn too: an audit asks which configuration the 

718 # request was made *against*, and a block is the case most likely to be 

719 # challenged later. 

720 agent_version=history_service.current_version( 

721 db, HistoryEnum.ResourceType.agent, getattr(agent, "id", None) 

722 ), 

723 ) 

724 

725 

726def _record_failed_invocation( 

727 db: Session, 

728 agent: Agent, 

729 *, 

730 user_id: str | None, 

731 model_info: dict | None, 

732 latency_ms: float | None, 

733 measured: Any = None, 

734 workspace: Any = None, 

735 invocation_id: str | UUID | None = None, 

736) -> None: 

737 """Append a ledger row for an invocation that was attempted and failed. 

738 

739 An error *rate* per agent or per model has to be counted somewhere, and 

740 svc-ai's per-invocation record carries no agent, project or organisation 

741 to count it against — so it is counted here, on the ledger that already 

742 stamps all three (see ``app.services.stats``). 

743 

744 No quota is affected: ``UsageWindow`` filters to successful rows, so a 

745 provider outage cannot consume somebody's hourly allowance. Tokens and 

746 cost are recorded as nothing rather than estimated, because a call that 

747 did not return produced no answer to charge for — unless svc-ai metered 

748 calls before it failed (``measured``), which were paid for all the same. 

749 """ 

750 usage_service.record_usage( 

751 db, 

752 owner_user_id=user_id, 

753 execution_type="agent", 

754 scope_type="agent", 

755 scope_id=str(agent.id), 

756 owner_project_id=agent.owner_project_id, 

757 owner_organisation_id=agent.owner_organisation_id, 

758 ai_model_id=model_info.get("id") if model_info else None, 

759 model_info=model_info, 

760 latency_ms=latency_ms, 

761 outcome=UsageEnum.Outcome.error, 

762 source_type=UsageEnum.Source.agent, 

763 source_id=agent.id, 

764 measured=measured, 

765 workspace=workspace, 

766 invocation_id=invocation_id, 

767 ) 

768 

769 

770def persist_error_turn( 

771 db: Session, 

772 agent: Agent, 

773 conversation: Conversation | None, 

774 prompt: str, 

775 sent_at: datetime, 

776 message: str, 

777 user_id: str | None = None, 

778 conversation_id: UUID | None = None, 

779 workspace: Any = None, 

780 *, 

781 user_meta: dict | None = None, 

782 stopped: bool = False, 

783 invocation_id: str | UUID | None = None, 

784) -> Conversation: 

785 """Persist a turn that failed for a reason other than a policy rule 

786 (provider error, timeout, tool failure, etc.) so it's still visible in 

787 History/Activity instead of being lost when the exception propagates. 

788 ``stopped``: the person stopped it, and ``message`` is what it wrote.""" 

789 return _persist_conversation( 

790 db, 

791 agent, 

792 conversation, 

793 prompt, 

794 message, 

795 sent_at, 

796 user_id=user_id, 

797 conversation_id=conversation_id, 

798 status=MessageEnum.Status.ERROR, 

799 workspace=workspace, 

800 user_meta=user_meta, 

801 stopped=stopped, 

802 invocation_id=invocation_id, 

803 agent_version=history_service.current_version( 

804 db, HistoryEnum.ResourceType.agent, getattr(agent, "id", None) 

805 ), 

806 ) 

807 

808 

809# --------------------------------------------------------------------------- 

810# Deprecated / simple accessors (kept for other callers) 

811# --------------------------------------------------------------------------- 

812 

813 

814def list_agents(db: Session) -> list[Agent]: 

815 return db.query(Agent).all() 

816 

817 

818def get_agent(db: Session, agent_id: UUID) -> Agent | None: 

819 return db.get(Agent, agent_id) 

820 

821 

822# --------------------------------------------------------------------------- 

823# Main prompt handler 

824# --------------------------------------------------------------------------- 

825 

826 

827def prompt_agent( 

828 db: Session, 

829 agent: Agent, 

830 request: Schema.Agent.Prompt, 

831 user_id: str = "system", 

832 on_status: Callable[[str], None] | None = None, 

833 invocation_id: str | None = None, 

834 input_rules: tuple | None = None, 

835 workspace: Any = None, 

836 command: Any = None, 

837 model_info: dict[str, Any] | None = None, 

838 attachments: list[Any] | None = None, 

839) -> tuple[str, UUID, list[dict]]: 

840 """ 

841 Execute a prompt against an agent via the unified dynamic graph. 

842 

843 Execution priority: 

844 1. **Skill** — agent has skills assigned → svc-ai skill graph execution 

845 2. **Agent** — has tools or knowledge bases → svc-ai dynamic execution 

846 

847 Calls on_status(message) at each significant step when provided. 

848 Output (audit) rules are evaluated here, before persistence, so a 

849 redact_pii/flag_for_review rule actually affects what gets stored — not 

850 just the HTTP response the caller returns to the client. 

851 

852 ``invocation_id`` is the caller's id for this turn: the policy rules ran 

853 before this function was entered, so passing it is what groups those and 

854 the audit rules below as one invocation in the governance activity log. 

855 The ledger row, the messages and any flags carry it too, and the caller 

856 names it to svc-ai (``ai_client.use_invocation``) for its traces. 

857 

858 ``input_rules`` is what the caller's ``evaluate_input`` returned. Passing 

859 it puts the policy node in the persisted trace beside the audit node, with 

860 svc-ai's enforcement of the same rules merged into each. 

861 

862 ``command`` is the chat command the turn runs, when it runs one 

863 (``app/services/chat_commands.py``): its skill answers in place of the 

864 agent's own, and its record goes on the user's message. 

865 

866 ``model_info`` is the agent's model as the caller resolved it before its 

867 policy rules, so they govern the model that answers; without it the 

868 agent's own model is resolved here. 

869 

870 ``attachments`` are the documents the message attaches 

871 (``attachments.turn_attachments``), which the caller's policy rules read 

872 with its words. They and the documents the conversation's earlier 

873 messages attached go to svc-ai beside the words, through the rules' 

874 redaction, and the message keeps them by id. 

875 

876 Returns (response_text, conversation_id, rule_trace) — the turn's rule 

877 trace, both phases. 

878 

879 Raises RuntimeError if execution fails after persisting an ERROR-status 

880 turn recording the attempt. 

881 """ 

882 

883 def _status(msg: str) -> None: 

884 if on_status: 

885 on_status(msg) 

886 

887 invocation_id = invocation_id or rule_engine.new_invocation_id() 

888 sent_at = aware_utcnow() 

889 

890 if model_info is None: 

891 _status(f"Resolving model for {agent.name}…") 

892 model_info = _resolve_model(db, agent) 

893 if note := model_substitution(agent, model_info): 

894 _status(note) 

895 provider = model_info["provider"]["name"] 

896 model_name = model_info["model_name"] 

897 config = model_info.get("config") or {} 

898 # What the agent brings to the turn — the one reading every path that 

899 # runs an agent shares (``app/services/agent_spec.py``). 

900 setup = agent_spec.load(db, agent) 

901 # Captured here, alongside the configuration it describes, rather than at 

902 # persistence: an edit landing mid-turn must not make the record claim a 

903 # revision that never ran this prompt. 

904 agent_version = history_service.current_version( 

905 db, HistoryEnum.ResourceType.agent, agent.id 

906 ) 

907 

908 _status("Loading conversation history…") 

909 conversation, history = _load_conversation(db, request.conversation_id) 

910 # The stored history goes to the model with the prompt, so it meets the 

911 # prompt's redaction — a turn stored before the rule existed is otherwise 

912 # sent as it was typed. 

913 if isinstance(input_rules, rule_engine.RulePass): 

914 history = input_rules.redact_history(history) 

915 # Pre-determine conversation UUID so svc-ai records the correct 

916 # conversation_id even for the first message of a new conversation. 

917 target_conversation_id = str(conversation.id) if conversation else str(uuid4()) 

918 agent_id_str = str(agent.id) 

919 # A command chose the skill; otherwise the agent's own, if it holds any. 

920 skills = [command.dispatch.skill] if command is not None else list(setup.skills) 

921 # The command's form values and its record, through the policy rules' 

922 # redaction like the prompt they travel with. 

923 command_inputs: dict = {} 

924 command_meta = None 

925 if command is not None: 

926 command_inputs = dict(command.inputs) 

927 command_meta = command.meta() 

928 if isinstance(input_rules, rule_engine.RulePass): 

929 command_inputs = input_rules.redact(command_inputs) 

930 command_meta = input_rules.redact(command_meta) 

931 from app.services import workspace as workspace_service 

932 

933 turn_ws = ( 

934 workspace if workspace is not None else workspace_service.home_of(db, agent) 

935 ) 

936 # The documents the turn carries — this message's, then the earlier 

937 # messages' — through the policy rules' redaction like the words. 

938 this_turn = list(attachments or []) 

939 turn_docs = attachments_service.redacted( 

940 attachments_service.for_turn( 

941 this_turn, 

942 attachments_service.earlier_attachments( 

943 db, conversation, turn_ws, exclude=[d.id for d in this_turn] 

944 ), 

945 ), 

946 input_rules, 

947 ) 

948 user_meta = attachments_service.message_meta(command_meta, turn_docs) 

949 # Every governed resource this turn touches — the agent, the skill it 

950 # answers through, its model, and the project/organisation that owns it. 

951 # One chain serves the rule forwarding below and the audit evaluation 

952 # after the call, so both see the same set. 

953 scope_chain = rule_scopes.serialize( 

954 rule_scopes.invocation_chain( 

955 agent=agent, 

956 skill=skills[0] if skills else None, 

957 model_id=model_info.get("id") if model_info else None, 

958 ) 

959 ) 

960 

961 # What the turn's rules hand svc-ai: the most it may spend — what is 

962 # left of the tightest budget that let it start, where svc-ai stops it 

963 # (``app/services/spend_limits.py``) — and the web sources its Tools 

964 # rules set. 

965 turn_rules = input_rules if isinstance(input_rules, rule_engine.RulePass) else None 

966 

967 def _refused(exc: ModelRefusedError, used: Any, started: float) -> None: 

968 """svc-ai could not use the model, or a budget stopped the turn: 

969 stored with the message that says why — never "Agent execution 

970 failed" — with what it spent, and re-raised for the caller.""" 

971 logger.warning("Agent %s turn refused by svc-ai (%s)", agent.id, exc.code) 

972 _record_failed_invocation( 

973 db, 

974 agent, 

975 user_id=user_id, 

976 model_info=model_info, 

977 latency_ms=(perf_counter() - started) * 1000, 

978 measured=used, 

979 workspace=workspace, 

980 invocation_id=invocation_id, 

981 ) 

982 spend_limits.record_stop( 

983 exc, 

984 { 

985 "execution_type": "agent", 

986 "user_id": user_id, 

987 "agent_id": agent_id_str, 

988 "scope_type": "agent", 

989 "scope_id": agent_id_str, 

990 rule_engine.WORKSPACE_CONTEXT_KEY: workspace.key 

991 if workspace is not None 

992 else None, 

993 rule_engine.INVOCATION_CONTEXT_KEY: invocation_id, 

994 }, 

995 user_id, 

996 db=db, 

997 ) 

998 persist_error_turn( 

999 db, 

1000 agent, 

1001 conversation, 

1002 request.prompt, 

1003 sent_at, 

1004 exc.user_message, 

1005 user_id=user_id, 

1006 conversation_id=( 

1007 UUID(target_conversation_id) if not conversation else None 

1008 ), 

1009 workspace=workspace, 

1010 user_meta=user_meta, 

1011 invocation_id=invocation_id, 

1012 ) 

1013 raise exc 

1014 

1015 # Forward the applicable policy/audit rules so svc-ai enforces them inside 

1016 # its execution engines as well as at the svc-core edge. 

1017 rule_specs = rule_engine.serialize_rules( 

1018 db, 

1019 user_id, 

1020 scopes=scope_chain, 

1021 workspace=workspace.key if workspace is not None else None, 

1022 ) 

1023 

1024 skill = skills[0] if skills else None 

1025 graph_definition = None 

1026 if skill is not None: 

1027 if len(skills) > 1: 

1028 logger.warning( 

1029 "Agent %s has %d skills — only %r (%s) will run; skill " 

1030 "composition is not yet supported, the remaining skills are " 

1031 "ignored: %s", 

1032 agent.id, 

1033 len(skills), 

1034 skill.name, 

1035 skill.id, 

1036 [s.name for s in skills[1:]], 

1037 ) 

1038 logger.info( 

1039 "Agent %s: routing through skill %r (%s)", agent.id, skill.name, skill.id 

1040 ) 

1041 _status(f"Running {agent.name} via skill '{skill.name}'…") 

1042 # What the agent reads: its own workspace's (``_reachable_by``). 

1043 graph_definition, graph_notes = agent_spec.resolve_skill(db, setup, skill) 

1044 for note in graph_notes: 

1045 _status(note) 

1046 else: 

1047 # Built-in tools are not forwarded: svc-ai binds the general set to 

1048 # every agent itself. What an agent adds on top of that is its 

1049 # knowledge and its MCP servers, both grants svc-core owns. 

1050 configured = [kb["name"] for kb in setup.knowledge_bases] + [ 

1051 s["name"] for s in setup.mcp_servers 

1052 ] 

1053 logger.info( 

1054 "Agent %s: executing with %d KB(s) and %d MCP server(s) " 

1055 "(+ svc-ai's general tools)", 

1056 agent.id, 

1057 len(setup.knowledge_bases), 

1058 len(setup.mcp_servers), 

1059 ) 

1060 _status( 

1061 f"Running {agent.name} with {', '.join(configured)}…" 

1062 if configured 

1063 else f"Running {agent.name}…" 

1064 ) 

1065 # An Economy profile's lighter model (``services/lighter_model.py``) 

1066 # and a native sibling for the structured steps 

1067 # (``services/native_sibling.py``). 

1068 from app.services import lighter_model as lighter_service 

1069 from app.services import native_sibling 

1070 

1071 lighter = lighter_service.for_turn( 

1072 db, 

1073 profile=setup.cost_profile, 

1074 model_info=model_info, 

1075 ws=turn_ws, 

1076 ) 

1077 structured = native_sibling.for_turn( 

1078 db, 

1079 model_info=model_info, 

1080 lighter=lighter, 

1081 ws=turn_ws, 

1082 ) 

1083 agent_request = agent_spec.build( 

1084 setup, 

1085 model_info=model_info, 

1086 config=config, 

1087 skill=skill, 

1088 graph_definition=graph_definition, 

1089 # A command's form values seed the graph state. 

1090 inputs=command_inputs, 

1091 lighter=lighter, 

1092 structured=structured, 

1093 ) 

1094 # Timed around the svc-ai call for the ledger's latency figure — the loads 

1095 # above are svc-core's own cost. 

1096 invocation_started = perf_counter() 

1097 # svc-ai's whole response, for the answer's own sources beside the figures. 

1098 answer_body: dict[str, Any] = {} 

1099 try: 

1100 with usage_capture() as used, in_turn_governance(turn_rules): 

1101 response, in_tokens, out_tokens, remote_rule_events = execute_agent_request( 

1102 agent_request.payload( 

1103 prompt=request.prompt, 

1104 messages=history, 

1105 user_id=user_id, 

1106 rules=rule_specs, 

1107 conversation_id=target_conversation_id, 

1108 external_agent_id=agent_id_str, 

1109 attachments=attachments_service.wire(turn_docs), 

1110 ), 

1111 body=answer_body, 

1112 ) 

1113 except ModelRefusedError as exc: 

1114 _refused(exc, used, invocation_started) 

1115 except AIServiceError: 

1116 logger.exception( 

1117 "Agent execution failed for agent %s%s", 

1118 agent.id, 

1119 f" (skill {skill.id})" if skill is not None else "", 

1120 ) 

1121 _record_failed_invocation( 

1122 db, 

1123 agent, 

1124 user_id=user_id, 

1125 model_info=model_info, 

1126 latency_ms=(perf_counter() - invocation_started) * 1000, 

1127 measured=used, 

1128 workspace=workspace, 

1129 invocation_id=invocation_id, 

1130 ) 

1131 persist_error_turn( 

1132 db, 

1133 agent, 

1134 conversation, 

1135 request.prompt, 

1136 sent_at, 

1137 "Agent execution failed", 

1138 user_id=user_id, 

1139 conversation_id=( 

1140 UUID(target_conversation_id) if not conversation else None 

1141 ), 

1142 workspace=workspace, 

1143 user_meta=user_meta, 

1144 invocation_id=invocation_id, 

1145 ) 

1146 raise RuntimeError("Agent execution failed") 

1147 

1148 # Measured around the svc-ai call only — audit rules and persistence run 

1149 # after this and are svc-core's own cost, not the model's. Attributing 

1150 # them to the model would make every model look slower than it is. 

1151 invocation_latency_ms = (perf_counter() - invocation_started) * 1000 

1152 

1153 # ── Rule enforcement: audit (output) ────────────────────────────────── 

1154 output_ctx = { 

1155 # What the policy rules read: the words with this message's documents. 

1156 "prompt": input_rules.text 

1157 if isinstance(input_rules, rule_engine.RulePass) 

1158 else request.prompt, 

1159 "execution_type": "agent", 

1160 "user_id": user_id, 

1161 "agent_id": agent_id_str, 

1162 "agent_name": agent.name, 

1163 "model_name": model_name, 

1164 "provider": provider, 

1165 "scope_type": "agent", 

1166 "scope_id": agent_id_str, 

1167 rule_engine.SCOPES_CONTEXT_KEY: scope_chain, 

1168 rule_engine.WORKSPACE_CONTEXT_KEY: workspace.key 

1169 if workspace is not None 

1170 else None, 

1171 rule_engine.INVOCATION_CONTEXT_KEY: invocation_id, 

1172 # How long the model took and what it cost — the ledger's figures — 

1173 # so an audit rule on either has a value to compare. 

1174 **usage_service.audit_figures( 

1175 latency_ms=invocation_latency_ms, 

1176 measured=used, 

1177 input_tokens=in_tokens, 

1178 output_tokens=out_tokens, 

1179 model_info=model_info, 

1180 ), 

1181 } 

1182 output_rules = rule_engine.evaluate_output(db, response, output_ctx, user_id) 

1183 response, output_rule_events = output_rules 

1184 # What the answer cites (svc-ai's ``cited_citations``), through the same 

1185 # redaction as its text. Absent from an svc-ai that predates it: stored 

1186 # as nothing, not as "cites nothing". A withheld answer's are not kept. 

1187 withheld = getattr(output_rules, "withheld", None) 

1188 cited_sources = ( 

1189 None 

1190 if withheld is not None 

1191 else stored_cited_sources(answer_body.get("cited_citations"), output_rules) 

1192 ) 

1193 # The turn's web searches, as svc-ai reported them: the answer's summary 

1194 # of them, and its Tools rules settled on them — "applied" only where 

1195 # one changed a search (``web_search_summary``). Settled before the 

1196 # trace is built, so it shows what each rule did. 

1197 web_reports = list(used.web_searches) 

1198 tools_settled: dict[str, dict] = {} 

1199 if isinstance(input_rules, rule_engine.RulePass): 

1200 settled_input = web_search_summary.settle(input_rules.evaluations, web_reports) 

1201 tools_settled = web_search_summary.settled_changes( 

1202 input_rules.evaluations, settled_input 

1203 ) 

1204 input_rules.evaluations = settled_input 

1205 web_search = web_search_summary.summarise( 

1206 web_reports, 

1207 getattr(input_rules, "evaluations", None), 

1208 held=withheld is not None, 

1209 ) 

1210 # One node per phase, each listing every applicable rule, with what svc-ai 

1211 # enforced of the same rules folded into the entry for that rule. 

1212 rule_trace = rule_engine.build_turn_rule_trace( 

1213 input_rules, output_rules, remote_rule_events 

1214 ) 

1215 

1216 # The model that wrote the answer, when it was the lighter one svc-ai was 

1217 # given: the ledger counts it, and the answer names it. 

1218 answered_model = lighter_service.answered( 

1219 agent_request.lighter_model, used.answered_by 

1220 ) 

1221 answered_info = answered_model or model_info 

1222 

1223 # Recorded before the turn is committed, so the counter behind rate limits 

1224 # and cost caps can never include a turn that was rolled back. Cost is 

1225 # what svc-ai measured across every model call of the turn (``used``); 

1226 # the model record resolved above is the fallback when nothing was metered. 

1227 usage_service.record_usage( 

1228 db, 

1229 workspace=workspace, 

1230 owner_user_id=user_id, 

1231 execution_type="agent", 

1232 scope_type="agent", 

1233 scope_id=agent_id_str, 

1234 # The row records the agent that ran; these say where it lives, so a 

1235 # project- or organisation-wide cap has traffic to count. 

1236 owner_project_id=agent.owner_project_id, 

1237 owner_organisation_id=agent.owner_organisation_id, 

1238 ai_model_id=answered_info.get("id") if answered_info else None, 

1239 input_tokens=in_tokens, 

1240 output_tokens=out_tokens, 

1241 model_info=answered_info, 

1242 latency_ms=invocation_latency_ms, 

1243 source_type=UsageEnum.Source.agent, 

1244 source_id=agent.id, 

1245 measured=used, 

1246 invocation_id=invocation_id, 

1247 ) 

1248 

1249 _status("Saving conversation…") 

1250 conversation = _persist_conversation( 

1251 db, 

1252 agent, 

1253 conversation, 

1254 request.prompt, 

1255 response, 

1256 sent_at, 

1257 in_tokens=in_tokens, 

1258 out_tokens=out_tokens, 

1259 user_id=user_id, 

1260 conversation_id=UUID(target_conversation_id) if not conversation else None, 

1261 trace=rule_trace or None, 

1262 agent_version=agent_version, 

1263 workspace=workspace, 

1264 user_meta=user_meta, 

1265 invocation_id=invocation_id, 

1266 model_name=answered_model.get("model_name") if answered_model else None, 

1267 lighter=( 

1268 lighter_service.answer_meta(used.answered_by) if answered_model else None 

1269 ), 

1270 cost_profile=setup.cost_profile, 

1271 cited_sources=cited_sources, 

1272 withheld=withheld.meta() if withheld is not None else None, 

1273 web_search=web_search, 

1274 # What the turn asked of the agent's knowledge, redacted as the 

1275 # request and answer were (the retrieval record). 

1276 knowledge_report=retrievals_service.prepared( 

1277 used.knowledge_report, 

1278 input_rules=input_rules, 

1279 output_rules=output_rules, 

1280 withheld=withheld is not None, 

1281 ), 

1282 ) 

1283 # Recorded after persistence so the flag can point at the conversation a 

1284 # reviewer needs to read, and so a turn that failed to persist leaves no 

1285 # flag behind pointing at nothing. Flags svc-ai raised come through 

1286 # `remote_rule_events` and land in the same queue — a reviewer should not 

1287 # have to know which service noticed. 

1288 review_service.record_flags( 

1289 db, 

1290 [*(remote_rule_events or []), *output_rule_events], 

1291 workspace=workspace, 

1292 owner_user_id=user_id, 

1293 response=response, 

1294 execution_type="agent", 

1295 conversation_id=conversation.id, 

1296 agent_id=agent.id, 

1297 ai_model_id=model_info.get("id") if model_info else None, 

1298 invocation_id=invocation_id, 

1299 ) 

1300 # The answer a withhold rule held, kept for review — not on the 

1301 # conversation, which stores the rule's message. 

1302 review_service.record_withheld( 

1303 db, 

1304 withheld, 

1305 workspace=workspace, 

1306 owner_user_id=user_id, 

1307 execution_type="agent", 

1308 conversation_id=conversation.id, 

1309 agent_id=agent.id, 

1310 ai_model_id=model_info.get("id") if model_info else None, 

1311 invocation_id=invocation_id, 

1312 ) 

1313 # …and point this turn's governance evaluations at the message they ran 

1314 # on. The ids exist only now: the policy rules ran before the prompt was 

1315 # sent and the audit rules before this was saved. 

1316 activity_service.link_invocation( 

1317 db, 

1318 invocation_id, 

1319 conversation_id=conversation.id, 

1320 message_id=latest_assistant_message_id(conversation), 

1321 ) 

1322 # The Tools rows recorded before the model, settled on what the turn's 

1323 # searches met. 

1324 activity_service.settle_tools(db, invocation_id, tools_settled) 

1325 db.commit() 

1326 

1327 return response, conversation.id, rule_trace 

1328 

1329 

1330def stored_web_search(db: Session, invocation_id: str | UUID | None) -> dict | None: 

1331 """What a turn's web searches came to, as its answer stores it 

1332 (``meta.web_search``), or None.""" 

1333 turn = _invocation_uuid(invocation_id) 

1334 if turn is None: 

1335 return None 

1336 message = ( 

1337 db.query(ChatMessage) 

1338 .filter( 

1339 ChatMessage.invocation_id == turn, 

1340 ChatMessage.role == MessageEnum.Role.ASSISTANT, 

1341 ) 

1342 .order_by(ChatMessage.sent_at.desc()) 

1343 .first() 

1344 ) 

1345 meta = getattr(message, "meta", None) 

1346 value = meta.get("web_search") if isinstance(meta, dict) else None 

1347 return value if isinstance(value, dict) else None