Coverage for app / router / app / agents / router.py: 92%

900 statements  

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

1import asyncio 

2import logging 

3from time import perf_counter 

4from typing import Literal, Optional 

5from uuid import UUID, uuid4 

6 

7from fastapi import ( 

8 APIRouter, 

9 Depends, 

10 HTTPException, 

11 WebSocket, 

12 WebSocketDisconnect, 

13 status, 

14) 

15from pydantic import BaseModel 

16from sqlalchemy.orm import Session 

17 

18from app.common import exceptions 

19from app.db.postgres.crud_schemas import Schema 

20from app.db.postgres.engine import SessionLocal 

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

22from app.db.postgres.models import ( 

23 Agent, 

24 AgentRepository, 

25 AgentSkillset, 

26 AgentToolkit, 

27 Conversation, 

28 CustomWorker, 

29 Knowledge, 

30 KnowledgeRepository, 

31 Rule, 

32 Skill, 

33 Skillset, 

34 Toolkit, 

35 User, 

36) 

37from app.dependency.base import get_db 

38from app.dependency.workspace import owner_for, request_workspace 

39from app.dependency.resource_access import ( 

40 verify_conversation_access, 

41 verify_owner_scope, 

42 verify_resource_access, 

43 verify_resource_read, 

44) 

45from app.dependency.user.context import get_current_user 

46from app.services import inheritance 

47from app.services import workspace as workspace_service 

48from app.router.app.agents import transformers as agent_transformers 

49from app.router.app.history.router import register_history_routes 

50from app.router.app.models.models import PromptResponse 

51from app.router.app.skills.router import RunFieldInfo 

52from app.services import ( 

53 ai_client, 

54 chat_commands, 

55 hitl, 

56 quality_check, 

57 rule_engine, 

58 uploads, 

59) 

60from app.services import agent_grants, agent_spec 

61from app.services.knowledge import built_in_crawls 

62from app.services.agent_grants import children_snapshot as _agent_children_snapshot 

63from app.services.agent_grants import record_grant_version as _record_grant_version 

64from app.services import attachments as attachments_service 

65from app.services import lighter_model as lighter_service 

66from app.services import native_sibling 

67from app.services.knowledge import retrievals as retrievals_service 

68from app.services import governance_activity as activity_service 

69from app.services import history as history_service 

70from app.services import mcp as mcp_service 

71from app.services import spend_limits 

72from app.services import review as review_service 

73from app.services import usage as usage_service 

74from app.services import turns, web_search_summary, withholding 

75from app.services.chat_socket import ChatSocket 

76from app.services.turns import STOPPED_TEXT, TurnStopped 

77from app.services.rules import scopes as rule_scopes 

78from app.util import cost_profiles, web_domains 

79from app.util.time import aware_utcnow 

80 

81logger = logging.getLogger(__name__) 

82 

83agent_router = APIRouter(prefix="/agents", tags=["App - Agents"]) 

84 

85 

86def _accessible_agent( 

87 agent_id: UUID, current_user: User, db: Session, *, read: bool = False 

88) -> Agent: 

89 """The agent, or 404 / 403 — the gate on every per-agent route. 

90 

91 Invoking an agent runs it over its knowledge, toolkits and memory, and a 

92 grant route changes what it can reach, so none of them may be keyed on a 

93 bare id. 

94 

95 ``read`` marks a route that only reads or invokes the agent, which admits 

96 CHAINR Bot; everything else — a grant, a revoke — refuses it, so the 

97 default stays closed. 

98 """ 

99 agent = db.get(Agent, agent_id) 

100 if not agent: 

101 raise exceptions.AgentNotFoundException 

102 if read: 

103 verify_resource_read(agent, current_user, db) 

104 else: 

105 verify_resource_access(agent, current_user, db) 

106 return agent 

107 

108 

109@agent_router.get("") 

110def agent_list( 

111 workspace: str | None = None, 

112 owner_organisation_id: UUID | None = None, 

113 owner_project_id: UUID | None = None, 

114 db: Session = Depends(get_db), 

115 current_user: User = Depends(get_current_user), 

116): 

117 """ 

118 List agents. ``workspace`` lists one workspace's 

119 (``app/services/workspace.py``), and naming nothing is Personal; the 

120 older owner_organisation_id / owner_project_id list exactly an org's or 

121 project's (membership verified). 

122 

123 A workspace's listing, and the personal one, also carry CHAINR Bot 

124 (``is_system``), first, so every picker that lists "my agents" offers it 

125 without a second call. 

126 """ 

127 

128 from app.dependency.resource_access import annotated, scoped, verify_list_scope 

129 

130 query = db.query(Agent) 

131 if not workspace and not owner_organisation_id and not owner_project_id: 

132 # No mixed listing any more: naming nothing is Personal. 

133 workspace = "personal" 

134 if workspace: 

135 where, ws = scoped( 

136 Agent, current_user, db, workspace=workspace, include_system=True 

137 ) 

138 return annotated( 

139 query.filter(where) 

140 .order_by(Agent.is_system.desc(), Agent.created_at.asc()) 

141 .all(), 

142 ws, 

143 ) 

144 if owner_organisation_id: 

145 verify_list_scope(owner_organisation_id, "organisation", current_user, db) 

146 query = query.filter(Agent.owner_organisation_id == owner_organisation_id) 

147 else: 

148 verify_list_scope(owner_project_id, "project", current_user, db) 

149 query = query.filter(Agent.owner_project_id == owner_project_id) 

150 return query.all() 

151 

152 

153class LighterModelPreview(BaseModel): 

154 """The lighter model a profile would have do an agent's lighter work 

155 (``services/lighter_model.py``), or why there is none.""" 

156 

157 model_id: Optional[str] = None 

158 model_name: Optional[str] = None 

159 display_name: Optional[str] = None 

160 #: Why there is none, in words; None when there is one. 

161 note: Optional[str] = None 

162 

163 

164class CostProfileInfo(BaseModel): 

165 """One cost profile an agent may run under (``app/util/cost_profiles.py``).""" 

166 

167 key: str 

168 label: str 

169 description: str 

170 #: Measured on the platform's gold datasets and found to answer as well 

171 #: as ``thorough``. One that is not is offered as such, never a default. 

172 measured: bool 

173 #: Whether a lighter model does some of the work (Economy). 

174 lighter_model: bool = False 

175 #: For ``?agent_id=``: which lighter model that agent would use here. 

176 lighter: Optional[LighterModelPreview] = None 

177 

178 

179# Declared before ``/{agent_id}``, which would otherwise take the path. 

180@agent_router.get("/cost-profiles", response_model=list[CostProfileInfo]) 

181def list_cost_profiles( 

182 agent_id: Optional[UUID] = None, 

183 db: Session = Depends(get_db), 

184 current_user: User = Depends(get_current_user), 

185): 

186 """The cost profiles an agent may run under: how much pipeline work each 

187 turn does, and whether the platform has measured it. With ``agent_id``, 

188 each profile that uses a lighter model says which one that agent would 

189 use in this workspace, or why none.""" 

190 rows = cost_profiles.catalogue() 

191 if agent_id is None: 

192 return rows 

193 agent = _accessible_agent(agent_id, current_user, db, read=True) 

194 try: 

195 model_info = agent_transformers._resolve_model(db, agent) 

196 except Exception: # noqa: BLE001 — a preview never fails the page 

197 model_info = None 

198 choice = lighter_service.for_turn( 

199 db, 

200 profile=cost_profiles.CostProfile.economy, 

201 model_info=model_info, 

202 ws=request_workspace(db, current_user), 

203 ) 

204 preview = ( 

205 LighterModelPreview( 

206 model_id=str(choice.model.get("id")), 

207 model_name=choice.model.get("model_name"), 

208 display_name=choice.model.get("display_name") 

209 or choice.model.get("model_name"), 

210 ) 

211 if choice.model is not None 

212 else LighterModelPreview(note=choice.text) 

213 ) 

214 return [ 

215 {**row, "lighter": preview if row.get("lighter_model") else None} 

216 for row in rows 

217 ] 

218 

219 

220@agent_router.get("/{agent_id}") 

221def agent_id( 

222 agent_id: UUID, 

223 db: Session = Depends(get_db), 

224 current_user: User = Depends(get_current_user), 

225): 

226 return _accessible_agent(agent_id, current_user, db, read=True) 

227 

228 

229@agent_router.post("/new", status_code=status.HTTP_201_CREATED) 

230def new_agent( 

231 agent_data: Schema.Agent.Create, 

232 db: Session = Depends(get_db), 

233 current_user: User = Depends(get_current_user), 

234): 

235 data = agent_data.model_dump() 

236 if not data.get("owner_organisation_id") and not data.get("owner_project_id"): 

237 # The workspace the request was made in (app/dependency/workspace.py). 

238 data.update(owner_for(db, current_user, model=Agent)) 

239 

240 agent = Agent(**data) 

241 verify_owner_scope(agent, current_user, db, model=Agent) 

242 try: 

243 db.add(agent) 

244 db.commit() 

245 db.refresh(agent) 

246 history_service.record_version( 

247 db, 

248 resource_type=HistoryEnum.ResourceType.agent, 

249 model=Agent, 

250 resource=agent, 

251 action=HistoryEnum.Action.created, 

252 actor=current_user, 

253 children_resolver=lambda: _agent_children_snapshot(db, agent.id), 

254 ) 

255 db.commit() 

256 return agent 

257 except Exception: 

258 db.rollback() 

259 logger.exception("Failed to create agent") 

260 raise 

261 

262 

263@agent_router.patch("/{agent_id}") 

264def update_agent( 

265 agent_id: UUID, 

266 body: Schema.Agent.Update, 

267 db: Session = Depends(get_db), 

268 current_user: User = Depends(get_current_user), 

269): 

270 agent = db.get(Agent, agent_id) 

271 if not agent: 

272 raise exceptions.AgentNotFoundException 

273 verify_resource_access(agent, current_user, db) 

274 for field, value in body.model_dump(exclude_none=True).items(): 

275 setattr(agent, field, value) 

276 history_service.record_version( 

277 db, 

278 resource_type=HistoryEnum.ResourceType.agent, 

279 model=Agent, 

280 resource=agent, 

281 action=HistoryEnum.Action.updated, 

282 actor=current_user, 

283 children_resolver=lambda: _agent_children_snapshot(db, agent.id), 

284 ) 

285 try: 

286 db.commit() 

287 db.refresh(agent) 

288 return agent 

289 except Exception as exc: 

290 db.rollback() 

291 from fastapi import HTTPException 

292 from sqlalchemy.exc import IntegrityError 

293 

294 if isinstance(exc, IntegrityError): 

295 raise HTTPException( 

296 status_code=status.HTTP_409_CONFLICT, 

297 detail="An agent with this name already exists for this owner.", 

298 ) from exc 

299 

300 logger.exception("Failed to update agent") 

301 raise 

302 

303 

304# Resource types the generative setup can create as dependents of an agent. 

305_GENERATED_CHILD_MODELS: list[tuple[str, type]] = [ 

306 ("skill", Skill), 

307 ("knowledge", Knowledge), 

308 ("repository", KnowledgeRepository), 

309 ("skillset", Skillset), 

310 ("toolkit", Toolkit), 

311 ("worker", CustomWorker), 

312 ("rule", Rule), 

313] 

314 

315 

316class GeneratedResourceRef(BaseModel): 

317 id: UUID 

318 name: str 

319 type: str 

320 

321 

322class GeneratedResourcesResponse(BaseModel): 

323 resources: list[GeneratedResourceRef] = [] 

324 total: int = 0 

325 

326 

327def _generated_children(db: Session, agent_id: UUID) -> list[tuple[str, object]]: 

328 """All rows the generative setup created alongside this agent.""" 

329 children: list[tuple[str, object]] = [] 

330 for type_name, model in _GENERATED_CHILD_MODELS: 

331 rows = db.query(model).filter(model.generated_by_agent_id == agent_id).all() 

332 children.extend((type_name, row) for row in rows) 

333 return children 

334 

335 

336@agent_router.get( 

337 "/{agent_id}/generated-resources", response_model=GeneratedResourcesResponse 

338) 

339def list_generated_resources( 

340 agent_id: UUID, 

341 db: Session = Depends(get_db), 

342 current_user: User = Depends(get_current_user), 

343): 

344 """List resources created by this agent's generative setup. 

345 

346 Used by the delete flow to offer cascading deletion of AI-generated 

347 child dependencies. 

348 """ 

349 agent = db.get(Agent, agent_id) 

350 if not agent: 

351 raise exceptions.AgentNotFoundException 

352 verify_resource_read(agent, current_user, db) 

353 refs = [ 

354 GeneratedResourceRef(id=row.id, name=row.name, type=type_name) 

355 for type_name, row in _generated_children(db, agent_id) 

356 ] 

357 return GeneratedResourcesResponse(resources=refs, total=len(refs)) 

358 

359 

360class ChatCommandForm(BaseModel): 

361 """The fields a target takes — for a skill, its standalone Run form's.""" 

362 

363 fields: list[RunFieldInfo] = [] 

364 #: Whether the free text after the command is required (a target with no 

