Coverage for app / services / scenarios / driver.py: 97%

150 statements  

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

1"""Running one scenario turn exactly as a person's chat runs it. 

2 

3The agent chat's turn is the websocket route 

4(``router/app/agents/router.py`` ``agent_prompt_ws``), and it touches its 

5socket only through ``accept``, one ``receive_json`` for the opening frame 

6and then ``ChatSocket``'s ``send_text`` / ``receive_json`` / ``close``. So a 

7stand-in socket (``ScenarioSocket``) runs the real turn — the same rules, 

8ledger, stored messages, retrieval record and decision record — and keeps 

9every frame it is sent. That includes a failed turn's frames, which nothing 

10else stores (``persist_error_turn`` keeps no trace). 

11 

12svc-ai's terminal frame never reaches a socket; ``ai_client.tap_stream`` 

13catches it (every passage retrieved, not only those cited). 

14 

15The stand-in never "leaves": after the opening frame its reads wait on a 

16queue, which holds only what the driver puts there — a pause's answers, a 

17non-answer when it has none, or Stop when the turn runs too long. 

18 

19A pause the file wrote no answers for is left unanswered, unless the file 

20says to answer it (``ScenarioFile.pauses``): then it gets what a person with 

21no preference would give (``default_answers``). Run 5's b-bakery asked 

22"Which regions?" after fifteen tool calls, and the turn ended there with no 

23answer, no quality check and no citations to measure. 

24""" 

25 

26from __future__ import annotations 

27 

28import asyncio 

29import json 

30import logging 

31from collections.abc import Awaitable, Callable 

32from dataclasses import dataclass, field 

33from time import perf_counter 

34from typing import Any 

35from uuid import UUID 

36 

37from app.services import ai_client, hitl 

38from app.util.time import aware_utcnow, utc_isoformat 

39 

40logger = logging.getLogger(__name__) 

41 

42#: A turn still running after this long is stopped, as Stop would stop it. 

43TURN_TIMEOUT_S = 600 

44#: How long a stopped turn is given to store itself before it is cancelled. 

45STOP_GRACE_S = 60 

46#: The frame that is no answer to a pause: the route records the pause as 

47#: unanswered ("The client sent something other than an answer."). 

48NOT_AN_ANSWER = "scenario_no_answer" 

49 

50#: Frames the route sends that are not kept: one per streamed token. 

51_NOT_KEPT = frozenset({"token", "worker_token"}) 

52 

53#: ``agent_prompt_ws``'s signature, for the stand-in a test passes. 

54TurnHandler = Callable[..., Awaitable[None]] 

55 

56#: What a question typed rather than chosen is answered with by default. 

57NO_PREFERENCE = "No preference — use your judgement" 

58#: How a pause given ``default_answers`` is recorded, after what the route 

59#: makes of it (``hitl.outcome``: answered or skipped; or an approval). 

60DEFAULT_SUFFIX = " (default)" 

61 

62 

63def _option_values(question: dict[str, Any], *, recommended: bool) -> list[str]: 

64 return [ 

65 str(option["value"]) 

66 for option in question.get("options") or [] 

67 if isinstance(option, dict) 

68 and option.get("value") not in (None, "") 

69 and (not recommended or option.get("recommended")) 

70 ] 

71 

72 

73def _default_for(question: dict[str, Any]) -> list[str]: 

74 """One question's answer from a person with no preference: the option 

75 the agent recommends (every one, for a question of several choices), 

76 else its first; a text field's ``NO_PREFERENCE``; nothing for a number 

77 or a date, which no default can honestly supply.""" 

78 kind = question.get("kind") or "single" 

79 if kind in hitl.INPUT_KINDS: 

80 return [NO_PREFERENCE] if kind == "text" else [] 

81 picked = _option_values(question, recommended=True) or _option_values( 

82 question, recommended=False 

83 ) 

84 if picked: 

85 return picked if kind == "multi" else picked[:1] 

86 return [NO_PREFERENCE] if question.get("allow_other", True) else [] 

87 

88 

