Coverage for app / services / hitl.py: 97%

184 statements  

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

1""" 

2Human in the loop — what a run showed a person when it stopped, and what they 

3said back. 

4 

5A graph run in svc-ai can pause for a person in three ways, all raised with 

6LangGraph's ``interrupt()`` and all resumed with the same payload: 

7 

8* an agent calling ``ask_user`` mid-task (``source="tool"``); 

9* the ``__clarify__`` node, when an agent that checks scope finds a request 

10 ambiguous before any work starts (``source="scope"``); 

11* an approval gate — a skill node's ``approval`` flag, or the ``__hitl__`` 

12 node — holding work for a decision. 

13 

14Two surfaces answer them: a chat turn, over its websocket, and a standalone 

15skill run, from its page. Both need the same things done to a pause, so they 

16live here once rather than twice: 

17 

18* ``normalise_interrupt`` — svc-ai's frame in the shape stored and drawn; 

19* ``pause_text`` / ``response_text`` — what the person saw and said, as text 

20 for the audit and policy rules (a question is model output reaching a 

21 person; an answer is user input reaching a model — both are governed); 

22* ``validate_response`` — an answer checked against the question it answers: 

23 every required one answered, a radio answered once, options drawn from 

24 the options unless "Other" was offered, numbers numeric, dates dates; 

25* ``exchange`` / ``resume_trace_frame`` — the record kept of it, on the 

26 message (chat) or the run (skill runs), and in the turn's trace beside the 

27 ``hitl_pause`` frame svc-ai emitted, so a trace reads *paused here, asked 

28 this, answered that, by whom, after how long*. 

29""" 

30 

31from __future__ import annotations 

32 

33import math 

34from datetime import date, datetime 

35from typing import Any, NamedTuple 

36 

37from sqlalchemy.orm import Session 

38 

39from app.services import governance_activity as activity_service 

40from app.services import rule_engine 

41from app.services.rules import pii 

42from app.util import web_domains 

43from app.util.time import aware_utcnow, utc_isoformat 

44 

45CLARIFICATION = "clarification" 

46APPROVAL = "approval" 

47 

48#: svc-ai's discriminator for a clarification pause (``tools/clarify.py``). 

49CLARIFICATION_INTERRUPT = "clarification_request" 

50APPROVAL_INTERRUPT = "approval_request" 

51 

52#: Question kinds answered by typing a value rather than choosing options. 

53INPUT_KINDS = frozenset({"text", "number", "date"}) 

54 

55#: How long one answer may be. A clarification is a few words or a figure; 

56#: anything longer is a document pasted into the wrong box, and it goes to a 

57#: model on the resume, where it would be billed. 

58MAX_ANSWER_CHARS = 4000 

59 

60 

61class HitlResponseInvalid(ValueError): 

62 """An answer that does not fit the pause. ``fields`` names what is wrong, 

63 keyed by question id (or ``approved`` / ``answers``).""" 

64 

65 def __init__(self, message: str, fields: dict[str, str] | None = None) -> None: 

66 super().__init__(message) 

67 self.message = message 

68 self.fields = fields or {} 

69 

70 

71# ── Shape ───────────────────────────────────────────────────────────────────── 

72 

73 

74def is_clarification(interrupt: dict[str, Any]) -> bool: 

75 return interrupt.get("interrupt_type") == CLARIFICATION_INTERRUPT or ( 

76 interrupt.get("kind") == CLARIFICATION 

77 ) 

78 

79 

80def normalise_interrupt(interrupt: dict[str, Any]) -> dict[str, Any]: 

81 """svc-ai's interrupt payload in the shape a pause is stored and drawn.""" 

82 kind = CLARIFICATION if is_clarification(interrupt) else APPROVAL 

83 pause: dict[str, Any] = { 

84 "kind": kind, 

85 "thread_id": interrupt.get("thread_id"), 

86 "node_id": interrupt.get("node_id") or None, 

87 "paused_at": utc_isoformat(aware_utcnow()), 

88 } 