365 #: fields) or optional additional instructions. 

366 request: Literal["required", "optional"] = "required" 

367 #: False when a worker's interface could not be looked up, so fields may 

368 #: be missing. 

369 complete: bool = True 

370 

371 

372class ChatCommandTarget(BaseModel): 

373 id: str 

374 slug: str 

375 name: str 

376 description: str = "" 

377 built_in: bool = False 

378 form: ChatCommandForm | None = None 

379 

380 

381class ChatCommandSpec(BaseModel): 

382 action: str 

383 kind: str 

384 label: str 

385 description: str 

386 request_hint: str 

387 request_required: bool = True 

388 usage: str 

389 targets: list[ChatCommandTarget] = [] 

390 

391 

392class ChatCommandCatalogue(BaseModel): 

393 commands: list[ChatCommandSpec] = [] 

394 

395 

396@agent_router.get("/{agent_id}/commands", response_model=ChatCommandCatalogue) 

397def agent_commands( 

398 agent_id: UUID, 

399 workspace: str | None = None, 

400 db: Session = Depends(get_db), 

401 current_user: User = Depends(get_current_user), 

402): 

403 """The chat commands this agent's chat offers. 

404 

405 Each comes with what it can target in ``workspace`` 

406 (``app/services/chat_commands.py``): the vocabulary fe-core's command 

407 palette completes a typed ``/`` from.""" 

408 agent = _accessible_agent(agent_id, current_user, db, read=True) 

409 ws = _chat_workspace(db, agent, workspace, current_user) 

410 ctx = chat_commands.CommandContext( 

411 db=db, user=current_user, agent=agent, workspace=ws 

412 ) 

413 return ChatCommandCatalogue(commands=chat_commands.catalogue(ctx)) 

414 

415 

416@agent_router.delete("/{agent_id}", status_code=status.HTTP_204_NO_CONTENT) 

417def delete_agent( 

418 agent_id: UUID, 

419 delete_generated: bool = False, 

420 db: Session = Depends(get_db), 

421 current_user: User = Depends(get_current_user), 

422): 

423 """Delete an agent and its assignments, conversations, and svc-ai memory. 

424 

425 With ``delete_generated=true``, resources created by this agent's 

426 generative setup (skills, knowledge bases, repositories, workers, rules) 

427 are deleted in the same transaction instead of being left orphaned. 

428 """ 

429 agent = db.get(Agent, agent_id) 

430 if not agent: 

431 raise exceptions.AgentNotFoundException 

432 verify_resource_access(agent, current_user, db) 

433 

434 worker_definitions: list[str] = [] 

435 if delete_generated: 

436 for type_name, row in _generated_children(db, agent_id): 

437 # Defence in depth: a child another principal owns is skipped, 

438 # never deleted through this cascade. 

439 try: 

440 verify_resource_access(row, current_user, db) 

441 except HTTPException: 

442 logger.warning( 

443 "Skipping generated %s %s during cascade delete of agent " 

444 "%s — current user has no access", 

445 type_name, 

446 row.id, 

447 agent_id, 

448 ) 

449 continue 

450 if type_name == "worker" and getattr(row, "definition_name", None): 

451 worker_definitions.append(row.definition_name) 

452 db.delete(row) 

453 

454 history_service.record_version( 

455 db, 

456 resource_type=HistoryEnum.ResourceType.agent, 

457 model=Agent, 

458 resource=agent, 

459 action=HistoryEnum.Action.deleted, 

460 actor=current_user, 

461 children_resolver=lambda: _agent_children_snapshot(db, agent.id), 

462 ) 

463 db.delete(agent) 

464 try: 

465 db.commit() 

466 except Exception: 

467 db.rollback() 

468 logger.exception("Failed to delete agent") 

469 raise 

470 

471 # Best-effort memory wipe, once the agent is gone — it used to run first, 

472 # so a deletion that then failed had still wiped everyone's memory of 

473 # the agent. Stale memory of a deleted agent is unreachable and must 

474 # not fail the deletion. 

475 from app.services import memory_lifecycle 

476 

477 memory_lifecycle.forget_agents([str(agent_id)]) 

478 

479 # Best-effort deregistration of deleted workers — a dangling svc-ai 

480 # definition is harmless and must not block deletion (same contract as 

481 # the standalone worker delete endpoint). 

482 for definition_name in worker_definitions: 

483 try: 

484 ai_client.delete_agent_definition(definition_name) 

485 except ai_client.AIServiceError as exc: 

486 logger.warning( 

487 "Could not deregister worker definition %s from svc-ai: %s", 

488 definition_name, 

489 exc, 

490 ) 

491 

492 

493@agent_router.websocket("/{agent_id}/prompt/ws") 

494async def agent_prompt_ws( 

495 agent_id: UUID, 

496 websocket: WebSocket, 

497 db: Session = Depends(get_db), 

498 current_user: User = Depends(get_current_user), 

499): 

500 """ 

501 WebSocket endpoint for agent prompts with true token-by-token streaming. 

502 

503 Protocol: 

504 Client → Server: 

505 {"prompt": "...", "conversation_id": "..." | null} 

506 

507 A prompt that opens with a chat command (``/execute skill 

508 research-brief …``, ``app/services/chat_commands.py``) runs that 

509 workflow on the rest of the text; a command that cannot run is one 

510 ``error`` frame with ``code: "command"`` and ``suggestions``. 

511 

512 Server → Client (ordered): 

513 {"type": "turn", "conversation_id": "...", "turn_id": "..."} 

514 {"type": "status", "message": "..."} 

515 {"type": "token", "token": "..."} 

516 {"type": "response", "response": "...", "conversation_id": "..."} 

517 {"type": "error", "message": "..."} 

518 

519 Client → Server, while the turn runs: 

520 {"type": "stop"} — Stop: end the turn where it is 

521 {"type": "hitl_resume"} — a pause's answer 

522 

523 The turn does not depend on the socket (``app/services/chat_socket.py``): 

524 a client that closes the page leaves it running, and it is stored as it 

525 would have been, so they come back to the answer instead of a paid-for 

526 half-run. Only ``stop`` ends it early; a pause nobody can now answer is 

527 recorded as unanswered. 

528 

529 All execution paths (skill, agent-with-tools, plain model) use the same 

530 three async phases: 

531 1. setup (thread: resolve model + load DB state) 

532 2. stream (async: httpx.AsyncClient SSE → WS frames via astream_execute) 

533 3. persist (thread: save conversation) 

534 """ 

535 await websocket.accept() 

536 # Every frame goes through this: a send to a client that has gone is 

537 # dropped rather than raised into the turn. 

538 sock = ChatSocket(websocket) 

539 

540 # Pre-declared so the failure handlers below can attempt a best-effort 

541 # persist even when the exception happens before these are normally 

542 # assigned further down — referencing an unset name would otherwise 

543 # raise NameError and silently drop the failure handling itself. 

544 prompt: str | None = None 

545 existing_conv_id: UUID | None = None 

546 # The conversation this turn is stored under — for a new chat, minted 

547 # once the setup has run (see below). 

548 turn_conv_id: UUID | None = None 

549 agent: Agent | None = None 

550 session_id: str | None = None 

551 partial_response: list[str] = [] 

552 # Whether an Output rule that can withhold the answer governs the turn: 

553 # then nothing of the answer is shown or kept before the Output rules 

554 # have run on it (``app/services/withholding.py``). Set before the 

555 # stream starts. 

556 hold = {"on": False} 

557 persisted = False 

558 # Pre-declared for the same reason as the rest: the error handler records 

559 # the failed invocation on the usage ledger, and a failure during setup 

560 # happens before the model has been resolved. 

561 model_info: dict | None = None 

562 # What the turn's svc-ai calls cost, from the stream's terminal frames — 

563 # opened when the first stream starts — and how many streams it started 

564 # (the first, and one per resume after a pause). A failed or stopped 

565 # turn is ledgered with what it spent: those calls were paid for. 

566 used: ai_client.UsageCapture | None = None 

567 stream_legs = 0 

568 # The most the turn may spend: what is left of the tightest budget that 

569 # let it start (``app/services/spend_limits.py``). svc-ai stops it there. 

570 turn_limit: rule_engine.SpendLimit | None = None 

571 # The web sources it may use, as its Tools rules set them. 

572 turn_web: web_domains.WebPolicy | None = None 

573 # The workspace the chat happens in, once the agent is known. 

574 chat_ws = None 

575 # The chat command this turn runs, once parsed; its record goes on the 

576 # user's message whatever the turn's outcome — redacted with the prompt 

577 # once the policy rules have run, as typed before that. 

578 command: chat_commands.ParsedCommand | None = None 

579 command_meta: dict | None = None 

580 # The documents this message attaches (``app/services/attachments.py``), 

581 # and what the user's message keeps beside its words: the command it 

582 # ran and those documents, by id — on every path the turn is stored by. 

583 this_turn: list[attachments_service.TurnDocument] = [] 

584 user_meta: dict | None = None 

585 # Its form's values as the skill is given them (redacted the same way). 

586 command_inputs: dict = {} 

587 # This turn in the registry of running turns (app/services/turns.py): 

588 # how a page that comes back finds it, and how Stop from one reaches it. 

589 turn: turns.RunningTurn | None = None 

590 # One id for everything this turn writes — both phases' governance 

591 # activity, the ledger row, the messages, any flags, and svc-ai's traces 

592 # (``ai_client.use_invocation`` below) — so the activity log groups the 

593 # policy rules that ran on the prompt with the audit rules that ran on 

594 # the response, and the answer's decision record joins. Minted before 

595 # anything can fail, so a failed turn is stored under it too. 

596 invocation_id = rule_engine.new_invocation_id() 

597 user_id = str(current_user.id) 

598 loop = asyncio.get_running_loop() 

599 

600 def _stop_context() -> dict: 

601 """What a budget stopping this turn is recorded against.""" 

602 return { 

603 "execution_type": "agent", 

604 "user_id": user_id, 

605 "agent_id": str(agent_id), 

606 "scope_type": "agent", 

607 "scope_id": str(agent_id), 

608 rule_engine.WORKSPACE_CONTEXT_KEY: chat_ws.key if chat_ws else None, 

609 rule_engine.INVOCATION_CONTEXT_KEY: invocation_id, 

610 } 

611 

612 def _kept_text(default: str) -> str: 

613 """What a turn stopped or failed part-way keeps: what it had written, 

614 unless a withhold rule governs it — then nothing it wrote was checked, 

615 and a neutral line is kept instead.""" 

616 if hold["on"]: 

617 return withholding.HELD_TEXT 

618 return "".join(partial_response) or default 

619 

620 async def _best_effort_persist( 

621 turn_status: MessageEnum.Status, 

622 message: str, 

623 rule_name: str | None = None, 

624 block: rule_engine.BlockLike | None = None, 

625 stopped: bool = False, 

626 reconcile: bool = False, 

627 ) -> UUID | None: 

628 """Persist whatever we have of a turn that failed before Phase 3 ran. 

629 

630 No-op when there's no prompt to attach it to (failure happened before 

631 the client even sent one) or a turn was already persisted. Returns the 

632 conversation id on success so callers can report it to the client. 

633 

634 ``reconcile`` is for a turn that ended without svc-ai's terminal frame 

635 — Stop, or a failure on svc-core's side of the stream — so the capture 

636 lacks the leg that was running: its spend is read from svc-ai's trace 

637 of the turn instead (``ai_client.reconcile_turn_usage``). 

638 """ 

639 if persisted or not (prompt or this_turn) or agent is None: 

640 return None 

641 

642 def _measured() -> ai_client.UsageCapture | None: 

643 if not reconcile: 

644 return used 

645 return ai_client.reconcile_turn_usage( 

646 used, invocation_id, user_id, legs=stream_legs 

647 ) 

648 

649 def _persist() -> UUID: 

650 thread_db = SessionLocal() 

651 try: 

652 thread_agent = thread_db.get(Agent, agent_id) 

653 existing_conv = ( 

654 thread_db.get(Conversation, existing_conv_id) 

655 if existing_conv_id 

656 else None 

657 ) 

658 measured = _measured() 

659 if turn_status == MessageEnum.Status.BLOCKED: 

660 # A block costs nothing in the common case — the rules 

661 # that refused it are recorded, one `governance_events` 

662 # row each, and no ledger row is written. One that svc-ai 

663 # enforced after the run had already made calls was paid 

664 # for all the same, and the ledger is where money is. 

665 if measured is not None and measured.measured: 

666 agent_transformers._record_failed_invocation( 

667 thread_db, 

668 thread_agent, 

669 user_id=user_id, 

670 model_info=model_info, 

671 latency_ms=None, 

672 measured=measured, 

673 workspace=chat_ws, 

674 invocation_id=invocation_id, 

675 ) 

676 conv = agent_transformers.persist_blocked_turn( 

677 thread_db, 

678 thread_agent, 

679 existing_conv, 

680 prompt, 

681 aware_utcnow(), 

682 rule_name or "unknown", 

683 message, 

684 user_id=user_id, 

685 conversation_id=turn_conv_id, 

686 block=block, 

687 workspace=chat_ws, 

688 user_meta=user_meta, 

689 invocation_id=invocation_id, 

690 ) 