89def default_answers(frame: dict[str, Any]) -> dict[str, list[str]]: 

90 """What a person with no preference answers ``frame`` (a 

91 ``hitl_interrupt``) with, checked as the chat route checks an answer 

92 (``hitl.validate_response``). When that would refuse it — a required 

93 number or date — no answer at all is given, which the route takes as a 

94 deliberate skip: the agent goes on with its own judgement.""" 

95 pause = hitl.normalise_interrupt(frame) 

96 answers = { 

97 str(question.get("id")): values 

98 for question in pause.get("questions") or [] 

99 if (values := _default_for(question)) 

100 } 

101 try: 

102 hitl.validate_response(pause, {"answers": answers}) 

103 except hitl.HitlResponseInvalid: 

104 return {} 

105 return answers 

106 

107 

108class ScenarioSocket: 

109 """What ``agent_prompt_ws`` uses of a websocket, and nothing else.""" 

110 

111 def __init__( 

112 self, 

113 opening: dict[str, Any], 

114 answers: dict | None = None, 

115 *, 

116 answer_unscripted: bool = False, 

117 ) -> None: 

118 self._opening = opening 

119 self._opened = False 

120 self._queue: asyncio.Queue[dict] = asyncio.Queue() 

121 self._answers = answers 

122 self._answered = False 

123 self._answer_unscripted = answer_unscripted 

124 #: Every frame sent, tokens aside, in order. 

125 self.frames: list[dict] = [] 

126 self.tokens = 0 

127 #: What each pause was given: ``answered``, ``not answered``, or 

128 #: what a default answer came to (``answered (default)``, 

129 #: ``skipped (default)``, ``approved (default)``). 

130 self.pauses: list[str] = [] 

131 

132 async def accept(self) -> None: 

133 return None 

134 

135 async def receive_json(self) -> dict: 

136 if not self._opened: 

137 self._opened = True 

138 return self._opening 

139 return await self._queue.get() 

140 

141 async def send_text(self, text: str) -> None: 

142 frame = json.loads(text) 

143 kind = frame.get("type") 

144 if kind in _NOT_KEPT: 

145 self.tokens += 1 

146 return 

147 self.frames.append(frame) 

148 if kind == "hitl_interrupt": 

149 self._answer(frame) 

150 elif kind == "hitl_invalid": 

151 # The answers given did not fit the questions: give up on this 

152 # pause rather than loop on it. 

153 self.pauses.append("answers refused") 

154 self._queue.put_nowait({"type": NOT_AN_ANSWER}) 

155 

156 async def close(self) -> None: 

157 return None 

158 

159 def stop(self) -> None: 

160 """Stop the turn, as the chat's Stop button does.""" 

161 self._queue.put_nowait({"type": "stop"}) 

162 

163 def _answer(self, frame: dict[str, Any]) -> None: 

164 if self._answers is not None and not self._answered: 

165 # Once: a second pause in the same turn is never given them, so 

166 # a scripted answer never meets a question it was not written 

167 # for. 

168 self._answered = True 

169 self.pauses.append("answered") 

170 self._queue.put_nowait( 

171 {"type": "hitl_resume", "answers": self._answers, "approved": True} 

172 ) 

173 return 

174 if self._answer_unscripted: 

175 # Every pause the file did not script, each with what a person 

176 # with no preference would say. svc-ai asks once a turn, and an 

177 # approval gate pauses once a step, so this cannot go on. 

178 if hitl.is_clarification(frame): 

179 answers = default_answers(frame) 

180 given = hitl.outcome({"kind": hitl.CLARIFICATION, "answers": answers}) 

181 else: 

182 answers, given = {}, "approved" 

183 self.pauses.append(given + DEFAULT_SUFFIX) 

184 self._queue.put_nowait( 

185 {"type": "hitl_resume", "answers": answers, "approved": True} 

186 ) 

187 return 

188 self.pauses.append("not answered") 

189 self._queue.put_nowait({"type": NOT_AN_ANSWER}) 

190 

191 

192@dataclass 

193class TurnRun: 

194 """What one turn sent, and how it ended.""" 

195 