89 if kind == CLARIFICATION: 

90 pause["source"] = interrupt.get("source") or "tool" 

91 pause["title"] = interrupt.get("title") 

92 pause["intro"] = interrupt.get("intro") 

93 if interrupt.get("reason"): 

94 pause["reason"] = interrupt["reason"] 

95 pause["questions"] = [ 

96 q for q in interrupt.get("questions") or [] if isinstance(q, dict) 

97 ] 

98 else: 

99 pause["message"] = interrupt.get("message") or interrupt.get("task") or "" 

100 completed = interrupt.get("completed") 

101 pause["completed"] = ( 

102 completed 

103 if isinstance(completed, dict) 

104 # The whole-run gate knows only the output it is holding. 

105 else {"result": str(interrupt.get("output") or "")} 

106 ) 

107 return pause 

108 

109 

110def pause_text(pause: dict[str, Any]) -> str: 

111 """What a pause shows a person, as text for the audit rules.""" 

112 if pause.get("kind") == CLARIFICATION: 

113 lines = [str(pause.get("title") or ""), str(pause.get("intro") or "")] 

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

115 lines.append(str(question.get("question") or "")) 

116 lines.extend( 

117 str(o.get("label") or o.get("value") or "") 

118 for o in question.get("options") or [] 

119 if isinstance(o, dict) 

120 ) 

121 return "\n".join(line for line in lines if line) 

122 completed = pause.get("completed") or {} 

123 return "\n\n".join( 

124 [str(pause.get("message") or "")] 

125 + [f"{node}:\n{text}" for node, text in completed.items()] 

126 ).strip() 

127 

128 

129def response_text(pause: dict[str, Any], response: dict[str, Any]) -> str: 

130 """What a person answered, as the text the policy rules evaluate.""" 

131 if pause.get("kind") == CLARIFICATION: 

132 questions = { 

133 str(q.get("id")): str(q.get("question") or q.get("id")) 

134 for q in pause.get("questions") or [] 

135 } 

136 lines = [ 

137 f"- {questions.get(str(qid), qid)}: {', '.join(map(str, values or []))}" 

138 for qid, values in (response.get("answers") or {}).items() 

139 ] 

140 return "Answers:\n" + "\n".join(lines) 

141 verdict = "Approved" if response.get("approved", True) else "Rejected" 

142 feedback = str(response.get("feedback") or "").strip() 

143 return f"{verdict}." + (f" Feedback: {feedback}" if feedback else "") 

144 

145 

146# ── Validation ──────────────────────────────────────────────────────────────── 

147 

148 

149def _values(raw: Any) -> list[str]: 

150 return [ 

151 str(v).strip() 

152 for v in (raw if isinstance(raw, list) else [raw]) 

153 if v is not None and str(v).strip() 

154 ] 

155 

156 

157def _typed_problem(kind: str, value: str) -> str | None: 

158 """Why ``value`` is not a valid answer to a ``kind`` field, or None.""" 

159 if kind == "number": 

160 try: 

161 number = float(value.replace(",", "")) 

162 except ValueError: 

163 return "enter a number" 

164 return None if math.isfinite(number) else "enter a number" 

165 if kind == "date": 

166 try: 

167 date.fromisoformat(value) 

168 except ValueError: 

169 return "enter a date as YYYY-MM-DD" 

170 return None 

171 

172 

173def validate_response( 

174 pause: dict[str, Any], response: dict[str, Any] 

175) -> dict[str, Any]: 

176 """A person's answer to ``pause``, checked and normalised. 

177 

178 Raises ``HitlResponseInvalid`` naming what is wrong. An approval needs a 

179 decision; a clarification needs an answer to every required question, 

180 drawn from the offered options where "Other" was not offered, and typed 

181 fields holding the type they ask for. An empty answer set is a deliberate 

182 skip and is accepted: svc-ai tells the agent every question went 

183 unanswered and it proceeds on its own judgement. 

184 """ 