691 else: 

692 # Same transaction as the turn it documents, with what 

693 # its calls cost before it failed or was stopped. 

694 agent_transformers._record_failed_invocation( 

695 thread_db, 

696 thread_agent, 

697 user_id=user_id, 

698 model_info=model_info, 

699 latency_ms=None, 

700 measured=measured, 

701 workspace=chat_ws, 

702 invocation_id=invocation_id, 

703 ) 

704 conv = agent_transformers.persist_error_turn( 

705 thread_db, 

706 thread_agent, 

707 existing_conv, 

708 prompt, 

709 aware_utcnow(), 

710 message, 

711 user_id=user_id, 

712 conversation_id=turn_conv_id, 

713 workspace=chat_ws, 

714 user_meta=user_meta, 

715 stopped=stopped, 

716 invocation_id=invocation_id, 

717 ) 

718 return conv.id 

719 finally: 

720 thread_db.close() 

721 

722 try: 

723 return await loop.run_in_executor(None, _persist) 

724 except Exception: 

725 logger.exception( 

726 "Failed to persist best-effort %s turn for agent %s", 

727 turn_status.value, 

728 agent_id, 

729 ) 

730 return None 

731 

732 try: 

733 data = await websocket.receive_json() 

734 # From here the client may press Stop, or answer a pause. 

735 sock.listen() 

736 prompt = data.get("prompt", "").strip() 

737 conversation_id_str = data.get("conversation_id") 

738 conversation_id = UUID(conversation_id_str) if conversation_id_str else None 

739 try: 

740 verify_conversation_access(conversation_id, current_user, db) 

741 except HTTPException: 

742 await sock.send({"type": "error", "message": "Conversation not found"}) 

743 return 

744 # Stable thread_id for LangGraph checkpointing — ties all turns in the 

745 # same conversation to the same checkpoint thread so HITL resume works. 

746 session_id = conversation_id_str or str(uuid4()) 

747 raw_file_ids: list[str] = data.get("file_ids") or [] 

748 output_format: str | None = data.get("output_format") or None 

749 output_schema: str | None = data.get("output_schema") or None 

750 model_override_id: str | None = data.get("model_override_id") or None 

751 disable_skills: bool = bool(data.get("disable_skills", False)) 

752 # A command's form values, beside its text (app/services/chat_commands.py). 

753 raw_command_inputs = data.get("command_inputs") 

754 if not isinstance(raw_command_inputs, dict): 

755 raw_command_inputs = None 

756 

757 # Checked before ``agent`` is assigned: the failure handlers persist a 

758 # turn against it, and must not write into an agent the caller cannot 

759 # reach. 

760 try: 

761 agent = _accessible_agent(agent_id, current_user, db, read=True) 

762 except HTTPException: 

763 await sock.send({"type": "error", "message": "Agent not found"}) 

764 return 

765 try: 

766 chat_ws = _chat_workspace(db, agent, data.get("workspace"), current_user) 

767 except HTTPException as exc: 

768 await sock.send({"type": "error", "message": str(exc.detail)}) 

769 return 

770 workspace_key = chat_ws.key 

771 # The socket names its workspace in a frame, not on the URL the 

772 # request carries: every svc-ai call this turn makes is told, and 

773 # told which turn it is part of. 

774 ai_client.use_workspace(workspace_key) 

775 ai_client.use_invocation(invocation_id) 

776 

777 # A chat command (``/execute skill research-brief …``) chooses how the 

778 # turn runs, and the text after it is the request. Parsed before 

779 # anything is prepended to the prompt, against what this workspace 

780 # offers — a hand-typed command is checked like a picked one. 

781 try: 

782 command = chat_commands.parse( 

783 prompt, 

784 chat_commands.CommandContext( 

785 db=db, user=current_user, agent=agent, workspace=chat_ws 

786 ), 

787 inputs=raw_command_inputs, 

788 ) 

789 except chat_commands.CommandError as exc: 

790 await sock.send( 

791 { 

792 "type": "error", 

793 "message": exc.message, 

794 "code": "command", 

795 "suggestions": exc.suggestions, 

796 "fields": exc.fields, 

797 } 

798 ) 

799 return 

800 if command is not None: 

801 # The turn runs on what a standalone run of the target would be 

802 # given: the instructions and the form's values (``task``). 

803 prompt = command.task 

804 command_meta = command.meta() 

805 command_inputs = dict(command.inputs) 

806 

807 # The documents this message attaches, from the chat's own workspace 

808 # library only: another workspace's id is left out, and one of its 

809 # own whose text is not read refuses the turn. They travel beside 

810 # the words, never pasted into them (``app/services/attachments.py``). 

811 try: 

812 this_turn = attachments_service.turn_attachments(db, raw_file_ids, chat_ws) 

813 except ( 

814 uploads.DocumentsNotReady, 

815 attachments_service.TooManyDocuments, 

816 ) as exc: 

817 await sock.send( 

818 {"type": "error", "message": exc.message, "code": "documents"} 

819 ) 

820 return 

821 user_meta = attachments_service.message_meta(command_meta, this_turn) 

822 

823 if not prompt and not this_turn: 

824 await sock.send({"type": "error", "message": "No prompt provided"}) 

825 return 

826 

827 await sock.send({"type": "status", "message": f"Starting {agent.name}…"}) 

828 

829 # ── Phase 1 — setup in thread (DB reads + model resolution) ─────────── 

830 await sock.send({"type": "status", "message": "Resolving model…"}) 

831 

832 def _setup(): 

833 thread_db = SessionLocal() 

834 try: 

835 thread_agent = thread_db.get(Agent, agent_id) 

836 model_info = agent_transformers._resolve_model(thread_db, thread_agent) 

837 if model_override_id: 

838 try: 

839 override_info = ai_client.get_model(UUID(model_override_id)) 

840 model_info = override_info 

841 logger.info( 

842 "Agent %s: model overridden to %s (%s)", 

843 agent_id, 

844 model_override_id, 

845 override_info.get("model_name", "?"), 

846 ) 

847 except Exception as exc: 

848 logger.warning( 

849 "Agent %s: model override %s failed (%s) — using agent default", 

850 agent_id, 

851 model_override_id, 

852 exc, 

853 ) 

854 conv, history = agent_transformers._load_conversation( 

855 thread_db, conversation_id 

856 ) 

857 # What the agent brings to the turn — the reading every path 

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

859 setup = agent_spec.load(thread_db, thread_agent) 

860 # Captured alongside the configuration it describes, not at 

861 # persistence: an edit landing mid-stream must not make the 

862 # record claim a revision that never ran this prompt. 

863 agent_version = history_service.current_version( 

864 thread_db, HistoryEnum.ResourceType.agent, agent_id 

865 ) 

866 # What the conversation's earlier messages attached: the 

867 # agent may use any document of the conversation. 

868 earlier = attachments_service.earlier_attachments( 

869 thread_db, conv, chat_ws, exclude=[d.id for d in this_turn] 

870 ) 

871 return ( 

872 model_info, 

873 (conv.id if conv else None), 

874 history, 

875 setup, 

876 agent_version, 

877 earlier, 

878 ) 

879 finally: 

880 thread_db.close() 

881 

882 ( 

883 model_info, 

884 existing_conv_id, 

885 history, 

886 setup, 

887 agent_version, 

888 earlier_docs, 

889 ) = await loop.run_in_executor(None, _setup) 

890 # What the turn carries: this message's documents, then earlier 

891 # ones, within the wire's limits. 

892 turn_docs = attachments_service.for_turn(this_turn, earlier_docs) 

893 agent_skills = list(setup.skills) 

894 if command is not None: 

895 # The command chose the skill: it runs whether or not the agent 

896 # holds it, and whether or not the chat's skill graph is on. 

897 agent_skills = [command.dispatch.skill] 

898 disable_skills = False 

899 # The skill this turn answers through, if any — a governed resource 

900 # the turn touches, so a rule scoped to it applies. 

901 routed_skill = agent_skills[0] if agent_skills and not disable_skills else None 

902 # A new chat's id is chosen now, not when the turn is persisted: 

903 # svc-ai stamps it on the turn's trace — every model call, with its 

904 # provider, model and tokens — and a first turn traced without one was 

905 # never linked to its conversation, so per-model and per-provider 

906 # token figures, counted from those traces, left it out. The batch 

907 # route does the same (`agent_transformers.prompt_agent`). 

908 turn_conv_id = existing_conv_id or uuid4() 

909 try: 

910 turn = turns.registry.start( 

911 kind="agent", 

912 user_id=user_id, 

913 target_id=str(agent_id), 

914 conversation_id=str(turn_conv_id), 

915 workspace=workspace_key, 

916 ) 

917 except turns.TurnConflict as exc: 

918 # Its history would not hold the answer still being written. 

919 await sock.send({"type": "error", "message": str(exc), "code": "busy"}) 

920 return 

921 turn.on_stop(sock.stop_soon) 

922 # The conversation the turn is stored under, before anything else: a 

923 # new chat's page has no other way to know it until the answer, and 

924 # needs it to keep this turn's stream to its own conversation when 

925 # the person looks at another one meanwhile. 

926 await sock.send( 

927 { 

928 "type": "turn", 

929 "conversation_id": str(turn_conv_id), 

930 "turn_id": turn.id, 

931 } 

932 ) 

933 

934 provider = model_info["provider"]["name"] 

935 model_name = model_info["model_name"] 

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

937 if not model_override_id and ( 

938 note := agent_transformers.model_substitution(agent, model_info) 

939 ): 

940 await sock.send({"type": "status", "message": note}) 

941 

942 # Every governed resource this turn touches: the agent, the model it 

943 # resolved to, and the project/organisation that owns the agent. A 

944 # rule written against any one of them governs this turn, which is 

945 # what stops a model-scoped policy quietly lapsing the moment its 

946 # model is reached through an agent rather than prompted directly. 

947 scope_chain = rule_scopes.serialize( 

948 rule_scopes.invocation_chain( 

949 agent=agent, 

950 skill=routed_skill, 

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

952 ) 

953 ) 

954 

955 # ── Rule enforcement: policy (input) ───────────────────────────────── 

956 # The rules read this message's documents with its words, as they 

957 # always have (``attachments.governed_text``); what they redact is 

958 # then redacted in the words and in every document. 

959 governed_prompt = attachments_service.governed_text(prompt, this_turn) 

960 

961 def _check_input_rules(): 

962 thread_db = SessionLocal() 

963 try: 

964 input_ctx = { 

965 "prompt": governed_prompt, 

966 "execution_type": "agent", 

967 "user_id": user_id, 

968 "agent_id": str(agent_id), 

969 "agent_name": agent.name, 

970 "model_name": model_name, 

971 "provider": provider, 

972 "scope_type": "agent", 

973 "scope_id": str(agent_id), 

974 rule_engine.SCOPES_CONTEXT_KEY: scope_chain, 

975 rule_engine.WORKSPACE_CONTEXT_KEY: workspace_key, 

976 rule_engine.INVOCATION_CONTEXT_KEY: invocation_id, 

977 } 

978 result = rule_engine.evaluate_input( 

979 thread_db, governed_prompt, input_ctx, user_id 

980 ) 

981 # The engine appended this evaluation to the governance 

982 # activity log; this session is about to be closed, so commit 

983 # it here rather than letting the record go with it. 

984 activity_service.commit(thread_db) 

985 return result 

986 except rule_engine.RuleBlock: 

987 # A refusal is the event the log least tolerates losing, and 

988 # it is the one the ordinary commit above never reaches. 

989 activity_service.commit(thread_db) 

990 raise 

991 finally: 

992 thread_db.close() 

993 

994 try: 

995 input_rules = await loop.run_in_executor(None, _check_input_rules) 

996 governed_prompt, input_rule_events = input_rules 

997 prompt = input_rules.redact(prompt) if this_turn else governed_prompt 

998 turn_docs = attachments_service.redacted(turn_docs, input_rules) 

999 turn_limit = getattr(input_rules, "spend_limit", None) 

1000 turn_web = getattr(input_rules, "web_policy", None) 

1001 ai_client.use_turn_governance(input_rules) 

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

1003 # meets the prompt's redaction: earlier turns are stored as they 

1004 # were, which is unredacted for any turn before the rule existed. 

1005 history = input_rules.redact_history(history) 

1006 if command is not None: 

1007 # The form's values travel with the prompt to the same model, 

1008 # so they meet the same redaction; so does their record. 

1009 command_inputs = input_rules.redact(command_inputs) 

1010 command_meta = input_rules.redact(command_meta) 

1011 user_meta = attachments_service.message_meta(command_meta, turn_docs) 

1012 # What a page that comes back shows while the answer is written: 

1013 # the message as it will be stored. 

1014 turn.prompt = prompt 

1015 turn.meta = user_meta 

1016 except rule_engine.RuleBlock as exc: 

1017 

1018 def _persist_blocked(): 

1019 thread_db = SessionLocal() 

1020 try: 

1021 thread_agent = thread_db.get(Agent, agent_id) 