196 frames: list[dict] 

197 #: svc-ai's terminal frames (``done``, ``error``), one per stream leg. 

198 terminal: list[dict] 

199 started_at: str 

200 duration_ms: int 

201 tokens: int = 0 

202 pauses: list[str] = field(default_factory=list) 

203 #: Stopped for running past ``TURN_TIMEOUT_S``. 

204 timed_out: bool = False 

205 #: The route itself raised (it stores and reports its own failures, so 

206 #: this is something it could not). 

207 crashed: str | None = None 

208 

209 def last(self, kind: str) -> dict | None: 

210 return next((f for f in reversed(self.frames) if f.get("type") == kind), None) 

211 

212 @property 

213 def conversation_id(self) -> UUID | None: 

214 for kind in ("response", "turn"): 

215 frame = self.last(kind) 

216 if frame and frame.get("conversation_id"): 

217 return UUID(str(frame["conversation_id"])) 

218 return None 

219 

220 

221def _handler() -> TurnHandler: 

222 # The router imports half the services; read it when a turn runs. 

223 from app.router.app.agents.router import agent_prompt_ws 

224 

225 return agent_prompt_ws 

226 

227 

228async def run_turn( 

229 *, 

230 user_id: UUID, 

231 agent_id: UUID, 

232 prompt: str, 

233 conversation_id: UUID | None, 

234 workspace_key: str | None, 

235 answers: dict | None = None, 

236 answer_unscripted: bool = False, 

237 command_inputs: dict | None = None, 

238 session_factory: Callable[[], Any] | None = None, 

239 handler: TurnHandler | None = None, 

240 timeout_s: float = TURN_TIMEOUT_S, 

241) -> TurnRun: 

242 """One turn of agent chat, run and stored as the chat runs it. 

243 

244 Runs in a task of its own: the route sets its workspace, invocation and 

245 budget on the task it runs in, and never resets them.""" 

246 from app.db.postgres.engine import SessionLocal 

247 from app.db.postgres.models import User 

248 

249 factory = session_factory or SessionLocal 

250 turn_handler = handler or _handler() 

251 opening: dict[str, Any] = {"prompt": prompt} 

252 if conversation_id is not None: 

253 opening["conversation_id"] = str(conversation_id) 

254 if workspace_key: 

255 opening["workspace"] = workspace_key 

256 if command_inputs: 

257 opening["command_inputs"] = command_inputs 

258 sock = ScenarioSocket(opening, answers, answer_unscripted=answer_unscripted) 

259 terminal: list[dict] = [] 

260 started_at = aware_utcnow() 

261 clock = perf_counter() 

262 crashed: str | None = None 

263 timed_out = False 

264 

265 db = factory() 

266 try: 

267 user = db.get(User, user_id) 

268 

269 async def _turn() -> None: 

270 with ai_client.tap_stream(terminal.append): 

271 await turn_handler(agent_id, sock, db=db, current_user=user) 

272 

273 task = asyncio.create_task(_turn()) 

274 try: 

275 await asyncio.wait_for(asyncio.shield(task), timeout_s) 

276 except asyncio.TimeoutError: 

277 timed_out = True 

278 logger.warning("Scenario turn ran past %ss; stopping it", timeout_s) 

279 sock.stop() 

280 try: 

281 await asyncio.wait_for(task, STOP_GRACE_S) 

282 except asyncio.TimeoutError: 

283 task.cancel() 

284 crashed = "The turn did not stop when asked, and was cancelled." 

285 except Exception as exc: # noqa: BLE001 — recorded on the turn 

286 logger.exception("Scenario turn failed outside the chat route") 

287 crashed = type(exc).__name__ 

288 finally: 

289 db.close() 

290 

291 return TurnRun( 

292 frames=sock.frames, 

293 terminal=terminal, 

294 started_at=utc_isoformat(started_at), 

295 duration_ms=int((perf_counter() - clock) * 1000), 

296 tokens=sock.tokens, 

297 pauses=sock.pauses, 

298 timed_out=timed_out, 

299 crashed=crashed, 

300 )