185 if pause.get("kind") == APPROVAL: 

186 if response.get("approved") is None: 

187 raise HitlResponseInvalid( 

188 "Approve or reject the step.", {"approved": "required"} 

189 ) 

190 feedback = str(response.get("feedback") or "").strip() 

191 if len(feedback) > MAX_ANSWER_CHARS: 

192 raise HitlResponseInvalid("Feedback is too long.", {"feedback": "too long"}) 

193 return { 

194 "kind": APPROVAL, 

195 "approved": bool(response["approved"]), 

196 "feedback": feedback, 

197 } 

198 answers = response.get("answers") 

199 if not isinstance(answers, dict): 

200 raise HitlResponseInvalid("Answer the questions.", {"answers": "required"}) 

201 problems: dict[str, str] = {} 

202 cleaned: dict[str, list[str]] = {} 

203 skipping = not any(_values(v) for v in answers.values()) 

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

205 qid = str(question.get("id")) 

206 values = _values(answers.get(qid)) 

207 if not values: 

208 if question.get("required", True) and not skipping: 

209 problems[qid] = "required" 

210 continue 

211 if any(len(v) > MAX_ANSWER_CHARS for v in values): 

212 problems[qid] = "too long" 

213 continue 

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

215 if kind in INPUT_KINDS: 

216 if len(values) > 1: 

217 problems[qid] = "one value" 

218 continue 

219 problem = _typed_problem(kind, values[0]) 

220 if problem: 

221 problems[qid] = problem 

222 continue 

223 cleaned[qid] = values 

224 continue 

225 allowed = { 

226 str(o.get("value")) 

227 for o in question.get("options") or [] 

228 if isinstance(o, dict) 

229 } 

230 if kind == "single" and len(values) > 1: 

231 problems[qid] = "choose one" 

232 continue 

233 if ( 

234 allowed 

235 and not question.get("allow_other", True) 

236 and any(v not in allowed for v in values) 

237 ): 

238 problems[qid] = "choose one of the options" 

239 continue 

240 cleaned[qid] = values 

241 if problems: 

242 raise HitlResponseInvalid("Some questions need an answer.", problems) 

243 return {"kind": CLARIFICATION, "answers": cleaned} 

244 

245 

246# ── Governance ──────────────────────────────────────────────────────────────── 

247 

248 

249class AuditedPause(NamedTuple): 

250 """A pause after the Output rules ran on it (:func:`audit_pause`).""" 

251 

252 #: The pause as it is stored and shown: redacted, or withheld. 

253 pause: dict[str, Any] 

254 #: The rules' events, any ``flag_for_review`` among them. 

255 events: list[dict] 

256 #: The redaction a ``redact_pii`` rule applied, for the frames that carry 

257 #: the same text to the browser. 

258 redactor: pii.Redactor | None 

259 #: What a ``withhold`` rule withheld, for its review item; the frames 

260 #: then show its message (:func:`withhold_shown`). 

261 withheld: rule_engine.Withheld | None 

262 

263 

264def audit_pause( 

265 db: Session, pause: dict[str, Any], context: dict[str, Any], owner_user_id: str 

266) -> AuditedPause: 

267 """Audit rules over what a pause is about to show a person. 

268 

269 A question, or the draft an approval gate holds, is model output 

270 reaching a person as surely as a final answer is. The pause comes back 

271 redacted throughout when a ``redact_pii`` rule ran, with that rule's own 

272 kinds and placeholders, or showing a ``withhold`` rule's message in place 

273 of what it held (the person may still go on, or skip the questions). 

274 """ 

275 result = rule_engine.evaluate_output(db, pause_text(pause), context, owner_user_id) 

276 activity_service.commit(db) 

277 audited = result.redact(pause) 

278 if result.withheld is not None: 