1022 existing_conv = ( 

1023 thread_db.get(Conversation, existing_conv_id) 

1024 if existing_conv_id 

1025 else None 

1026 ) 

1027 conv = agent_transformers.persist_blocked_turn( 

1028 thread_db, 

1029 thread_agent, 

1030 existing_conv, 

1031 prompt, 

1032 aware_utcnow(), 

1033 exc.rule_name, # noqa: F821 

1034 exc.message, # noqa: F821 

1035 user_id=user_id, 

1036 conversation_id=turn_conv_id, 

1037 block=exc, # noqa: F821 

1038 workspace=chat_ws, 

1039 user_meta=user_meta, 

1040 invocation_id=invocation_id, 

1041 ) 

1042 # A refused turn is persisted too, and is the one a reader 

1043 # most wants to open from the activity log. 

1044 activity_service.link_invocation( 

1045 thread_db, 

1046 invocation_id, 

1047 conversation_id=conv.id, 

1048 message_id=agent_transformers.latest_assistant_message_id(conv), 

1049 ) 

1050 thread_db.commit() 

1051 return conv.id 

1052 finally: 

1053 thread_db.close() 

1054 

1055 blocked_conv_id = await loop.run_in_executor(None, _persist_blocked) 

1056 persisted = True 

1057 await sock.send( 

1058 { 

1059 "type": "error", 

1060 "message": exc.message, 

1061 "rule": exc.rule_name, 

1062 "conversation_id": str(blocked_conv_id), 

1063 } 

1064 ) 

1065 return 

1066 

1067 # Forward the applicable policy/audit rules to svc-ai so they are also 

1068 # enforced inside its execution engines (skill graphs, workers, 

1069 # streaming) — not just here at the svc-core edge. 

1070 def _serialize_rules(): 

1071 thread_db = SessionLocal() 

1072 try: 

1073 return rule_engine.serialize_rules( 

1074 thread_db, 

1075 user_id, 

1076 scopes=scope_chain, 

1077 workspace=workspace_key, 

1078 ) 

1079 finally: 

1080 thread_db.close() 

1081 

1082 rule_specs = await loop.run_in_executor(None, _serialize_rules) 

1083 

1084 # ── Phase 2 — stream via svc-ai (async, event loop) ─────────────────── 

1085 trace_events: list[dict] = [] 

1086 stream_segments: list[dict] = [] 

1087 # Mutable container shared between the closures and the resume loop. 

1088 # Set to the hitl_interrupt payload when the graph pauses for a 

1089 # person; reset to None once their answer is sent. 

1090 hitl_state: dict[str, object] = { 

1091 "interrupt": None, 

1092 "pause": None, 

1093 "pause_frame": None, 

1094 "spec": None, 

1095 "type": None, 

1096 } 

1097 

1098 async def _on_token(token: str) -> None: 

1099 # Buffered so a mid-stream failure (disconnect, provider error) can 

1100 # still persist whatever was generated so far instead of losing it. 

1101 partial_response.append(token) 

1102 if hold["on"]: 

1103 # Not shown before the Output rules have run on it. 

1104 return 

1105 await sock.send({"type": "token", "token": token}) 

1106 

1107 async def _on_status(msg: str) -> None: 

1108 await sock.send({"type": "status", "message": msg}) 

1109 

1110 async def _on_citations(citations: list) -> None: 

1111 if hold["on"]: 

1112 return 

1113 await sock.send({"type": "citations", "citations": citations}) 

1114 

1115 # What the answer cites, as svc-ai's final ``citations`` frame sent it: 

1116 # stored on the answer once the audit rules have redacted it. None 

1117 # until svc-ai sends a list (one that predates it never does). 

1118 answer_sources: dict[str, list | None] = {"cited": None} 

1119 

1120 async def _on_sources(citations: list) -> None: 

1121 # The answer's own sources, once it is written: they replace the 

1122 # passages streamed as they were retrieved (``final``). Sent as 

1123 # svc-ai wrote them — before the audit rules run; what is stored 

1124 # is redacted (``stored_cited_sources``). 

1125 answer_sources["cited"] = citations 

1126 if hold["on"]: 

1127 # Sent once the answer has been checked, as stored. 

1128 return 

1129 await sock.send( 

1130 {"type": "citations", "citations": citations, "final": True} 

1131 ) 

1132 

1133 async def _on_trace(event: dict) -> None: 

1134 if event.get("type") == "hitl_pause": 

1135 # Held until the pause it describes has been audited, so a 

1136 # redacted question is never streamed or stored unredacted. 

1137 hitl_state["pause_frame"] = event 

1138 return 

1139 if event.get("type") == ai_client.TOKEN_RESET: 

1140 # The node's text so far was not answer: neither kept for a 

1141 # turn that fails or stops, nor in the stored trace. 

1142 partial_response.clear() 

1143 await sock.send(event) 

1144 return 

1145 trace_events.append(event) 

1146 if event.get("type") == "node_end": 

1147 # What a failed turn keeps is the node that was writing, as 

1148 # fe-core's preview and its Stop do. Every node's text used to 

1149 # pile up here — a skill's plan, its research notes, the brief 

1150 # and each revision — and a turn that failed late was stored 

1151 # as all of them run together. 

1152 partial_response.clear() 

1153 await sock.send(event) 

1154 

1155 # Surface policy-rule enforcement as trace frames so it is visible in 

1156 # the live chat trace and persisted for the Activity page — every 

1157 # applicable rule with its outcome, not only the ones that acted. 

1158 # Emitted before svc-ai streams so ordering is chronological. 

1159 input_rule_frames = rule_engine.build_rule_trace( 

1160 input_rule_events, "input", input_rules.evaluations 

1161 ) 

1162 for _frame in input_rule_frames: 

1163 await _on_trace(_frame) 

1164 

1165 async def _on_ai_trace(event: dict) -> None: 

1166 # svc-ai's trace frames — while a withhold rule governs the turn, 

1167 # held to what describes the run, not what it wrote: shown and 

1168 # stored alike. svc-core's own rule frames go to ``_on_trace``. 

1169 if hold["on"]: 

1170 event = withholding.held_frame(event) 

1171 if event is None: 

1172 return 

1173 await _on_trace(event) 

1174 

1175 async def _on_worker_token(slug: str, token: str) -> None: 

1176 if hold["on"]: 

1177 return 

1178 await sock.send( 

1179 { 

1180 "type": "worker_token", 

1181 "worker_agent_slug": slug, 

1182 "token": token, 

1183 } 

1184 ) 

1185 

1186 # Every pause of this turn and how it ended — persisted on the 

1187 # assistant message, the audit record of who decided what. 

1188 hitl_exchanges: list[dict] = [] 

1189 # Audit events raised over what pauses showed (a flag_for_review on 

1190 # a question lands in the review queue with the turn's other flags). 

1191 pause_rule_events: list[dict] = [] 

1192 # What withhold rules held at pauses, for their review items. 

1193 withheld_pauses: list[rule_engine.Withheld] = [] 

1194 

1195 def _governance_context() -> dict: 

1196 return { 

1197 "prompt": governed_prompt, 

1198 "execution_type": "agent", 

1199 "user_id": user_id, 

1200 "agent_id": str(agent_id), 

1201 "agent_name": agent.name, 

1202 "model_name": model_name, 

1203 "provider": provider, 

1204 "scope_type": "agent", 

1205 "scope_id": str(agent_id), 

1206 rule_engine.SCOPES_CONTEXT_KEY: scope_chain, 

1207 rule_engine.WORKSPACE_CONTEXT_KEY: workspace_key, 

1208 rule_engine.INVOCATION_CONTEXT_KEY: invocation_id, 

1209 } 

1210 

1211 def _audit_pause(pause: dict) -> hitl.AuditedPause: 

1212 thread_db = SessionLocal() 

1213 try: 

1214 return hitl.audit_pause( 

1215 thread_db, pause, _governance_context(), user_id 

1216 ) 

1217 finally: 

1218 thread_db.close() 

1219 

1220 async def _on_hitl_interrupt(data: dict) -> None: 

1221 pause = hitl.normalise_interrupt(data) 

1222 audited, events, redactor, withheld_pause = await loop.run_in_executor( 

1223 None, _audit_pause, pause 

1224 ) 

1225 pause_rule_events.extend(events) 

1226 frame = dict(hitl_state.get("pause_frame") or {}) 

1227 hitl_state["pause_frame"] = None 

1228 if withheld_pause is not None: 

1229 # A withhold rule held what the pause shows: the person sees 

1230 # its message, and what it held goes to review with the turn. 

1231 withheld_pauses.append(withheld_pause) 

1232 data = hitl.withhold_shown( 

1233 data, pause.get("kind"), withheld_pause.message 

1234 ) 

1235 frame = ( 

1236 hitl.withhold_shown( 

1237 frame, pause.get("kind"), withheld_pause.message 

1238 ) 

1239 if frame 

1240 else frame 

1241 ) 

1242 redactor = None 

1243 if redactor is not None: 

1244 # A redact_pii rule ran: what the person sees, what the 

1245 # trace keeps and what the answer is validated against are 

1246 # all the redacted questions — redacted as that rule chose. 

1247 data = { 

1248 **data, 

1249 **redactor.redact_values( 

1250 { 

1251 k: data[k] 

1252 for k in ( 

1253 "title", 

1254 "intro", 

1255 "reason", 

1256 "questions", 

1257 "task", 

1258 "output", 

1259 ) 

1260 if k in data 

1261 } 

1262 ), 

1263 } 

1264 frame = redactor.redact_values(frame) if frame else frame 

1265 hitl_state["interrupt"] = data 

1266 hitl_state["pause"] = audited 

1267 if frame: 

1268 frame.setdefault("node_id", audited.get("node_id") or "") 

1269 trace_events.append(frame) 

1270 await sock.send(frame) 

1271 await sock.send({"type": "hitl_interrupt", **data}) 

1272 

1273 skill = routed_skill 

1274 graph_definition = None 

1275 if skill is not None: 

1276 if len(agent_skills) > 1: 

1277 logger.warning( 

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

1279 "composition is not yet supported, the remaining skills " 

1280 "are ignored: %s", 

1281 agent_id, 

1282 len(agent_skills), 

1283 skill.name, 

1284 skill.id, 

1285 [s.name for s in agent_skills[1:]], 

1286 ) 

1287 await _on_status(f"Running {agent.name} via skill '{skill.name}'…") 

1288 

1289 # As every other path runs a skill: MCP ids resolved, and a node 

1290 # pin this deployment cannot run dropped with a note. Its tool 

1291 # nodes read what the agent's own workspace has. 

1292 def _resolve_graph() -> tuple[dict, list[str]]: 

1293 thread_db = SessionLocal() 

1294 try: 

1295 return agent_spec.resolve_skill(thread_db, setup, skill) 

1296 finally: 

1297 thread_db.close() 

1298 

1299 graph_definition, graph_notes = await loop.run_in_executor( 

1300 None, _resolve_graph 

1301 ) 

1302 for note in graph_notes: 

1303 await _on_status(note) 

1304 else: 

1305 # Built-in tools are bound by svc-ai and not forwarded; what an 

1306 # agent adds on top is its knowledge and its MCP servers. 

1307 configured_label = ", ".join( 

1308 [kb["name"] for kb in setup.knowledge_bases] 

1309 + [s["name"] for s in setup.mcp_servers] 

1310 ) 

1311 await _on_status( 

1312 f"Running {agent.name} with {configured_label}…" 

1313 if configured_label 

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

1315 ) 

1316 

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

1318 # and a native sibling for the structured steps 

1319 # (``services/native_sibling.py``): neither for a turn whose model a 

1320 # person chose. 

1321 def _choose_models(): 

1322 if model_override_id: 

1323 return None, None 

1324 thread_db = SessionLocal() 

1325 try: 

1326 ws = workspace_service.from_key(thread_db, workspace_key) 

1327 chosen = lighter_service.for_turn( 

1328 thread_db, 

1329 profile=setup.cost_profile, 

1330 model_info=model_info, 

1331 ws=ws, 

1332 ) 

1333 return chosen, native_sibling.for_turn( 

1334 thread_db, 

1335 model_info=model_info, 

1336 lighter=chosen, 

1337 ws=ws, 

1338 ) 

1339 finally: 

1340 thread_db.close() 

1341 

1342 lighter, structured = await loop.run_in_executor(None, _choose_models) 

1343 agent_request = agent_spec.build( 

1344 setup, 

1345 model_info={"provider": {"name": provider}, "model_name": model_name}, 

1346 config=config, 

1347 skill=skill, 

1348 graph_definition=graph_definition, 

1349 # A person is on the other end to answer a question first. 

1350 interactive=True, 

1351 output_format=output_format, 

1352 output_schema=output_schema, 

1353 # A model chosen for this turn answers every node. 

1354 model_override=bool(model_override_id), 

1355 # A command's form values seed the graph state, as a standalone 

1356 # run's do. 

1357 inputs=command_inputs, 

1358 lighter=lighter, 

1359 structured=structured, 

1360 ) 

1361 hitl_state["type"] = agent_request.type 

1362 hitl_state["spec"] = agent_request.spec 

