Coverage for app / services / skill_runs / runner.py: 88%
360 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Standalone skill runs — a skill used as structured inference.
4A run is started in the request (inputs validated against the run schema, a
5``running`` row committed) and carried out on a worker thread, because a
6multi-step workflow — research a topic, then write a report on it — takes
7longer than anyone should hold an HTTP request open for. The page polls the
8row.
10It is governed the way an agent turn is, not the way the old test bench was.
11That forwarded rules to svc-ai and nothing else, so svc-core's ``core_only``
12actions (block, rate limits, cost caps) never ran, nothing reached the usage
13ledger, and a skill used as a workflow would have been the one way to reach a
14model that no quota counted. Here:
16* **policy** rules run over the task text *and* the form values (they are
17 written into the task, see ``compose_task``); when a PII filter fires, the
18 structured inputs are redacted too, so the state the graph is seeded with
19 holds what the prompt does;
20* **audit** rules run over the answer *and* the structured outputs; when a
21 redaction runs, it runs over every stored value — outputs, final state and
22 each step's text — because a run page showing the redacted answer beside an
23 unredacted ``summary`` field would be the redaction failing quietly;
24* the call is **ledgered** as ``execution_type="skill"`` against the skill
25 and the project/organisation that owns it, succeeded or failed, with the
26 cost svc-ai *measured* — every model call priced on the model that made it.
28A run can pause. A node with an approval gate stops before it runs and shows
29the work so far; a node allowed to ``ask_user`` stops with questions. The run
30is then ``awaiting_input`` until its owner answers on the run page
31(``respond``), and each resume is another **segment**: governed on its own
32(policy over the answer, audit over what comes back), ledgered on its own,
33and added to the run's totals. Rejecting a gate ends the run ``rejected``;
34a pause nobody answers within ``PAUSE_TTL`` is cancelled, and svc-ai is told
35to drop the paused state it holds.
36"""
38from __future__ import annotations
40import logging
41from concurrent.futures import ThreadPoolExecutor
42from dataclasses import dataclass
43from datetime import datetime, timedelta
44from decimal import Decimal
45from time import perf_counter
46from typing import Any, Callable
47from uuid import UUID
49from sqlalchemy.orm import Session
51from app.db.postgres.enums import HistoryEnum, SkillRunEnum, UsageEnum
52from app.db.postgres.models import CustomWorker, Skill, SkillRun
53from app.services import ai_client, hitl, rule_engine, skill_graph
54from app.services import history as history_service
55from app.services import spend_limits
56from app.services import review as review_service
57from app.services import usage as usage_service
58from app.services import withholding
59from app.services.rules import scopes as rule_scopes
60from app.services.skill_runs.schema import (
61 RunSchema,
62 build_run_schema,
63 compose_task,
64 render_values,
65 validate_inputs,
66)
67from app.services.skill_runs.steps import steps_from_trace
68from app.util.time import aware_utcnow, utc_isoformat
70logger = logging.getLogger(__name__)
72Status = SkillRunEnum.Status
74#: How long svc-ai may take over one run. A background run has nobody
75#: waiting on the socket, so this is a ceiling on a stuck call, not a
76#: patience budget.
77RUN_TIMEOUT_S = 900.0
78#: A run still ``running`` this long after it started was orphaned by a
79#: restart: the worker thread that owned it is gone.
80ABANDONED_AFTER = timedelta(seconds=RUN_TIMEOUT_S + 300)
81#: What svc-ai records the call as — the label the Activity feed already has.
82TRACE_PURPOSE = "skill"
83EXECUTION_TYPE = "skill"
85_executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix="skill-run")
88class RunRefused(ValueError):
89 """The run cannot start. ``fields`` names the inputs at fault."""
91 def __init__(self, message: str, fields: dict[str, str] | None = None) -> None:
92 super().__init__(message)
93 self.message = message
94 self.fields = fields or {}
97# ── Run schema ────────────────────────────────────────────────────────────────
100def _definition_lookup(db: Session) -> Callable[[set[str]], dict[str, list[dict]]]:
101 """Worker ``input_schema`` by name: custom workers from svc-core's own
102 rows, built-ins from svc-ai's registry (one call, only when needed)."""
104 def lookup(names: set[str]) -> dict[str, list[dict]]:
105 found: dict[str, list[dict]] = {}
106 custom = {n for n in names if n.startswith(skill_graph.CUSTOM_WORKER_PREFIX)}
107 if custom:
108 for worker in (
109 db.query(CustomWorker)
110 .filter(CustomWorker.definition_name.in_(sorted(custom)))
111 .all()
112 ):
113 found[str(worker.definition_name)] = list(worker.input_schema or [])
114 if names - custom:
115 for row in ai_client.list_agent_definitions(is_builtin=True) or []:
116 if isinstance(row, dict) and row.get("name") in names:
117 found[str(row["name"])] = list(row.get("input_schema") or [])
118 return found
120 return lookup
123def shared_definition_lookup(
124 db: Session,
125) -> Callable[[set[str]], dict[str, list[dict]]]:
126 """``_definition_lookup`` that remembers what it found, for building
127 many skills' run schemas in one request — the chat's command catalogue —
128 with one call to svc-ai rather than one per skill. A failed lookup is not
129 remembered, so the next skill tries again (and degrades the same way)."""
130 lookup = _definition_lookup(db)
131 found: dict[str, list[dict]] = {}
132 asked: set[str] = set()
134 def cached(names: set[str]) -> dict[str, list[dict]]:
135 missing = names - asked
136 if missing:
137 found.update(lookup(missing))
138 asked.update(missing)
139 return {name: found[name] for name in names if name in found}
141 return cached
144def run_schema(
145 db: Session,
146 skill: Skill,
147 lookup: Callable[[set[str]], dict[str, list[dict]]] | None = None,
148) -> RunSchema:
149 return build_run_schema(
150 skill.graph_definition or {}, lookup or _definition_lookup(db)
151 )
154# ── Starting ──────────────────────────────────────────────────────────────────
157def start(
158 db: Session,
159 skill: Skill,
160 user_id: UUID,
161 prompt: str,
162 inputs: dict[str, Any],
163 *,
164 submit: Callable[[UUID], None] | None = None,
165 workspace: Any = None,
166) -> SkillRun:
167 """Validate, record a ``running`` run and hand it to a worker.
169 ``workspace`` is where it was started (``app/services/workspace.py``):
170 its rules govern the run and its ledger counts it, though the run
171 carries on in the background long after the request.
173 Raises ``RunRefused`` for a graph with nothing to run or inputs the run
174 schema does not accept — before anything is written, so a bad form is a
175 422 and never a failed run in the list.
176 """
177 if not (skill.graph_definition or {}).get("nodes"):
178 raise RunRefused("This skill has no graph nodes — build the graph first.")
179 schema = run_schema(db, skill)
180 coerced, errors = validate_inputs(schema, inputs)
181 if errors:
182 raise RunRefused("Some inputs are missing or invalid.", errors)
183 if schema.requires_prompt and not (prompt or "").strip():
184 raise RunRefused(
185 "This skill takes no inputs, so it needs a task to work on.",
186 {"prompt": "required"},
187 )
189 run = SkillRun(
190 skill_id=skill.id,
191 skill_name=skill.name,
192 # Read now, beside the graph it describes: an edit landing while the
193 # run is queued must not make the record claim a revision it did not
194 # run.
195 skill_version=history_service.current_version(
196 db, HistoryEnum.ResourceType.skill, skill.id
197 ),
198 user_id=user_id,
199 **_workspace_columns(workspace),
200 status=Status.running.value,
201 prompt=(prompt or "").strip() or None,
202 inputs=coerced,
203 input_tokens=0,
204 output_tokens=0,
205 llm_calls=0,
206 unpriced_calls=0,
207 started_at=aware_utcnow(),
208 )
209 db.add(run)
210 db.commit()
211 db.refresh(run)
212 (submit or _submit)(run.id)
213 return run
216def _workspace_columns(workspace: Any) -> dict[str, Any]:
217 if workspace is None:
218 return {}
219 stamp = workspace.ledger_stamp()
220 return {
221 "workspace_organisation_id": stamp["owner_organisation_id"],
222 "workspace_project_id": stamp["owner_project_id"],
223 }
226def _workspace_key(run: SkillRun) -> str | None:
227 """The workspace a run was started in, for its rule context. None for a
228 personal run, or one older than the columns: the engine then reads the
229 workspace off the skill, which for a personal skill is the invoker's."""
230 if getattr(run, "workspace_project_id", None):
231 return f"project:{run.workspace_project_id}"
232 if getattr(run, "workspace_organisation_id", None):
233 return f"organisation:{run.workspace_organisation_id}"
234 return None
237def _run_workspace(db: Session, run: SkillRun):
238 """The workspace a run was started in, resolved: what its tool nodes may
239 read (``skill_graph.resolve_for_execution``)."""
240 from app.services import workspace as workspace_service
242 key = _workspace_key(run)
243 if key:
244 return workspace_service.from_key(db, key)
245 return workspace_service.Workspace(
246 workspace_service.WorkspaceKind.personal, run.user_id
247 )
250def _submit(run_id: UUID) -> None:
251 _executor.submit(_execute_logged, run_id)
254def _execute_logged(run_id: UUID) -> None:
255 try:
256 execute(run_id)
257 except Exception: # pragma: no cover — execute() records its own failures
258 logger.exception("Skill run %s crashed", run_id)
261# ── Carrying out ──────────────────────────────────────────────────────────────
264def _without_output(step: dict[str, Any]) -> dict[str, Any]:
265 """A run step with what it wrote left out — for a run whose answer an
266 Output rule withheld."""
267 if not isinstance(step, dict):
268 return step
269 kept = {key: value for key, value in step.items() if key != "output"}
270 if isinstance(kept.get("tool_calls"), list):
271 kept["tool_calls"] = withholding.strip_tool_calls(kept["tool_calls"])
272 return kept
275def _governed_output(output: str, outputs: dict[str, Any] | None) -> str:
276 """The answer plus the structured outputs, as one text for audit rules —
277 a "flag if the response mentions X" rule must see a field that does."""
278 if not outputs:
279 return output
280 return f"{output}\n\nOutputs:\n{render_values(outputs)}"
283def _finish(db: Session, run: SkillRun, status: Status, error: str | None = None):
284 run.status = status.value
285 run.error = error
286 run.finished_at = aware_utcnow()
287 db.commit()
290def execute(
291 run_id: UUID,
292 *,
293 session_factory: Callable[[], Session] | None = None,
294 invoke: Callable[..., dict] | None = None,
295) -> None:
296 """Carry out the next segment of a ``running`` run, recording the outcome.
298 A run is one or more *segments*: the first, from its inputs, and one more
299 for every pause a person answered. Which this is follows from the run: an
300 answered, not-yet-consumed ``interrupt`` means resume it.
302 The session and the svc-ai call are injectable so the whole path —
303 governance, ledger, redaction, pause and resume — can be exercised
304 without either.
305 """
306 if session_factory is None:
307 from app.db.postgres.engine import SessionLocal
309 session_factory = SessionLocal
310 invoke = invoke or ai_client.run_skill
312 db = session_factory()
313 try:
314 run = db.get(SkillRun, run_id)
315 if run is None or run.status != Status.running.value:
316 return
317 skill = db.get(Skill, run.skill_id) if run.skill_id else None
318 if skill is None:
319 _finish(db, run, Status.failed, "The skill was deleted before it ran.")
320 return
321 try:
322 pending = run.interrupt or {}
323 # On a worker thread, with no request behind it: svc-ai is told
324 # the run's workspace for its trace rows (``ai_client``).
325 with ai_client.in_workspace(_workspace_key(run) or "personal"):
326 if pending.get("answered") and not pending.get("consumed"):
327 _resume(db, run, skill, invoke)
328 else:
329 _carry_out(db, run, skill, invoke)
330 except Exception as exc: # noqa: BLE001 — recorded, never left running
331 logger.exception("Skill run %s failed unexpectedly", run_id)
332 db.rollback()
333 run = db.get(SkillRun, run_id)
334 if run is not None and run.status == Status.running.value:
335 _finish(db, run, Status.failed, f"Unexpected error: {exc}")
336 finally:
337 db.close()
340@dataclass
341class _Governance:
342 """The rule context, chain and ledger identity one run is governed under."""
344 user_id: str
345 invocation_id: str
346 scope_chain: list[dict]
347 context: dict[str, Any]
348 ledger: dict[str, Any]
350 @classmethod
351 def of(cls, run: SkillRun, skill: Skill) -> "_Governance":
352 user_id = str(run.user_id)
353 # The run's id across every segment: its rules, ledger rows and
354 # svc-ai's traces carry it (the run's decision record).
355 invocation_id = str(run.invocation_id or rule_engine.new_invocation_id())
356 run.invocation_id = UUID(invocation_id)
357 scope_chain = rule_scopes.serialize(rule_scopes.invocation_chain(skill=skill))
358 return cls(
359 user_id=user_id,
360 invocation_id=invocation_id,
361 scope_chain=scope_chain,
362 context={
363 "execution_type": EXECUTION_TYPE,
364 "user_id": user_id,
365 "scope_type": "skill",
366 "scope_id": str(skill.id),
367 rule_engine.SCOPES_CONTEXT_KEY: scope_chain,
368 rule_engine.INVOCATION_CONTEXT_KEY: invocation_id,
369 rule_engine.WORKSPACE_CONTEXT_KEY: _workspace_key(run),
370 },
371 ledger={
372 "owner_user_id": user_id,
373 "execution_type": EXECUTION_TYPE,
374 "scope_type": "skill",
375 "scope_id": str(skill.id),
376 # Where it ran: the workspace it was started in, else the
377 # skill's own (``usage.workspace_stamp`` completes either).
378 **(
379 {
380 "owner_project_id": run.workspace_project_id,
381 "owner_organisation_id": None
382 if run.workspace_project_id
383 else run.workspace_organisation_id,
384 }
385 if getattr(run, "workspace_project_id", None)
386 or getattr(run, "workspace_organisation_id", None)
387 else {
388 "owner_project_id": skill.owner_project_id,
389 "owner_organisation_id": skill.owner_organisation_id,
390 }
391 ),
392 "source_type": UsageEnum.Source.skill,
393 "source_id": skill.id,
394 "invocation_id": invocation_id,
395 },
396 )
398 def check_input(self, db: Session, text: str) -> rule_engine.RulePass:
399 """Policy rules over ``text``. Raises ``RuleBlock``."""
400 return rule_engine.evaluate_input(
401 db, text, {**self.context, "prompt": text}, self.user_id
402 )
404 def check_output(
405 self,
406 db: Session,
407 text: str,
408 prompt: str | None,
409 figures: dict[str, Any] | None = None,
410 ) -> rule_engine.RulePass:
411 """Audit rules over ``text`` — model output about to be stored or shown.
413 ``figures`` are the segment's latency and cost (``audit_figures``),
414 for a rule that asks about either. A pause is audited without them:
415 they describe a finished call, and a paused run has not finished.
416 """
417 return rule_engine.evaluate_output(
418 db,
419 text,
420 {
421 **self.context,
422 "prompt": prompt or "",
423 "response": text,
424 **(figures or {}),
425 },
426 self.user_id,
427 )
429 def queue_flags(
430 self,
431 db: Session,
432 output_rules: rule_engine.RulePass,
433 remote_events: list[dict] | None,
434 shown: str | None,
435 ) -> None:
436 """Put every ``flag_for_review`` the audit raised — here or in svc-ai —
437 in the review queue, under the run's id: a flag on a skill run used to
438 reach the activity log and no queue. ``shown`` is what the rules ran
439 over (redacted), the excerpt a reviewer reads."""
440 _, events = output_rules
441 review_service.record_flags(
442 db,
443 [*(remote_events or []), *events],
444 owner_user_id=self.user_id,
445 response=shown,
446 execution_type=EXECUTION_TYPE,
447 invocation_id=self.invocation_id,
448 )
449 # What a withhold rule held, kept for review and nowhere on the run.
450 review_service.record_withheld(
451 db,
452 getattr(output_rules, "withheld", None),
453 owner_user_id=self.user_id,
454 execution_type=EXECUTION_TYPE,
455 invocation_id=self.invocation_id,
456 )
459def _carry_out(
460 db: Session, run: SkillRun, skill: Skill, invoke: Callable[..., dict]
461) -> None:
462 """The first segment: policy over the task and inputs, then the run."""
463 gov = _Governance.of(run, skill)
464 task = compose_task(skill.name, skill.description, run.prompt, run.inputs or {})
465 try:
466 input_rules = gov.check_input(db, task)
467 except rule_engine.RuleBlock as exc:
468 run.rule_trace = rule_engine.build_block_trace_from_exc(exc)
469 _finish(
470 db, run, Status.blocked, f"Blocked by rule '{exc.rule_name}': {exc.message}"
471 )
472 return
473 filtered_task = input_rules.text
474 # The inputs travel with the task to the same model, so they meet the
475 # same redaction — the kinds the rule chose, behind the same placeholders.
476 inputs = input_rules.redact(run.inputs or {})
477 run.task = filtered_task
478 run.inputs = inputs
479 # The governance events and the redacted inputs are on record before the
480 # model is called, whatever happens to the call.
481 db.commit()
482 _segment(db, run, skill, invoke, gov, filtered_task, inputs, input_rules)
485def _resume(
486 db: Session, run: SkillRun, skill: Skill, invoke: Callable[..., dict]
487) -> None:
488 """A later segment: policy over what the person answered, then resume."""
489 gov = _Governance.of(run, skill)
490 pending = dict(run.interrupt or {})
491 response = (run.responses or [{}])[-1]
492 # Consumed before the call, so a crash mid-resume cannot replay it.
493 run.interrupt = {**pending, "consumed": True}
494 db.commit()
495 answer_text = response_text(pending, response)
496 try:
497 input_rules = gov.check_input(db, answer_text)
498 except rule_engine.RuleBlock as exc:
499 run.rule_trace = [
500 *(run.rule_trace or []),
501 *rule_engine.build_block_trace_from_exc(exc),
502 ]
503 _finish(
504 db, run, Status.blocked, f"Blocked by rule '{exc.rule_name}': {exc.message}"
505 )
506 return
507 filtered_answer = input_rules.text
508 response = input_rules.redact(response)
509 db.commit()
510 resume = {
511 "thread_id": pending.get("thread_id"),
512 "approved": bool(response.get("approved", True)),
513 "feedback": str(response.get("feedback") or ""),
514 "answers": response.get("answers") or {},
515 }
516 _segment(
517 db,
518 run,
519 skill,
520 invoke,
521 gov,
522 filtered_answer,
523 run.inputs or {},
524 input_rules,
525 resume=resume,
526 )
529def _segment(
530 db: Session,
531 run: SkillRun,
532 skill: Skill,
533 invoke: Callable[..., dict],
534 gov: _Governance,
535 prompt: str,
536 inputs: dict[str, Any],
537 input_rules: rule_engine.RulePass,
538 *,
539 resume: dict[str, Any] | None = None,
540) -> None:
541 """Call svc-ai for one segment and record what came of it.
543 Each segment is its own ledger row: it is its own provider spend, and a
544 run left paused for a day should not hold its first half off the ledger
545 until somebody answers. So a resume's own policy pass already counts
546 what the segments before it spent, and the limit it returns — what is
547 left of the tightest budget — is the most this segment may spend
548 (``app/services/spend_limits.py``), and the web sources it sets are the
549 ones the segment's tools may use.
550 """
551 started = perf_counter()
552 with (
553 ai_client.usage_capture() as used,
554 ai_client.in_invocation(gov.invocation_id),
555 ai_client.in_turn_governance(input_rules),
556 ):
557 try:
558 data = invoke(
559 skill_id=str(skill.id),
560 graph_definition=skill_graph.resolve_for_execution(
561 skill.graph_definition, db, workspace=_run_workspace(db, run)
562 ),
563 prompt=prompt,
564 user_id=gov.user_id,
565 name=skill.name,
566 inputs=inputs,
567 rules=rule_engine.serialize_rules(
568 db,
569 gov.user_id,
570 scopes=gov.scope_chain,
571 workspace=gov.context.get(rule_engine.WORKSPACE_CONTEXT_KEY),
572 ),
573 purpose=TRACE_PURPOSE,
574 reference={"skill_id": str(skill.id), "skill_run_id": str(run.id)},
575 timeout=RUN_TIMEOUT_S,
576 resume=resume,
577 )
578 except ai_client.RuleBlockedError as exc:
579 _add_usage(run, used, perf_counter() - started)
580 run.rule_trace = [
581 *(run.rule_trace or []),
582 *rule_engine.build_block_trace_from_exc(exc),
583 ]
584 _finish(
585 db, run, Status.blocked, f"Blocked by rule '{exc.rule}': {exc.message}"
586 )
587 return
588 except ai_client.AIServiceError as exc:
589 latency = perf_counter() - started
590 _add_usage(run, used, latency)
591 usage_service.record_usage(
592 db,
593 **gov.ledger,
594 latency_ms=latency * 1000,
595 outcome=UsageEnum.Outcome.error,
596 measured=used,
597 )
598 # A budget stopped it part-way: on the record beside the row
599 # that let it start.
600 spend_limits.record_stop(exc, gov.context, gov.user_id, db=db)
601 _finish(
602 db,
603 run,
604 Status.failed,
605 exc.user_message
606 if isinstance(exc, ai_client.ModelRefusedError)
607 else str(exc),
608 )
609 return
610 latency = perf_counter() - started
611 usage = data.get("usage") or {}
612 _add_usage(
613 run,
614 used,
615 latency,
616 fallback=(
617 int(usage.get("prompt_tokens") or 0),
618 int(usage.get("completion_tokens") or 0),
619 ),
620 )
621 usage_service.record_usage(
622 db,
623 **gov.ledger,
624 input_tokens=int(usage.get("prompt_tokens") or 0),
625 output_tokens=int(usage.get("completion_tokens") or 0),
626 latency_ms=latency * 1000,
627 measured=used,
628 )
630 response_context = data.get("context") or {}
631 steps = steps_from_trace(data.get("messages"), response_context)
632 citations = list(data.get("citations") or [])
634 interrupt = data.get("interrupt")
635 if isinstance(interrupt, dict):
636 _pause(db, run, gov, interrupt, steps, citations, input_rules, data)
637 return
639 output = str(data.get("output") or "")
640 outputs = response_context.get("skill_outputs") or None
641 state = response_context.get("skill_state") or None
642 rejected = response_context.get("rejected")
644 # ── Audit ────────────────────────────────────────────────────────────
645 governed = _governed_output(output, outputs)
646 output_rules = gov.check_output(
647 db,
648 governed,
649 prompt,
650 usage_service.audit_figures(
651 latency_ms=latency * 1000,
652 measured=used,
653 input_tokens=int(usage.get("prompt_tokens") or 0),
654 output_tokens=int(usage.get("completion_tokens") or 0),
655 ),
656 )
657 if output_rules.redactor is not None:
658 output = output_rules.redact(output)
659 outputs = output_rules.redact(outputs)
660 state = output_rules.redact(state)
661 steps = output_rules.redact(steps)
662 withheld = getattr(output_rules, "withheld", None)
663 if withheld is not None:
664 # People get the rule's message; the run keeps nothing it wrote —
665 # its outputs, state, sources and each step's output — since the
666 # answer went to review alone.
667 output = output_rules.text
668 outputs = state = None
669 citations = []
670 steps = [_without_output(step) for step in steps]
671 gov.queue_flags(db, output_rules, data.get("rule_events"), output_rules.text)
673 run.output = output
674 run.outputs = outputs
675 run.state = state
676 run.steps = [*(run.steps or []), *steps] or None
677 run.citations = [*(run.citations or []), *citations] or None
678 run.rule_trace = [
679 *(run.rule_trace or []),
680 *rule_engine.build_turn_rule_trace(
681 input_rules, output_rules, data.get("rule_events")
682 ),
683 ] or None
684 _finish(db, run, Status.rejected if rejected else Status.completed)
687def _pause(
688 db: Session,
689 run: SkillRun,
690 gov: _Governance,
691 interrupt: dict[str, Any],
692 steps: list[dict],
693 citations: list[dict],
694 input_rules: rule_engine.RulePass,
695 data: dict[str, Any],
696) -> None:
697 """Record that the run is waiting for a person, and on what.
699 What it shows them — the questions a node asked, the work an approval
700 gate is holding — is model output reaching a person, so the audit rules
701 run over it first, exactly as they would over a finished answer.
702 """
703 pause = normalise_interrupt(interrupt)
704 shown = pause_text(pause)
705 output_rules = gov.check_output(db, shown, run.task)
706 pause = output_rules.redact(pause)
707 steps = output_rules.redact(steps)
708 withheld = getattr(output_rules, "withheld", None)
709 if withheld is not None:
710 # What the pause holds is withheld: the person sees the rule's
711 # message, and may still go on.
712 pause = withhold_shown(pause, pause.get("kind"), withheld.message)
713 steps = [_without_output(step) for step in steps]
714 citations = []
715 gov.queue_flags(db, output_rules, data.get("rule_events"), output_rules.text)
716 run.interrupt = pause
717 run.steps = [*(run.steps or []), *steps] or None
718 run.citations = [*(run.citations or []), *citations] or None
719 run.rule_trace = [
720 *(run.rule_trace or []),
721 *rule_engine.build_turn_rule_trace(
722 input_rules, output_rules, data.get("rule_events")
723 ),
724 ] or None
725 run.status = Status.awaiting_input.value
726 db.commit()
729def _add_usage(
730 run: SkillRun,
731 used: ai_client.UsageCapture,
732 latency_s: float,
733 fallback: tuple[int, int] = (0, 0),
734) -> None:
735 """Add one segment's measured spend to the run's running totals."""
736 run.latency_ms = int((run.latency_ms or 0) + latency_s * 1000)
737 if used.measured:
738 run.input_tokens = (run.input_tokens or 0) + used.input_tokens
739 run.output_tokens = (run.output_tokens or 0) + used.output_tokens
740 run.llm_calls = (run.llm_calls or 0) + used.calls
741 run.unpriced_calls = (run.unpriced_calls or 0) + used.unpriced_calls
742 if used.cost_usd is not None:
743 run.cost_usd = Decimal(str(run.cost_usd or 0)) + used.cost_usd
744 run.cost_detail = _merge_detail(run.cost_detail or [], used.breakdown())
745 else:
746 run.input_tokens = (run.input_tokens or 0) + fallback[0]
747 run.output_tokens = (run.output_tokens or 0) + fallback[1]
750def _merge_detail(existing: list[dict], new: list[dict]) -> list[dict]:
751 """Per-model rows summed across segments, costliest first."""
752 merged: dict[tuple[str, str], dict[str, Any]] = {
753 (r["provider"], r["model"]): dict(r) for r in existing
754 }
755 for row in new:
756 key = (row["provider"], row["model"])
757 into = merged.setdefault(
758 key,
759 {
760 **row,
761 "calls": 0,
762 "input_tokens": 0,
763 "output_tokens": 0,
764 "unpriced_calls": 0,
765 "cost_usd": None,
766 },
767 )
768 for field_name in ("calls", "input_tokens", "output_tokens", "unpriced_calls"):
769 into[field_name] = (into.get(field_name) or 0) + (row.get(field_name) or 0)
770 if row.get("cost_usd") is not None:
771 into["cost_usd"] = float(into.get("cost_usd") or 0) + float(row["cost_usd"])
772 return sorted(
773 merged.values(),
774 key=lambda r: (r["cost_usd"] is None, -(r["cost_usd"] or 0)),
775 )
778# ── Pauses ────────────────────────────────────────────────────────────────────
780#: How long a paused run waits for an answer before it is given up on. The
781#: paused state lives in svc-ai's memory, so waiting forever would hold it
782#: there forever.
783PAUSE_TTL = timedelta(hours=24)
785CLARIFICATION = hitl.CLARIFICATION
786APPROVAL = hitl.APPROVAL
787normalise_interrupt = hitl.normalise_interrupt
788pause_text = hitl.pause_text
789withhold_shown = hitl.withhold_shown
790response_text = hitl.response_text
793def validate_response(
794 pause: dict[str, Any], response: dict[str, Any]
795) -> dict[str, Any]:
796 """``hitl.validate_response``, refused the way a run refuses anything."""
797 try:
798 return hitl.validate_response(pause, response)
799 except hitl.HitlResponseInvalid as exc:
800 raise RunRefused(exc.message, exc.fields) from exc
803def respond(
804 db: Session,
805 run: SkillRun,
806 skill: Skill,
807 response: dict[str, Any],
808 actor_id: UUID,
809 *,
810 submit: Callable[[UUID], None] | None = None,
811) -> SkillRun:
812 """Record a person's answer to a paused run and carry the run on.
814 Refused (``RunRefused``) when the run is not waiting, when the answer does
815 not fit the question, or when the skill was edited while it waited: the
816 paused state is a checkpoint of the *old* graph, and resuming it on a new
817 one would run a graph nobody wrote.
818 """
819 if run.status != Status.awaiting_input.value or not run.interrupt:
820 raise RunRefused("This run is not waiting for input.")
821 current = history_service.current_version(
822 db, HistoryEnum.ResourceType.skill, skill.id
823 )
824 if run.skill_version is not None and current != run.skill_version:
825 raise RunRefused(
826 "The skill was edited while this run was paused, so it cannot be "
827 "resumed. Cancel it and start a new run."
828 )
829 cleaned = validate_response(run.interrupt, response)
830 run.responses = [
831 *(run.responses or []),
832 {
833 **cleaned,
834 "node_id": run.interrupt.get("node_id"),
835 "answered_at": utc_isoformat(aware_utcnow()),
836 "answered_by": str(actor_id),
837 },
838 ]
839 run.interrupt = {**run.interrupt, "answered": True}
840 run.status = Status.running.value
841 db.commit()
842 db.refresh(run)
843 (submit or _submit)(run.id)
844 return run
847def cancel(db: Session, run: SkillRun, reason: str | None = None) -> SkillRun:
848 """Abandon a paused run, and free the paused state svc-ai is holding."""
849 if run.status != Status.awaiting_input.value:
850 raise RunRefused("Only a run waiting for input can be cancelled.")
851 _discard(run)
852 _finish(db, run, Status.cancelled, reason)
853 return run
856def _discard(run: SkillRun) -> None:
857 thread_id = (run.interrupt or {}).get("thread_id")
858 if not thread_id:
859 return
860 try:
861 ai_client.discard_paused_run(str(thread_id))
862 except ai_client.AIServiceError:
863 logger.warning("Could not discard paused thread %s", thread_id)
866# ── Reading ───────────────────────────────────────────────────────────────────
869def _aware(value):
870 if value is None:
871 return None
872 return value if value.tzinfo else value.replace(tzinfo=aware_utcnow().tzinfo)
875def parse_utc(value: Any) -> datetime | None:
876 """A stored ISO timestamp as an aware datetime, or None."""
877 if not value:
878 return None
879 try:
880 return _aware(datetime.fromisoformat(str(value)))
881 except ValueError:
882 return None
885def expire_abandoned(db: Session, skill_id: UUID, user_id: UUID) -> int:
886 """Close runs a restart orphaned, and pauses nobody answered in time.
888 Called when runs are read, so a restart shows up as a failed run with a
889 reason rather than a spinner that never stops, and a forgotten pause
890 releases the state svc-ai holds for it.
891 """
892 now = aware_utcnow()
893 closed = 0
894 for run in (
895 db.query(SkillRun)
896 .filter(
897 SkillRun.skill_id == skill_id,
898 SkillRun.user_id == user_id,
899 SkillRun.status.in_([Status.running.value, Status.awaiting_input.value]),
900 )
901 .all()
902 ):
903 if run.status == Status.running.value:
904 if _aware(run.started_at) < now - ABANDONED_AFTER:
905 run.status = Status.failed.value
906 run.finished_at = now
907 run.error = (
908 "Abandoned: the run stopped reporting (the service restarted)."
909 )
910 closed += 1
911 continue
912 paused_at = parse_utc((run.interrupt or {}).get("paused_at")) or _aware(
913 run.started_at
914 )
915 if paused_at < now - PAUSE_TTL:
916 _discard(run)
917 run.status = Status.cancelled.value
918 run.finished_at = now
919 run.error = "Expired: nobody answered within 24 hours."
920 closed += 1
921 if closed:
922 db.commit()
923 return closed