279 audited = withhold_shown(audited, audited.get("kind"), result.withheld.message) 

280 return AuditedPause( 

281 audited, list(result.events or []), result.redactor, result.withheld 

282 ) 

283 

284 

285#: What a pause, its trace frame or the interrupt sent to the page shows. 

286_SHOWN_KEYS = frozenset( 

287 {"title", "intro", "reason", "questions", "task", "output", "message", "completed"} 

288) 

289 

290 

291def withhold_shown(values: dict[str, Any], kind: Any, message: str) -> dict[str, Any]: 

292 """``values`` — a pause, its trace frame or the interrupt sent to the page 

293 — with what it shows replaced by a withhold rule's ``message``: a 

294 clarification asks nothing, an approval gate holds nothing.""" 

295 kept = {key: value for key, value in values.items() if key not in _SHOWN_KEYS} 

296 if kind == CLARIFICATION: 

297 return {**kept, "intro": message, "questions": [], "withheld": True} 

298 return { 

299 **kept, 

300 "message": message, 

301 "task": message, 

302 "completed": {}, 

303 "withheld": True, 

304 } 

305 

306 

307class GovernedAnswer(tuple): 

308 """``(answer to forward, whether it was redacted)``, as ``govern_answer`` 

309 has always returned — plus ``spend_limit``, what the re-check left the 

310 turn to spend (``RulePass.spend_limit``), and ``web_policy``, the web 

311 sources its Tools rules set (``RulePass.web_policy``), for the resume it 

312 allows.""" 

313 

314 spend_limit: "rule_engine.SpendLimit | None" 

315 web_policy: web_domains.WebPolicy | None 

316 

317 def __new__( 

318 cls, 

319 forwarded: dict[str, Any], 

320 redacted: bool, 

321 spend_limit: "rule_engine.SpendLimit | None" = None, 

322 web_policy: web_domains.WebPolicy | None = None, 

323 ) -> "GovernedAnswer": 

324 instance = super().__new__(cls, (forwarded, redacted)) 

325 instance.spend_limit = spend_limit 

326 instance.web_policy = web_policy 

327 return instance 

328 

329 

330def govern_answer( 

331 db: Session, 

332 pause: dict[str, Any], 

333 cleaned: dict[str, Any], 

334 context: dict[str, Any], 

335 owner_user_id: str, 

336) -> GovernedAnswer: 

337 """Policy rules over what a person answered, before any model sees it. 

338 

339 An answer is user input on its way to the model, so it meets the rules 

340 the prompt met: a ``block`` raises ``rule_engine.RuleBlock`` (the caller 

341 ends the turn), and a ``filter_pii`` redacts every answer value with the 

342 kinds it names. Returns the answer to forward and whether it was 

343 redacted, what the turn may spend now (``spend_limits.for_resume``) and 

344 the web sources its Tools rules set now (``spend_limits.web_for_resume``). 

345 """ 

346 try: 

347 result = rule_engine.evaluate_input( 

348 db, response_text(pause, cleaned), context, owner_user_id 

349 ) 

350 finally: 

351 # A refusal is the record the activity log least tolerates losing. 

352 activity_service.commit(db) 

353 limit = getattr(result, "spend_limit", None) 

354 web = getattr(result, "web_policy", None) 

355 if result.redactor is not None: 

356 return GovernedAnswer(result.redact(cleaned), True, limit, web) 

357 return GovernedAnswer(cleaned, False, limit, web) 

358 

359 

360def abandoned(pause: dict[str, Any], *, reason: str) -> dict[str, Any]: 

361 """The record of a pause nobody answered — the chat closed, say.""" 

362 return { 

363 "kind": pause.get("kind"), 

364 "outcome": "abandoned", 

365 "node_id": pause.get("node_id"), 

366 "paused_at": pause.get("paused_at"), 

367 "reason_closed": reason, 

368 **( 

369 {"source": pause.get("source"), "questions": pause.get("questions") or []} 

370 if pause.get("kind") == CLARIFICATION 

371 else {"message": pause.get("message") or ""} 

372 ), 

373 } 