1363 payload = agent_request.payload( 

1364 prompt=prompt, 

1365 messages=history, 

1366 user_id=user_id, 

1367 session_id=session_id, 

1368 conversation_id=str(turn_conv_id), 

1369 external_agent_id=str(agent_id), 

1370 attachments=attachments_service.wire(turn_docs), 

1371 ) 

1372 

1373 payload["rules"] = rule_specs 

1374 

1375 # While an Output rule that can withhold the answer governs the turn, 

1376 # nothing of it is shown before the Output rules have run on it 

1377 # (``app/services/withholding.py``). 

1378 def _may_withhold() -> bool: 

1379 thread_db = SessionLocal() 

1380 try: 

1381 return rule_engine.may_withhold( 

1382 thread_db, _governance_context(), user_id 

1383 ) 

1384 finally: 

1385 thread_db.close() 

1386 

1387 hold["on"] = await loop.run_in_executor(None, _may_withhold) 

1388 if hold["on"]: 

1389 await _on_status(withholding.HELD_STATUS) 

1390 

1391 # Timed around the stream for the ledger's latency figure. For a 

1392 # stream this is time-to-complete, not time-to-first-token: the 

1393 # figure that compares consistently across streaming and 

1394 # non-streaming paths. 

1395 invocation_started = perf_counter() 

1396 # Every model call of the turn, across the stream and any resumes after 

1397 # a pause — what the ledger row below records and prices. 

1398 used = ai_client.open_capture() 

1399 stream_legs += 1 

1400 ( 

1401 response, 

1402 in_tokens, 

1403 out_tokens, 

1404 stream_segments, 

1405 eval_result, 

1406 remote_rule_events, 

1407 ) = await sock.run( 

1408 ai_client.astream_execute( 

1409 payload=payload, 

1410 on_token=_on_token, 

1411 on_status=_on_status, 

1412 on_citations=_on_citations, 

1413 on_sources=_on_sources, 

1414 on_trace=_on_ai_trace, 

1415 on_worker_token=_on_worker_token, 

1416 on_hitl_interrupt=_on_hitl_interrupt, 

1417 ) 

1418 ) 

1419 

1420 # Captured before the HITL resume loop, which waits on a *person*. Time 

1421 # spent waiting for human approval is not the model being slow, and 

1422 # folding it in would make any agent that asks for approval look like 

1423 # the slowest model on the platform. 

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

1425 

1426 # ── HITL resume loop ─────────────────────────────────────────────────── 

1427 # When the graph pauses for human approval, the stream returns early with 

1428 # an empty response. Wait for the frontend to send a hitl_resume message, 

1429 # then stream the resumed graph execution. 

1430 answer_block: rule_engine.RuleBlock | None = None 

1431 while hitl_state["interrupt"] is not None: 

1432 ctx = hitl_state["interrupt"] 

1433 pause = dict(hitl_state["pause"] or hitl.normalise_interrupt(ctx)) 

1434 hitl_state["interrupt"] = None 

1435 hitl_state["pause"] = None 

1436 thread_id: str = ctx.get("thread_id", "") if isinstance(ctx, dict) else "" 

1437 

1438 # Wait for an answer that fits the question. An invalid one is 

1439 # sent back with what is wrong and the pause stays open — the 

1440 # form is the client's, so it is never trusted to have checked. 

1441 cleaned: dict | None = None 

1442 closed_reason = "" 

1443 turn.status = "awaiting_input" 

1444 while cleaned is None: 

1445 resume_data = await sock.next_message() 

1446 if resume_data is None: 

1447 closed_reason = ( 

1448 "Stopped before the question was answered." 

1449 if sock.stopped 

1450 else "The chat closed before the question was answered." 

1451 ) 

1452 break 

1453 if resume_data.get("type") != "hitl_resume": 

1454 closed_reason = "The client sent something other than an answer." 

1455 break 

1456 try: 

1457 cleaned = hitl.validate_response( 

1458 pause, 

1459 { 

1460 "answers": resume_data.get("answers") or {}, 

1461 "approved": resume_data.get("approved", True), 

1462 "feedback": resume_data.get("feedback", ""), 

1463 }, 

1464 ) 

1465 except hitl.HitlResponseInvalid as exc: 

1466 await sock.send( 

1467 { 

1468 "type": "hitl_invalid", 

1469 "message": exc.message, 

1470 "fields": exc.fields, 

1471 } 

1472 ) 

1473 

1474 turn.status = "running" 

1475 if cleaned is None: 

1476 # Nobody will answer: record that, and free the checkpoint 

1477 # svc-ai holds rather than leave it until the process ends. 

1478 abandoned = hitl.abandoned(pause, reason=closed_reason) 

1479 hitl_exchanges.append(abandoned) 

1480 # Closed in the trace too, so no view shows this pause as 

1481 # still waiting. Appended, not sent: nobody is listening. 

1482 trace_events.append(hitl.resume_trace_frame(abandoned)) 

1483 if thread_id: 

1484 await loop.run_in_executor( 

1485 None, ai_client.discard_paused_run, thread_id 

1486 ) 

1487 if sock.stopped: 

1488 raise TurnStopped 

1489 break 

1490 

1491 def _govern_answer(_pause=pause, _cleaned=cleaned): 

1492 thread_db = SessionLocal() 

1493 try: 

1494 return hitl.govern_answer( 

1495 thread_db, _pause, _cleaned, _governance_context(), user_id 

1496 ) 

1497 finally: 

1498 thread_db.close() 

1499 

1500 try: 

1501 governed = await loop.run_in_executor(None, _govern_answer) 

1502 forwarded, redacted = governed 

1503 except rule_engine.RuleBlock as exc: 

1504 answer_block = exc 

1505 record = hitl.exchange(pause, cleaned, actor_id=user_id) 

1506 record["outcome"] = "blocked" 

1507 record["blocked_by"] = exc.rule_name 

1508 hitl_exchanges.append(record) 

1509 await _on_trace(hitl.resume_trace_frame(record)) 

1510 if thread_id: 

1511 await loop.run_in_executor( 

1512 None, ai_client.discard_paused_run, thread_id 

1513 ) 

1514 break 

1515 

1516 record = hitl.exchange( 

1517 pause, forwarded, actor_id=user_id, redacted=redacted 

1518 ) 

1519 hitl_exchanges.append(record) 

1520 await _on_trace(hitl.resume_trace_frame(record)) 

1521 

1522 # What the turn may spend from here: the ledger does not hold 

1523 # what it spent before the pause until it ends. 

1524 resume_limit = spend_limits.for_resume( 

1525 turn_limit, getattr(governed, "spend_limit", None), used 

1526 ) 

1527 if spend_limits.exhausted(resume_limit): 

1528 if thread_id: 

1529 await loop.run_in_executor( 

1530 None, ai_client.discard_paused_run, thread_id 

1531 ) 

1532 raise spend_limits.exhausted_error(resume_limit) 

1533 ai_client.use_turn_governance( 

1534 ai_client.TurnGovernance( 

1535 resume_limit, 

1536 spend_limits.web_for_resume( 

1537 turn_web, getattr(governed, "web_policy", None) 

1538 ), 

1539 ) 

1540 ) 

1541 

1542 is_clarification = pause.get("kind") == hitl.CLARIFICATION 

1543 approved = bool(forwarded.get("approved", True)) 

1544 await _on_status( 

1545 "Continuing with your answers…" 

1546 if is_clarification and forwarded.get("answers") 

1547 else "Continuing without answers…" 

1548 if is_clarification 

1549 else ("Resuming execution…" if approved else "Incorporating feedback…") 

1550 ) 

1551 

1552 stream_legs += 1 

1553 ( 

1554 response, 

1555 in_tokens, 

1556 out_tokens, 

1557 stream_segments, 

1558 eval_result, 

1559 resumed_rule_events, 

1560 ) = await sock.run( 

1561 ai_client.astream_execute_resume( 

1562 thread_id=thread_id, 

1563 exec_type=str(hitl_state["type"] or "skill"), 

1564 spec=dict(hitl_state["spec"] or {}), 

1565 user_id=user_id, 

1566 approved=approved, 

1567 feedback=str(forwarded.get("feedback") or ""), 

1568 answers=forwarded.get("answers") or {}, 

1569 rules=rule_specs, 

1570 on_token=_on_token, 

1571 on_status=_on_status, 

1572 on_citations=_on_citations, 

1573 on_sources=_on_sources, 

1574 on_trace=_on_ai_trace, 

1575 on_worker_token=_on_worker_token, 

1576 on_hitl_interrupt=_on_hitl_interrupt, # support re-interrupt 

1577 conversation_id=payload.get("conversation_id"), 

1578 ) 

1579 ) 

1580 # Accumulate rather than replace: rules enforced on the leg that 

1581 # was interrupted still fired, and an audit trail that forgets 

1582 # them because a human was asked to approve something is wrong. 

1583 remote_rule_events = [*remote_rule_events, *resumed_rule_events] 

1584 

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

1586 def _check_output_rules(): 

1587 thread_db = SessionLocal() 

1588 try: 

1589 output_ctx = { 

1590 "prompt": governed_prompt, 

1591 "execution_type": "agent", 

1592 "user_id": user_id, 

1593 "agent_id": str(agent_id), 

1594 "agent_name": agent.name, 

1595 "model_name": model_name, 

1596 "provider": provider, 

1597 "scope_type": "agent", 

1598 "scope_id": str(agent_id), 

1599 rule_engine.SCOPES_CONTEXT_KEY: scope_chain, 

1600 rule_engine.WORKSPACE_CONTEXT_KEY: workspace_key, 

1601 rule_engine.INVOCATION_CONTEXT_KEY: invocation_id, 

1602 # The ledger's figures for this turn: the model's time 

1603 # (not the time a person took to answer it) and the cost 

1604 # of every call, resumes included. 

1605 **usage_service.audit_figures( 

1606 latency_ms=invocation_latency_ms, 

1607 measured=used, 

1608 input_tokens=in_tokens, 

1609 output_tokens=out_tokens, 

1610 model_info=model_info, 

1611 ), 

1612 # What the quality check concluded, so a rule can send an 

1613 # answer it could not stand behind to a person. 

1614 **quality_check.audit_figures(eval_result), 

1615 } 

1616 result = rule_engine.evaluate_output( 

1617 thread_db, response, output_ctx, user_id 

1618 ) 

1619 activity_service.commit(thread_db) 

1620 return result 

1621 finally: 

1622 thread_db.close() 

1623 

1624 # Rules svc-ai enforced during the stream arrive on its terminal 

1625 # ``done`` frame. They are the same rules svc-core evaluated, so they 

1626 # are folded into the existing nodes rather than given their own: the 

1627 # policy node already sent is corrected in place, and the audit node 

1628 # below carries both services' view of each rule. 

1629 remote_input_events = [ 

1630 e for e in remote_rule_events or [] if e.get("phase") == "input" 

1631 ] 

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

1633 # summary of them, and its Tools rules settled on them — "applied" 

1634 # only where one changed a search (``web_search_summary``). The 

1635 # policy node already sent is corrected in place. 

1636 web_reports = list(used.web_searches) 

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

1638 tools_settled = web_search_summary.settled_changes( 

1639 input_rules.evaluations, settled_input 

1640 ) 

1641 input_rules.evaluations = settled_input 

1642 web_search = web_search_summary.summarise( 

1643 web_reports, settled_input, held=hold["on"] 

1644 ) 

1645 if remote_input_events or tools_settled: 

1646 build_input = ( 

1647 rule_engine.build_rule_trace_update 

1648 if input_rule_frames 

1649 else rule_engine.build_rule_trace 

1650 ) 

1651 for _frame in build_input( 

1652 input_rule_events, 

1653 "input", 

1654 input_rules.evaluations, 

1655 remote_input_events, 

1656 ): 

1657 await _on_trace(_frame) 

1658 

1659 # The answer's sources as it stores them; none for a blocked turn, 

1660 # whose reply is the rule's message, nor for a withheld one. 

1661 cited_sources: list[dict] | None = None 

1662 # The answer an Output rule withheld, if one did. 

1663 withheld: rule_engine.Withheld | None = None 

1664 if answer_block is not None: 

1665 # A policy rule refused what the person answered: the turn ends 

1666 # there, recorded as blocked like a refused prompt — but through 

1667 # the ordinary persist below, so the model calls made before the 

1668 # pause still reach the usage ledger. 

1669 response = answer_block.message 

1670 output_rule_events = [] 

1671 for _frame in rule_engine.build_block_trace_from_exc(answer_block): 

1672 await _on_trace(_frame) 

1673 else: 

1674 output_rules = await loop.run_in_executor(None, _check_output_rules) 

1675 response, output_rule_events = output_rules 

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

1677 if withheld is None: 

1678 cited_sources = agent_transformers.stored_cited_sources( 

1679 answer_sources["cited"], output_rules 

1680 ) 

1681 if hold["on"] and isinstance(answer_sources["cited"], list): 

1682 # Checked: the answer's sources, through the turn's 

1683 # redaction, as they were held back. 

1684 await sock.send( 

1685 { 

1686 "type": "citations", 

1687 "citations": output_rules.redact(answer_sources["cited"]), 

1688 "final": True, 

1689 } 

1690 ) 

1691 for _frame in rule_engine.build_rule_trace( 

1692 output_rule_events, 

1693 "output", 

1694 output_rules.evaluations, 

1695 [e for e in remote_rule_events or [] if e.get("phase") != "input"], 

1696 ): 

1697 await _on_trace(_frame) 

1698 

1699 # ── Phase 3 — persist conversation in thread ─────────────────────────── 

1700 await sock.send({"type": "status", "message": "Saving conversation…"}) 

1701 sent_at = aware_utcnow() 

1702 

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

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

1705 answered_model = lighter_service.answered( 

1706 agent_request.lighter_model, used.answered_by 

1707 ) 

1708 answered_info = answered_model or model_info 

1709 

1710 def _persist(): 

1711 thread_db = SessionLocal() 

1712 try: 

1713 thread_agent = thread_db.get(Agent, agent_id) 

1714 existing_conv = ( 

1715 thread_db.get(Conversation, existing_conv_id) 

1716 if existing_conv_id 

1717 else None 

1718 ) 

1719 # Same transaction as the turn it documents, so a rolled-back 

1720 # stream cannot leave a phantom invocation on the ledger that 

1721 # rate limits and cost caps would count. 

1722 usage_service.record_usage( 

1723 thread_db, 

1724 owner_user_id=user_id, 

1725 execution_type="agent", 

1726 scope_type="agent", 

1727 scope_id=str(agent_id), 

1728 # Stamped so a project- or organisation-wide cap counts 

1729 # this turn: the row records the agent that ran, never 

1730 # where it lives. 

1731 owner_project_id=agent.owner_project_id, 

1732 owner_organisation_id=agent.owner_organisation_id, 

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

1734 input_tokens=in_tokens, 

1735 output_tokens=out_tokens, 

1736 model_info=answered_info, 

1737 latency_ms=invocation_latency_ms, 

1738 source_type=UsageEnum.Source.agent, 

1739 source_id=agent_id, 

1740 measured=used, 

1741 workspace=chat_ws, 

1742 invocation_id=invocation_id, 

1743 ) 

1744 conv = agent_transformers._persist_conversation( 

1745 thread_db, 

1746 thread_agent, 

1747 existing_conv, 

1748 prompt, 

1749 response, 

1750 sent_at, 

1751 in_tokens=in_tokens, 

1752 out_tokens=out_tokens, 

1753 user_id=user_id, 

1754 trace=trace_events or None, 

1755 # Held, a worker's text and the quality check's critique 

1756 # were never checked: neither is kept. 

1757 segments=None if hold["on"] else (stream_segments or None), 

1758 output_format=output_format, 

1759 output_schema=output_schema, 

1760 model_name=( 

1761 answered_model.get("model_name") 

1762 if answered_model 

1763 else model_name 

1764 ), 

1765 provider=provider, 

1766 eval_result=( 

1767 withholding.checked_verdict(eval_result) 

1768 if hold["on"] 

1769 else eval_result 

1770 ) 

1771 or None, 

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

1773 agent_version=agent_version, 

1774 hitl=hitl_exchanges or None, 

1775 workspace=chat_ws, 

1776 conversation_id=turn_conv_id, 

1777 user_meta=user_meta, 

1778 invocation_id=invocation_id, 

1779 lighter=( 

1780 lighter_service.answer_meta(used.answered_by) 

1781 if answered_model 

1782 else None 

1783 ), 

1784 cost_profile=setup.cost_profile, 

1785 cited_sources=cited_sources, 

1786 web_search=web_search, 

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

1788 # as the request and answer were; none of the person's 

1789 # words where a withhold rule held something back. 

1790 knowledge_report=retrievals_service.prepared( 

1791 used.knowledge_report, 

1792 input_rules=input_rules, 

1793 output_rules=output_rules if answer_block is None else None, 

1794 withheld=withheld is not None or bool(withheld_pauses), 

1795 ), 

1796 **( 

1797 { 

1798 "status": MessageEnum.Status.BLOCKED, 

1799 "rule_name": answer_block.rule_name, 

1800 } 

1801 if answer_block is not None 

1802 else {} 

1803 ), 

1804 ) 

1805 # Inside the same session and transaction as the turn, so a 

1806 # flag cannot survive a persist that rolled back. Flags svc-ai 

1807 # raised arrive on `remote_rule_events` and land in the same 

1808 # queue as the ones enforced here. 

1809 review_service.record_flags( 

1810 thread_db, 

1811 [ 

1812 *(remote_rule_events or []), 

1813 *pause_rule_events, 

1814 *output_rule_events, 

1815 ], 

1816 owner_user_id=user_id, 

1817 response=response, 

1818 execution_type="agent", 

1819 conversation_id=conv.id, 

1820 agent_id=agent_id, 

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

1822 workspace=chat_ws, 

1823 invocation_id=invocation_id, 

1824 ) 

1825 # What withhold rules held — at a pause, or the answer — kept 

1826 # for review, never on the conversation. 

1827 for held in [*withheld_pauses, *([withheld] if withheld else [])]: 

1828 review_service.record_withheld( 

1829 thread_db, 

1830 held, 

1831 owner_user_id=user_id, 

1832 execution_type="agent", 

1833 conversation_id=conv.id, 

1834 agent_id=agent_id, 

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

1836 workspace=chat_ws, 

1837 invocation_id=invocation_id, 

1838 ) 

1839 # Point this turn's governance evaluations at the message they 

1840 # ran on — the ids exist only now, and both phases were 

1841 # recorded in earlier sessions of their own. 

1842 message_id = agent_transformers.latest_assistant_message_id(conv) 

1843 activity_service.link_invocation( 

1844 thread_db, 

1845 invocation_id, 

1846 conversation_id=conv.id, 

1847 message_id=message_id, 

1848 ) 

1849 # The Tools rows recorded before the model, settled on what 

1850 # the turn's searches met. 

1851 activity_service.settle_tools(thread_db, invocation_id, tools_settled) 

1852 thread_db.commit() 

1853 return ( 

1854 conv.id, 

1855 message_id, 

1856 usage_service.turn_cost_fields(thread_db, invocation_id), 

1857 ) 

1858 finally: 

1859 thread_db.close() 

1860 

1861 ( 

1862 conversation_id_result, 

1863 message_id_result, 

1864 turn_cost, 

1865 ) = await loop.run_in_executor(None, _persist) 

1866 persisted = True 

1867 

1868 if answer_block is not None: 

1869 await sock.send( 

1870 { 

1871 "type": "error", 

1872 "message": answer_block.message, 

1873 "rule": answer_block.rule_name, 

1874 "conversation_id": str(conversation_id_result), 

1875 } 

1876 ) 

1877 return 

1878 

1879 await sock.send( 

1880 { 

1881 "type": "response", 

1882 "response": response, 

1883 "conversation_id": str(conversation_id_result), 

1884 # The stored reply's id: what a document in it is 

1885 # downloaded by, and what a deep link to it names. 

1886 "message_id": str(message_id_result) if message_id_result else None, 

1887 # The turn's id: what "Why did it do this?" opens. 

1888 "invocation_id": invocation_id, 

1889 # What the quality check concluded, as stored on the answer — 

1890 # the badge a live answer shows, as a reloaded one does. 

1891 "eval_outcome": (eval_result or {}).get("outcome"), 

1892 "eval_score": (eval_result or {}).get("score"), 

1893 # What the turn cost, read back from the ledger: the figure 

1894 # the answer shows once the conversation is reloaded. 

1895 **turn_cost, 

1896 "segments": [] if hold["on"] else stream_segments, 

1897 "model_name": model_name, 

1898 "provider": provider, 

1899 # An answer a rule withheld: ``response`` is its message. 

1900 **({"withheld": withheld.meta()} if withheld is not None else {}), 

1901 # What the turn's web searches came to, as stored on the 

1902 # answer (``meta.web_search``). 

1903 **({"web_search": web_search} if web_search else {}), 

1904 } 

1905 ) 

1906 

1907 except WebSocketDisconnect: 

1908 # Only the opening frame is read outside the socket wrapper, so the 

1909 # client left before it sent a prompt: there is no turn to keep. 

1910 logger.info("Client left agent %s's chat before sending a prompt", agent_id) 

1911 except TurnStopped: 

1912 # The person pressed Stop. What the turn had written so far is kept, 

1913 # as the chat showed it when they stopped it. 

1914 logger.info("Agent %s WS prompt stopped by the person", agent_id) 

1915 await _best_effort_persist( 

1916 MessageEnum.Status.ERROR, 

1917 _kept_text(STOPPED_TEXT), 

1918 stopped=True, 

1919 # Stop cancels the stream before its terminal frame, so what the 

1920 # running leg spent is read from svc-ai's trace. 

1921 reconcile=True, 

1922 ) 

1923 except ai_client.ModelRefusedError as exc: 

1924 # svc-ai could not use the model (no route on this backend, model 

1925 # access, credentials, quota, the spending ceiling): its message says 

1926 # what to fix, and is written to be shown. "Processing failed" said 

1927 # nothing, and an empty answer less. 

1928 logger.warning("Agent %s WS prompt refused by svc-ai (%s)", agent_id, exc.code) 

1929 refused_conv_id = await _best_effort_persist( 

1930 MessageEnum.Status.ERROR, exc.user_message 

1931 ) 

1932 if isinstance(exc, ai_client.SpendLimitReached): 

1933 # A budget stopped it part-way: on the record beside the row 

1934 # that let it start. 

1935 await loop.run_in_executor( 

1936 None, 

1937 spend_limits.record_stop, 

1938 exc, 

1939 _stop_context(), 

1940 user_id, 

1941 ) 

1942 await sock.send( 

1943 { 

1944 "type": "error", 

1945 "message": exc.user_message, 

1946 "code": exc.code, 

1947 **( 

1948 {"conversation_id": str(refused_conv_id)} if refused_conv_id else {} 

1949 ), 

1950 } 

1951 ) 

1952 except ai_client.RuleBlockedError as exc: 

1953 # A policy rule enforced inside svc-ai blocked the request — surface 

1954 # the rule's block message rather than a generic processing error. 

1955 logger.info("Agent %s WS prompt blocked by rule %r", agent_id, exc.rule) 

1956 blocked_conv_id = await _best_effort_persist( 

1957 MessageEnum.Status.BLOCKED, exc.message, rule_name=exc.rule, block=exc 

1958 ) 

1959 await sock.send( 

1960 { 

1961 "type": "error", 

1962 "message": exc.message, 

1963 "rule": exc.rule, 

1964 **( 

1965 {"conversation_id": str(blocked_conv_id)} if blocked_conv_id else {} 

1966 ), 

1967 } 

1968 ) 

1969 except Exception: 

1970 logger.exception("Error in agent WS prompt for agent %s", agent_id) 

1971 error_conv_id = await _best_effort_persist( 

1972 MessageEnum.Status.ERROR, 

1973 _kept_text("Processing failed"), 

1974 # Failed on this side of the stream, possibly mid-leg: svc-ai's 

1975 # trace says what the leg spent. 

1976 reconcile=True, 

1977 ) 

1978 await sock.send( 

1979 { 

1980 "type": "error", 

1981 "message": "Processing failed", 

1982 **({"conversation_id": str(error_conv_id)} if error_conv_id else {}), 

1983 } 

1984 ) 

1985 finally: 

1986 # Only now, with the turn stored: a page that sees it gone reads the 

1987 # conversation and finds the answer there. 

1988 if turn is not None: 

1989 turns.registry.finish(turn) 

1990 await sock.close() 

1991 

1992 

1993def _chat_workspace(db: Session, agent: Agent, requested: str | None, user: User): 

1994 """The workspace a chat with ``agent`` happens in 

1995 (``app/services/workspace.py``): the one the client is working in, when 

1996 the agent is in it — its own, inherited, or a built-in — else the 

1997 agent's own, or the user's personal one for a built-in agent. Its rules 

1998 govern the turn and its ledger counts it. 403/404 for a workspace the 

1999 user isn't in; 422 for one the agent isn't in.""" 

2000 if requested: 

2001 ws = workspace_service.resolve(db, requested, user) 

2002 if getattr(agent, "is_system", False) is True or inheritance.visible( 

2003 db, agent, ws 

2004 ): 

2005 return ws 

2006 raise HTTPException( 

2007 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

2008 detail="This agent isn't in that workspace.", 

2009 ) 

2010 home = workspace_service.home_of(db, agent) 

2011 if home is not None: 

2012 return home 

2013 return workspace_service.resolve(db, workspace_service.PERSONAL, user) 

2014 

2015 

2016@agent_router.post("/{agent_id}/prompt", response_model=PromptResponse) 

2017def agent_id_prompt( 

2018 agent_id: UUID, 

2019 request: Schema.Agent.Prompt, 

2020 workspace: str | None = None, 

2021 db: Session = Depends(get_db), 

2022 current_user: User = Depends(get_current_user), 

2023): 

2024 """One turn with the agent, governed by the rules of ``workspace`` — the 

2025 one the caller is working in, which must hold the agent — or, with 

2026 none, the agent's own.""" 