374 

375 

376# ── Record ──────────────────────────────────────────────────────────────────── 

377 

378 

379def outcome(cleaned: dict[str, Any]) -> str: 

380 """One word for how a pause ended: answered / skipped / approved / rejected.""" 

381 if cleaned.get("kind") == APPROVAL: 

382 return "approved" if cleaned.get("approved") else "rejected" 

383 return "answered" if cleaned.get("answers") else "skipped" 

384 

385 

386def _waited_ms(paused_at: Any, answered_at: datetime) -> int | None: 

387 try: 

388 started = datetime.fromisoformat(str(paused_at)) 

389 except (TypeError, ValueError): 

390 return None 

391 if started.tzinfo is None: 

392 started = started.replace(tzinfo=answered_at.tzinfo) 

393 return max(0, int((answered_at - started).total_seconds() * 1000)) 

394 

395 

396def exchange( 

397 pause: dict[str, Any], 

398 cleaned: dict[str, Any], 

399 *, 

400 actor_id: Any, 

401 redacted: bool = False, 

402) -> dict[str, Any]: 

403 """The record of one pause and its answer. 

404 

405 Kept whole — the questions as shown, not only the answers — because an 

406 answer ``["eu"]`` means nothing to an auditor without the question and 

407 the options it was chosen from. ``redacted`` notes that a policy rule 

408 filtered PII out of the answer before the agent saw it; the stored 

409 answer is the filtered one, so the record never holds more than the 

410 model was given. 

411 """ 

412 answered_at = aware_utcnow() 

413 record: dict[str, Any] = { 

414 "kind": pause.get("kind"), 

415 "outcome": outcome(cleaned), 

416 "node_id": pause.get("node_id"), 

417 "paused_at": pause.get("paused_at"), 

418 "answered_at": utc_isoformat(answered_at), 

419 "answered_by": str(actor_id) if actor_id else None, 

420 "waited_ms": _waited_ms(pause.get("paused_at"), answered_at), 

421 } 

422 if pause.get("kind") == CLARIFICATION: 

423 record.update( 

424 source=pause.get("source") or "tool", 

425 title=pause.get("title"), 

426 intro=pause.get("intro"), 

427 questions=pause.get("questions") or [], 

428 answers=cleaned.get("answers") or {}, 

429 ) 

430 if pause.get("reason"): 

431 record["reason"] = pause["reason"] 

432 else: 

433 record.update( 

434 message=pause.get("message") or "", 

435 approved=bool(cleaned.get("approved")), 

436 feedback=cleaned.get("feedback") or "", 

437 ) 

438 if redacted: 

439 record["redacted"] = True 

440 return record 

441 

442 

443def resume_trace_frame(record: dict[str, Any]) -> dict[str, Any]: 

444 """The ``hitl_resume`` trace frame closing svc-ai's ``hitl_pause``.""" 

445 frame: dict[str, Any] = { 

446 "type": "hitl_resume", 

447 "node_id": record.get("node_id") or "", 

448 "interrupt_type": ( 

449 CLARIFICATION_INTERRUPT 

450 if record.get("kind") == CLARIFICATION 

451 else APPROVAL_INTERRUPT 

452 ), 

453 "outcome": record.get("outcome"), 

454 "answered_at": record.get("answered_at"), 

455 "answered_by": record.get("answered_by"), 

456 "waited_ms": record.get("waited_ms"), 

457 } 

458 if record.get("kind") == CLARIFICATION: 

459 frame["answers"] = record.get("answers") or {} 

460 else: 

461 frame["approved"] = record.get("approved") 

462 frame["feedback"] = record.get("feedback") or "" 

463 if record.get("redacted"): 

464 frame["redacted"] = True 

465 return frame