2027 from fastapi import HTTPException 

2028 from fastapi import status as http_status 

2029 

2030 agent = _accessible_agent(agent_id, current_user, db, read=True) 

2031 verify_conversation_access(request.conversation_id, current_user, db) 

2032 chat_ws = _chat_workspace(db, agent, workspace, current_user) 

2033 ai_client.use_workspace(chat_ws.key) 

2034 

2035 # The same chat commands as the WebSocket route: the text after one is 

2036 # the request, and a command that cannot run is a 422 saying why. 

2037 try: 

2038 command = chat_commands.parse( 

2039 request.prompt, 

2040 chat_commands.CommandContext( 

2041 db=db, user=current_user, agent=agent, workspace=chat_ws 

2042 ), 

2043 inputs=request.command_inputs, 

2044 ) 

2045 except chat_commands.CommandError as exc: 

2046 raise HTTPException( 

2047 status_code=http_status.HTTP_422_UNPROCESSABLE_ENTITY, 

2048 detail={ 

2049 "message": exc.message, 

2050 "suggestions": exc.suggestions, 

2051 "fields": exc.fields, 

2052 }, 

2053 ) from exc 

2054 if command is not None: 

2055 request = request.model_copy(update={"prompt": command.task}) 

2056 

2057 # The documents this message attaches, from the chat's own workspace: 

2058 # beside the words, never pasted into them (``app/services/attachments.py``). 

2059 try: 

2060 this_turn = attachments_service.turn_attachments(db, request.file_ids, chat_ws) 

2061 except uploads.DocumentsNotReady as exc: 

2062 raise HTTPException( 

2063 status_code=http_status.HTTP_409_CONFLICT, detail=exc.message 

2064 ) from exc 

2065 except attachments_service.TooManyDocuments as exc: 

2066 raise HTTPException( 

2067 status_code=http_status.HTTP_422_UNPROCESSABLE_ENTITY, detail=exc.message 

2068 ) from exc 

2069 if not request.prompt.strip() and not this_turn: 

2070 raise HTTPException( 

2071 status_code=http_status.HTTP_422_UNPROCESSABLE_ENTITY, 

2072 detail="No prompt provided", 

2073 ) 

2074 # What the rules read: this message's documents with its words, as they 

2075 # always have. 

2076 governed_prompt = attachments_service.governed_text(request.prompt, this_turn) 

2077 

2078 user_id = str(current_user.id) 

2079 # The turn's id: both rule phases, the ledger row, the messages, any 

2080 # flags and svc-ai's traces carry it (the answer's decision record). 

2081 invocation_id = rule_engine.new_invocation_id() 

2082 ai_client.use_invocation(invocation_id) 

2083 

2084 # As on the socket: the agent's model, resolved (an unavailable one falls 

2085 # back to the default), before the policy rules, so they govern the model 

2086 # that will answer. ``prompt_agent`` runs the turn on it. 

2087 model_info = agent_transformers._resolve_model(db, agent) 

2088 scope_chain = rule_scopes.serialize( 

2089 rule_scopes.invocation_chain( 

2090 agent=agent, 

2091 skill=command.dispatch.skill if command is not None else None, 

2092 model_id=model_info.get("id"), 

2093 ) 

2094 ) 

2095 

2096 # ── Rule enforcement: policy (input) ───────────────────────────────────── 

2097 input_ctx: dict = { 

2098 "prompt": governed_prompt, 

2099 "execution_type": "agent", 

2100 "user_id": user_id, 

2101 "agent_id": str(agent_id), 

2102 "agent_name": agent.name, 

2103 **rule_engine.model_fields(model_info), 

2104 "scope_type": "agent", 

2105 "scope_id": str(agent_id), 

2106 # Every governed resource the turn touches, its model the one that 

2107 # will answer. 

2108 rule_engine.SCOPES_CONTEXT_KEY: scope_chain, 

2109 rule_engine.WORKSPACE_CONTEXT_KEY: chat_ws.key, 

2110 # Handed to prompt_agent below, which evaluates this turn's audit 

2111 # rules — the two phases group in the activity log by sharing it. 

2112 rule_engine.INVOCATION_CONTEXT_KEY: invocation_id, 

2113 } 

2114 try: 

2115 input_rules = rule_engine.evaluate_input( 

2116 db, governed_prompt, input_ctx, user_id 

2117 ) 

2118 filtered_prompt, _ = input_rules 

2119 except rule_engine.RuleBlock as exc: 

2120 sent_at = aware_utcnow() 

2121 conversation, _ = agent_transformers._load_conversation( 

2122 db, request.conversation_id 

2123 ) 

2124 blocked_conv = agent_transformers.persist_blocked_turn( 

2125 db, 

2126 agent, 

2127 conversation, 

2128 request.prompt, 

2129 sent_at, 

2130 exc.rule_name, 

2131 exc.message, 

2132 user_id=user_id, 

2133 conversation_id=(request.conversation_id if not conversation else None), 

2134 block=exc, 

2135 workspace=chat_ws, 

2136 user_meta=attachments_service.message_meta( 

2137 command.meta() if command is not None else None, this_turn 

2138 ), 

2139 invocation_id=invocation_id, 

2140 ) 

2141 activity_service.link_invocation( 

2142 db, 

2143 invocation_id, 

2144 conversation_id=getattr(blocked_conv, "id", None), 

2145 message_id=agent_transformers.latest_assistant_message_id(blocked_conv), 

2146 ) 

2147 db.commit() 

2148 raise HTTPException( 

2149 status_code=http_status.HTTP_403_FORBIDDEN, 

2150 detail={"rule": exc.rule_name, "message": exc.message}, 

2151 ) 

2152 # With documents, the pass read them too: the words meet its redaction 

2153 # on their own (the documents do in ``prompt_agent``). 

2154 if this_turn: 

2155 filtered_prompt = input_rules.redact(request.prompt) 

2156 if filtered_prompt != request.prompt: 

2157 request = request.model_copy(update={"prompt": filtered_prompt}) 

2158 

2159 # The policy pass is handed on so the persisted trace carries both 

2160 # phases, merged with what svc-ai enforced of the same rules — and the 

2161 # most the turn may spend, where svc-ai stops it. 

2162 try: 

2163 response, conversation_id, rule_trace = agent_transformers.prompt_agent( 

2164 db=db, 

2165 agent=agent, 

2166 request=request, 

2167 user_id=user_id, 

2168 invocation_id=invocation_id, 

2169 input_rules=input_rules, 

2170 workspace=chat_ws, 

2171 command=command, 

2172 model_info=model_info, 

2173 attachments=this_turn, 

2174 ) 

2175 except ai_client.ModelRefusedError as exc: 

2176 # Stored with its message by ``prompt_agent``: no route for the 

2177 # model, credentials, quota, the spending ceiling — or a budget that 

2178 # stopped the turn part-way. Said here as model chat says it. 

2179 raise HTTPException( 

2180 status_code=http_status.HTTP_502_BAD_GATEWAY, detail=exc.user_message 

2181 ) from exc 

2182 

2183 return PromptResponse( 

2184 response=response, 

2185 conversation_id=conversation_id, 

2186 trace=rule_trace or None, 

2187 invocation_id=invocation_id, 

2188 web_search=agent_transformers.stored_web_search(db, invocation_id), 

2189 **usage_service.turn_cost_fields(db, invocation_id), 

2190 ) 

2191 

2192 

2193# --------------------------------------------------------------------------- 

2194# Agent effective tools (tool-based agents) 

2195# --------------------------------------------------------------------------- 

2196 

2197 

2198@agent_router.get("/{agent_id}/effective-tools") 

2199def get_agent_effective_tools( 

2200 agent_id: UUID, 

2201 db: Session = Depends(get_db), 

2202 current_user: User = Depends(get_current_user), 

2203): 

2204 """Return the tool set available to this agent at runtime. 

2205 

2206 Every agent gets svc-ai's **general** built-ins — they are platform 

2207 capabilities, not grants, so this is the same list for every agent and is 

2208 read from the registry rather than from any per-agent configuration. 

2209 

2210 **specialist** stays in the response and stays empty. The two specialist 

2211 built-ins are knowledge-base connectors, bound by a knowledge grant rather 

2212 than named here, and the `Tool` rows this key used to report never reached 

2213 an invocation at all. An agent's tools *beyond* the general set come from 

2214 its knowledge and its MCP servers, each of which has its own endpoint. 

2215 """ 

2216 _accessible_agent(agent_id, current_user, db, read=True) 

2217 

2218 try: 

2219 all_tools = ai_client.list_tools() 

2220 general = [t for t in all_tools if t.get("category") == "general"] 

2221 except Exception: 

2222 logger.warning( 

2223 "Could not fetch general tools from svc-ai; returning empty list" 

2224 ) 

2225 general = [] 

2226 

2227 return {"general": general, "specialist": []} 

2228 

2229 

2230# --------------------------------------------------------------------------- 

2231# Agent ↔ Toolkit assignment 

2232# 

2233# A toolkit bundles MCP servers for one-step reuse across agents. 

2234# MCP servers are toolkit-only — an agent only ever integrates 

2235# either through an attached toolkit, never individually (mirrors Skillset 

2236# for skills). 

2237# --------------------------------------------------------------------------- 

2238 

2239 

2240@agent_router.get( 

2241 "/{agent_id}/toolkits", 

2242 response_model=list[Schema.AgentToolkit.ReadWithDetail], 

2243) 

2244def list_agent_toolkits( 

2245 agent_id: UUID, 

2246 db: Session = Depends(get_db), 

2247 current_user: User = Depends(get_current_user), 

2248): 

2249 """List toolkits granted to an agent.""" 

2250 _accessible_agent(agent_id, current_user, db, read=True) 

2251 return db.query(AgentToolkit).filter(AgentToolkit.agent_id == agent_id).all() 

2252 

2253 

2254@agent_router.post( 

2255 "/{agent_id}/toolkits", 

2256 response_model=Schema.AgentToolkit.Read, 

2257 status_code=status.HTTP_201_CREATED, 

2258 # Toolkits bundle MCP servers, which are not available in this release; 

2259 # listing and revoking a grant stay. 

2260 dependencies=[Depends(mcp_service.require_available)], 

2261) 

2262def add_agent_toolkit( 

2263 agent_id: UUID, 

2264 body: Schema.AgentToolkit.Add, 

2265 db: Session = Depends(get_db), 

2266 current_user: User = Depends(get_current_user), 

2267): 

2268 """Grant a toolkit (bundle of tools/MCP servers) to an agent.""" 

2269 from fastapi import HTTPException 

2270 

2271 agent = _accessible_agent(agent_id, current_user, db) 

2272 toolkit = db.get(Toolkit, body.toolkit_id) 

2273 if not toolkit: 

2274 raise HTTPException( 

2275 status_code=status.HTTP_404_NOT_FOUND, detail="Toolkit not found" 

2276 ) 

2277 verify_resource_access(toolkit, current_user, db) 

2278 existing = db.get( 

2279 AgentToolkit, {"agent_id": agent_id, "toolkit_id": body.toolkit_id} 

2280 ) 

2281 if existing: 

2282 raise HTTPException( 

2283 status_code=status.HTTP_409_CONFLICT, 

2284 detail="Toolkit already granted to this agent", 

2285 ) 

2286 row = AgentToolkit( 

2287 agent_id=agent_id, toolkit_id=body.toolkit_id, config=body.config 

2288 ) 

2289 try: 

2290 db.add(row) 

2291 db.flush() 

2292 _record_grant_version(db, agent, current_user, "toolkits") 

2293 db.commit() 

2294 db.refresh(row) 

2295 return row 

2296 except Exception: 

2297 db.rollback() 

2298 logger.exception("Failed to grant toolkit to agent") 

2299 raise 

2300 

2301 

2302@agent_router.delete( 

2303 "/{agent_id}/toolkits/{toolkit_id}", 

2304 status_code=status.HTTP_204_NO_CONTENT, 

2305) 

2306def remove_agent_toolkit( 

2307 agent_id: UUID, 

2308 toolkit_id: UUID, 

2309 db: Session = Depends(get_db), 

2310 current_user: User = Depends(get_current_user), 

2311): 

2312 """Revoke a toolkit from an agent.""" 

2313 from fastapi import HTTPException 

2314 

2315 agent = _accessible_agent(agent_id, current_user, db) 

2316 row = db.get(AgentToolkit, {"agent_id": agent_id, "toolkit_id": toolkit_id}) 

2317 if not row: 

2318 raise HTTPException( 

2319 status_code=status.HTTP_404_NOT_FOUND, 

2320 detail="Toolkit assignment not found", 

2321 ) 

2322 db.delete(row) 

2323 db.flush() 

2324 _record_grant_version(db, agent, current_user, "toolkits") 

2325 db.commit() 

2326 

2327 

2328# --------------------------------------------------------------------------- 

2329# Agent ↔ Knowledge repository assignment 

2330# --------------------------------------------------------------------------- 

2331 

2332 

2333@agent_router.get( 

2334 "/{agent_id}/repositories", 

2335 response_model=list[Schema.AgentRepository.ReadWithDetail], 

2336) 

2337def list_agent_repositories( 

2338 agent_id: UUID, 

2339 db: Session = Depends(get_db), 

2340 current_user: User = Depends(get_current_user), 

2341): 

2342 """List knowledge repositories granted to an agent.""" 

2343 _accessible_agent(agent_id, current_user, db, read=True) 

2344 return db.query(AgentRepository).filter(AgentRepository.agent_id == agent_id).all() 

2345 

2346 

2347@agent_router.post( 

2348 "/{agent_id}/repositories", 

2349 response_model=Schema.AgentRepository.Read, 

2350 status_code=status.HTTP_201_CREATED, 

2351) 

2352def add_agent_repository( 

2353 agent_id: UUID, 

2354 body: Schema.AgentRepository.Add, 

2355 db: Session = Depends(get_db), 

2356 current_user: User = Depends(get_current_user), 

2357): 

2358 """Grant a knowledge repository (collection of sources) to an agent. 

2359 

2360 A grant is a reference — the agent reads through the repository — so a 

2361 platform-managed one (the CHAIN-R User Guide, News) may be granted to 

2362 the caller's own agent. The agent itself is still checked for writing. 

2363 """ 

2364 from fastapi import HTTPException 

2365 

2366 agent = _accessible_agent(agent_id, current_user, db) 

2367 repository = db.get(KnowledgeRepository, body.repository_id) 

2368 if not repository: 

2369 raise HTTPException( 

2370 status_code=status.HTTP_404_NOT_FOUND, detail="Repository not found" 

2371 ) 

2372 verify_resource_read(repository, current_user, db) 

2373 inheritance.require_visible( 

2374 db, repository, workspace_service.home_of(db, agent, named=True), "repository" 

2375 ) 

2376 existing = db.get( 

2377 AgentRepository, {"agent_id": agent_id, "repository_id": body.repository_id} 

2378 ) 

2379 if existing: 

2380 raise HTTPException( 

2381 status_code=status.HTTP_409_CONFLICT, 

2382 detail="Repository already granted to this agent", 

2383 ) 

2384 try: 

2385 row = agent_grants.grant_repository( 

2386 db, agent, repository, current_user, config=body.config 

2387 ) 

2388 db.commit() 

2389 # Once committed: a built-in website repository nobody had granted 

2390 # holds nothing until its first crawl. 

2391 built_in_crawls.start_for(db, [repository.id]) 

2392 db.refresh(row) 

2393 return row 

2394 except Exception: 

2395 db.rollback() 

2396 logger.exception("Failed to grant repository to agent") 

2397 raise 

2398 

2399 

2400@agent_router.delete( 

2401 "/{agent_id}/repositories/{repository_id}", 

2402 status_code=status.HTTP_204_NO_CONTENT, 

2403) 

2404def remove_agent_repository( 

2405 agent_id: UUID, 

2406 repository_id: UUID, 

2407 db: Session = Depends(get_db), 

2408 current_user: User = Depends(get_current_user), 

2409): 

2410 """Revoke a knowledge repository from an agent.""" 

2411 from fastapi import HTTPException 

2412 

2413 agent = _accessible_agent(agent_id, current_user, db) 

2414 row = db.get( 

2415 AgentRepository, {"agent_id": agent_id, "repository_id": repository_id} 

2416 ) 

2417 if not row: 

2418 raise HTTPException( 

2419 status_code=status.HTTP_404_NOT_FOUND, 

2420 detail="Repository assignment not found", 

2421 ) 

2422 db.delete(row) 

2423 db.flush() 

2424 _record_grant_version(db, agent, current_user, "repositories") 

2425 db.commit() 

2426 

2427 

2428# --------------------------------------------------------------------------- 

2429# Agent ↔ Skillset assignment 

2430# 

2431# A skillset bundles skills for one-step reuse across agents. Skills are 

2432# skillset-only — an agent only ever integrates a skill through an attached 

2433# skillset, never individually (mirrors Toolkit for tools/MCP servers). 

2434# --------------------------------------------------------------------------- 

2435 

2436 

2437@agent_router.get( 

2438 "/{agent_id}/skillsets", 

2439 response_model=list[Schema.AgentSkillset.ReadWithDetail], 

2440) 

2441def list_agent_skillsets( 

2442 agent_id: UUID, 

2443 db: Session = Depends(get_db), 

2444 current_user: User = Depends(get_current_user), 

2445): 

2446 """List skillsets granted to an agent.""" 

2447 _accessible_agent(agent_id, current_user, db, read=True) 

2448 return db.query(AgentSkillset).filter(AgentSkillset.agent_id == agent_id).all() 

2449 

2450 

2451@agent_router.post( 

2452 "/{agent_id}/skillsets", 

2453 response_model=Schema.AgentSkillset.Read, 

2454 status_code=status.HTTP_201_CREATED, 

2455) 

2456def add_agent_skillset( 

2457 agent_id: UUID, 

2458 body: Schema.AgentSkillset.Add, 

2459 db: Session = Depends(get_db), 

2460 current_user: User = Depends(get_current_user), 

2461): 

2462 """Grant a skillset (bundle of tools/MCP servers/skills) to an agent.""" 

2463 from fastapi import HTTPException 

2464 

2465 agent = _accessible_agent(agent_id, current_user, db) 

2466 skillset = db.get(Skillset, body.skillset_id) 

2467 if not skillset: 

2468 raise HTTPException( 

2469 status_code=status.HTTP_404_NOT_FOUND, detail="Skillset not found" 

2470 ) 

2471 # A grant is a reference, so a built-in skillset may be granted. 

2472 verify_resource_read(skillset, current_user, db) 

2473 inheritance.require_visible( 

2474 db, skillset, workspace_service.home_of(db, agent, named=True), "skillset" 

2475 ) 

2476 existing = db.get( 

2477 AgentSkillset, {"agent_id": agent_id, "skillset_id": body.skillset_id} 

2478 ) 

2479 if existing: 

2480 raise HTTPException( 

2481 status_code=status.HTTP_409_CONFLICT, 

2482 detail="Skillset already granted to this agent", 

2483 ) 

2484 row = AgentSkillset( 

2485 agent_id=agent_id, skillset_id=body.skillset_id, config=body.config 

2486 ) 

2487 try: 

2488 db.add(row) 

2489 db.flush() 

2490 _record_grant_version(db, agent, current_user, "skillsets") 

2491 db.commit() 

2492 db.refresh(row) 

2493 return row 

2494 except Exception: 

2495 db.rollback() 

2496 logger.exception("Failed to grant skillset to agent") 

2497 raise 

2498 

2499 

2500@agent_router.delete( 

2501 "/{agent_id}/skillsets/{skillset_id}", 

2502 status_code=status.HTTP_204_NO_CONTENT, 

2503) 

2504def remove_agent_skillset( 

2505 agent_id: UUID, 

2506 skillset_id: UUID, 

2507 db: Session = Depends(get_db), 

2508 current_user: User = Depends(get_current_user), 

2509): 

2510 """Revoke a skillset from an agent.""" 

2511 from fastapi import HTTPException 

2512 

2513 agent = _accessible_agent(agent_id, current_user, db) 

2514 row = db.get(AgentSkillset, {"agent_id": agent_id, "skillset_id": skillset_id}) 

2515 if not row: 

2516 raise HTTPException( 

2517 status_code=status.HTTP_404_NOT_FOUND, 

2518 detail="Skillset assignment not found", 

2519 ) 

2520 db.delete(row) 

2521 db.flush() 

2522 _record_grant_version(db, agent, current_user, "skillsets") 

2523 db.commit() 

2524 

2525 

2526# --------------------------------------------------------------------------- 

2527# Agent memory (proxied to svc-ai) 

2528# --------------------------------------------------------------------------- 

2529 

2530 

2531def _memory_owner(agent: Agent, current_user: User) -> str: 

2532 """Whose memories a memory route may see or remove: the caller's own. 

2533 

2534 svc-ai keeps memory per (agent, user), and every member who can chat 

2535 with an agent has their own: CHAINR Bot's every user, an organisation's 

2536 or project's members, and a personal agent's too — its owner's personal 

2537 projects inherit it, so their members chat with it. Its owner used to be 

2538 given the agent-wide view, which disclosed what it remembered of those 

2539 members' conversations, and an agent-wide clear wiped theirs. Only 

2540 deleting the agent clears everyone's. 

2541 """ 

2542 return str(current_user.id) 

2543 

2544 

2545@agent_router.get( 

2546 "/{agent_id}/knowledge-kinds", response_model=Schema.AgentContext.Read 

2547) 

2548def get_agent_context_kinds( 

2549 agent_id: UUID, 

2550 db: Session = Depends(get_db), 

2551 current_user: User = Depends(get_current_user), 

2552): 

2553 """What the agent draws on, in eight kinds: its knowledge by kind 

2554 (Domain, Temporal, Reasoning), and what each of the other five comes 

2555 from — skills, the conversation, memory and the decision record, tools, 

2556 rules and instructions — with where to change each. Its memory is 

2557 counted for the caller alone, and its rules are the ones the engine 

2558 applies to it in this workspace.""" 

2559 from app.services import agent_context 

2560 from app.services.agent_context.kinds import OWNER_LABELS 

2561 

2562 agent = _accessible_agent(agent_id, current_user, db, read=True) 

2563 inputs = agent_context.AgentContextInputs( 

2564 db=db, agent=agent, ws=request_workspace(db, current_user), viewer=current_user 

2565 ) 

2566 C = Schema.AgentContext 

2567 return C.Read( 

2568 agent_id=agent.id, 

2569 kinds=[ 

2570 C.Kind( 

2571 key=r.key, 

2572 label=r.label, 

2573 description=r.description, 

2574 owner=r.owner.value, 

2575 owner_label=OWNER_LABELS[r.owner], 

2576 state=r.state.value, 

2577 summary=r.summary, 

2578 facts=[C.Fact(label=f.label, value=f.value) for f in r.facts], 

2579 place=C.Place(kind=r.place.kind.value, target=r.place.target) 

2580 if r.place 

2581 else None, 

2582 category=r.category, 

2583 suggestions=[ 

2584 C.Suggestion(id=x.id, name=x.name, description=x.description) 

2585 for x in r.suggestions 

2586 ], 

2587 ) 

2588 for r in agent_context.read_all(inputs) 

2589 ], 

2590 ) 

2591 

2592 

2593@agent_router.get("/{agent_id}/memory") 

2594def list_agent_memory( 

2595 agent_id: UUID, 

2596 db: Session = Depends(get_db), 

2597 current_user: User = Depends(get_current_user), 

2598): 

2599 """Return all persisted memory entries for this agent.""" 

2600 agent = _accessible_agent(agent_id, current_user, db, read=True) 

2601 try: 

2602 return ai_client.get_agent_memory( 

2603 str(agent_id), user_id=_memory_owner(agent, current_user) 

2604 ) 

2605 except ai_client.AIServiceError: 

2606 return [] 

2607 

2608 

2609@agent_router.delete( 

2610 "/{agent_id}/memory/{memory_id}", 

2611 status_code=status.HTTP_204_NO_CONTENT, 

2612) 

2613def delete_agent_memory_item( 

2614 agent_id: UUID, 

2615 memory_id: str, 

2616 db: Session = Depends(get_db), 

2617 current_user: User = Depends(get_current_user), 

2618): 

2619 """Delete a single memory entry for this agent.""" 

2620 from fastapi import HTTPException 

2621 

2622 agent = _accessible_agent(agent_id, current_user, db, read=True) 

2623 try: 

2624 ai_client.delete_agent_memory_item( 

2625 str(agent_id), memory_id, user_id=_memory_owner(agent, current_user) 

2626 ) 

2627 except ai_client.AIServiceError as exc: 

2628 raise HTTPException( 

2629 status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc) 

2630 ) from exc 

2631 

2632 

2633@agent_router.delete( 

2634 "/{agent_id}/memory", 

2635 status_code=status.HTTP_204_NO_CONTENT, 

2636) 

2637def clear_agent_memory( 

2638 agent_id: UUID, 

2639 db: Session = Depends(get_db), 

2640 current_user: User = Depends(get_current_user), 

2641): 

2642 """Clear all memory entries for this agent.""" 

2643 from fastapi import HTTPException 

2644 

2645 agent = _accessible_agent(agent_id, current_user, db, read=True) 

2646 try: 

2647 ai_client.clear_agent_memory( 

2648 str(agent_id), user_id=_memory_owner(agent, current_user) 

2649 ) 

2650 except ai_client.AIServiceError as exc: 

2651 raise HTTPException( 

2652 status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc) 

2653 ) from exc 

2654 

2655 

2656# --------------------------------------------------------------------------- 

2657# Edit history (audit trail) 

2658# --------------------------------------------------------------------------- 

2659 

2660register_history_routes( 

2661 agent_router, 

2662 resource_type=HistoryEnum.ResourceType.agent, 

2663 model=Agent, 

2664 not_found_detail="Agent not found", 

2665 # Reading a trail is a read: CHAINR Bot's releases are on it too. 

2666 access_check=verify_resource_read, 

2667)