Coverage for app / services / rules / actions.py: 95%

505 statements  

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

1""" 

2Rule actions — everything a rule can *do* once its conditions match. 

3 

4One class per action, registered against the layer it acts in 

5(``layers.py``). The evaluator asks the registry for the action rather than 

6branching on its type string, so adding rate limits, cost caps or retention windows is a class here 

7plus its parameters, not an edit to three ``match`` statements and a 

8hard-coded list in the frontend. 

9 

10Every action is a ``TextAction``: given the text under evaluation, it returns 

11an :class:`ActionOutcome` — possibly rewritten text, the events to record, and 

12possibly a decision to refuse the invocation outright. 

13 

14Actions never raise to signal a block. They return a :class:`BlockDecision` 

15and let the caller turn it into whatever its transport needs — an exception in 

16svc-core, a refusal frame in a stream — so the same action class is usable 

17from both without either knowing about the other's control flow. 

18""" 

19 

20from __future__ import annotations 

21 

22import logging 

23from abc import ABC, abstractmethod 

24from dataclasses import dataclass 

25from dataclasses import field as dataclass_field 

26from decimal import Decimal, InvalidOperation 

27from enum import StrEnum 

28from typing import Any, ClassVar 

29 

30from app.db.postgres.enums import RuleEnum, UsageEnum 

31from app.services import llm_paths 

32from app.services.rules import periods as period_registry 

33from app.services.rules import pii 

34from app.services.rules import redaction as redaction_service 

35from app.services.rules.operators import ValueType 

36from app.util import vocab, web_domains 

37 

38logger = logging.getLogger(__name__) 

39 

40 

41class Enforcement(StrEnum): 

42 """Which services can carry out an action. 

43 

44 Most actions are pure text transforms and run in both svc-core and svc-ai, 

45 so governance holds wherever execution happens. A few need state only 

46 svc-core has — the usage ledger behind rate limits and cost caps — and 

47 those must be marked, because ``serialize_rules`` strips them before 

48 forwarding a rule to svc-ai. Without that, svc-ai would warn about an 

49 unsupported action on every single invocation for a rule that is being 

50 enforced correctly, just elsewhere. 

51 """ 

52 

53 #: Runs in svc-core and svc-ai alike. 

54 both = "both" 

55 #: svc-core only — needs the usage ledger, so it is resolved before the 

56 #: request is sent and never forwarded. 

57 core_only = "core_only" 

58 

59 

60@dataclass(frozen=True) 

61class ActionParam: 

62 """One configurable parameter on an action block. 

63 

64 Surfaced in the catalogue so the rule builder can render the right input 

65 without knowing anything about the action it belongs to. 

66 """ 

67 

68 key: str 

69 label: str 

70 value_type: ValueType 

71 description: str = "" 

72 required: bool = False 

73 default: Any = None 

74 options: tuple[str, ...] = () 

75 #: The kind of resource the value names by id (``"dataset"``), so the 

76 #: builder offers a picker rather than a bare id field — and so the id 

77 #: can be checked at write time (see ``referenced_resources``). 

78 resource: str | None = None 

79 #: The catalogue section that describes ``options`` (``"pii_kinds"``), 

80 #: so the builder can show each one's label and group instead of a key. 

81 vocabulary: str | None = None 

82 #: ``(param, value)``: the parameter only means something while another 

83 #: one holds that value — a trailing window's length, for the trailing 

84 #: period — so the builder shows it only then. 

85 shown_when: tuple[str, str] | None = None 

86 #: What each item of a ``list`` is when it is more than text 

87 #: (``"domain"``), so the builder offers an input that reads it as one. 

88 item: str | None = None 

89 

90 def spec(self) -> dict[str, Any]: 

91 return { 

92 "key": self.key, 

93 "label": self.label, 

94 "value_type": self.value_type.value, 

95 "description": self.description, 

96 "required": self.required, 

97 "default": self.default, 

98 "options": list(self.options), 

99 "resource": self.resource, 

100 "vocabulary": self.vocabulary, 

101 "shown_when": ( 

102 {"param": self.shown_when[0], "value": self.shown_when[1]} 

103 if self.shown_when 

104 else None 

105 ), 

106 "item": self.item, 

107 } 

108 

109 

110@dataclass(frozen=True) 

111class BlockDecision: 

112 """An action's decision that this invocation must not proceed.""" 

113 

114 message: str 

115 

116 

117@dataclass(frozen=True) 

118class WithholdDecision: 

119 """An Output action's decision that people receive ``message`` instead of 

120 the answer. Deferred: the engine applies it after every other Output rule 

121 has run on the answer (``rule_engine.evaluate_output``), so a rule that 

122 flags or redacts the answer still sees it.""" 

123 

124 message: str 

125 #: Send the answer itself to review — the one place it is then kept. 

126 review: bool = True 

127 

128 

129@dataclass 

130class ActionOutcome: 

131 """What a text action did. 

132 

133 ``text`` is always present — an action that changes nothing returns what 

134 it was given, so callers can thread the value through a chain of actions 

135 without checking which of them were no-ops. 

136 """ 

137 

138 text: str 

139 events: list[dict] = dataclass_field(default_factory=list) 

140 block: BlockDecision | None = None 

141 #: The redaction a ``filter_pii`` / ``redact_pii`` action applied — the 

142 #: kinds it chose and the owner its placeholders are keyed to — so the 

143 #: engine can apply exactly that to whatever travels with the text (the 

144 #: conversation history, a paused run's answers, a run's outputs). 

145 redactor: pii.Redactor | None = None 

146 #: The most the invocation may spend, set by a cost cap that let it 

147 #: through: what is left of it. The engine sends the tightest to svc-ai, 

148 #: which stops the turn there (``RulePass.spend_limit``). 

149 spend_limit: Decimal | None = None 

150 #: The web sources a Tools rule sets for the run. The engine merges every 

151 #: rule's (``WebPolicy.merge``) and sends the result to svc-ai, whose web 

152 #: tools hold to it (``RulePass.web_policy``). 

153 web_policy: web_domains.WebPolicy | None = None 

154 #: An Output rule's decision to withhold the answer (``RulePass.withheld``). 

155 withhold: WithholdDecision | None = None 

156 

157 

158class Action(ABC): 

159 """Base class shared by every action, whatever it acts on.""" 

160 

161 #: Stable key stored in the action block and sent over the API. 

162 type: ClassVar[str] 

163 #: Human label for the rule builder. 

164 label: ClassVar[str] 

165 #: One line explaining the effect, surfaced in the catalogue. 

166 description: ClassVar[str] = "" 

167 #: The layer whose rules may carry this action. One key may be registered 

168 #: in two layers (``redact_pii``, in Input and in Output), one class each. 

169 layer: ClassVar[RuleEnum.Layer] 

170 #: Where this action can be enforced. See :class:`Enforcement`. 

171 enforced_in: ClassVar[Enforcement] = Enforcement.both 

172 #: Configurable parameters on the action block. 

173 params: ClassVar[tuple[ActionParam, ...]] = () 

174 

175 def summarise(self, config: dict[str, Any]) -> str: 

176 """What this block does, as a short sentence a rule's card shows 

177 ("Caps spend at $100 a month"). Read from the stored block, so a rule 

178 says what *it* does rather than what the action can do.""" 

179 return self.label 

180 

181 def problems(self, config: dict[str, Any]) -> list[str]: 

182 """Why this block cannot be kept as written, beyond what its params' 

183 types say — a domain that names no domain, say. Checked when a rule 

184 is saved (422) and when one is proposed (dropped whole).""" 

185 return [] 

186 

187 def normalise(self, config: dict[str, Any]) -> dict[str, Any]: 

188 """The block as it is stored — a pasted link kept as the domain it 

189 names, say — so a rule's card shows what the engine compares.""" 

190 return config 

191 

192 def spec(self) -> dict[str, Any]: 

193 """Catalogue entry for this action.""" 

194 return { 

195 "type": self.type, 

196 "label": self.label, 

197 "description": self.description, 

198 "layer": self.layer.value, 

199 "enforced_in": self.enforced_in.value, 

200 "params": [param.spec() for param in self.params], 

201 } 

202 

203 

204class TextAction(Action): 

205 """An action applied to the text under evaluation.""" 

206 

207 @abstractmethod 

208 def apply( 

209 self, 

210 config: dict[str, Any], 

211 text: str, 

212 context: dict[str, Any], 

213 ) -> ActionOutcome: 

214 """Act on ``text``. ``config`` is the stored action block.""" 

215 

216 

217# ── Registry ────────────────────────────────────────────────────────────────── 

218 

219_REGISTRY: dict[tuple[RuleEnum.Layer, str], Action] = {} 

220 

221 

222def register_action(cls: type[Action]) -> type[Action]: 

223 """Class decorator adding one action to the registry.""" 

224 instance = cls() 

225 key = (instance.layer, instance.type) 

226 if key in _REGISTRY: 

227 raise RuntimeError( 

228 f"Action '{instance.type}' is already registered in the " 

229 f"{instance.layer.value} layer." 

230 ) 

231 _REGISTRY[key] = instance 

232 return cls 

233 

234 

235def get_action(layer: RuleEnum.Layer, action_type: str) -> Action | None: 

236 """The action registered for ``layer``/``action_type``, if any.""" 

237 return _REGISTRY.get((layer, action_type)) 

238 

239 

240def action_types(layer: RuleEnum.Layer) -> frozenset[str]: 

241 """Every action type valid on a rule in ``layer``.""" 

242 return frozenset( 

243 action_type 

244 for registered_layer, action_type in _REGISTRY 

245 if registered_layer == layer 

246 ) 

247 

248 

249def catalogue(layer: RuleEnum.Layer | None = None) -> list[dict[str, Any]]: 

250 """Registered actions, optionally narrowed to one layer.""" 

251 return [ 

252 action.spec() 

253 for (registered_layer, _), action in _REGISTRY.items() 

254 if layer is None or registered_layer == layer 

255 ] 

256 

257 

258# ── Effect reporting ────────────────────────────────────────────────────────── 

259# 

260# Every event an action emits may carry ``changed``. Absent means True: an 

261# action like ``flag_for_review`` has done something by definition. 

262# The actions that may run and find nothing to do say so explicitly, and that 

263# flag is what separates "applied" from "ran, changed nothing" in the 

264# governance activity log — both are the rule working, and only one of them is 

265# worth drawing a reader's attention to. 

266 

267 

268def _redaction( 

269 action_type: str, text: str, config: dict[str, Any], context: dict[str, Any] 

270) -> ActionOutcome: 

271 """One redaction pass, reported as kinds and counts. 

272 

273 The event says *what kind* of PII was removed and *how many* of each — 

274 never the matched text. An audit trail quoting the addresses a rule exists 

275 to remove would be a copy of exactly what was redacted, kept for longer 

276 than the conversation it came from. 

277 """ 

278 redactor = redaction_service.for_action(config, context) 

279 redacted, counts = redactor.redact(text) 

280 event: dict[str, Any] = {"action": action_type, "changed": bool(counts)} 

281 if counts: 

282 event["redacted"] = counts 

283 return ActionOutcome(text=redacted, events=[event], redactor=redactor) 

284 

285 

286def _redaction_summary(config: dict[str, Any], where: str) -> str: 

287 """ "Redacts email addresses and phone numbers from the prompt", or the 

288 count of kinds when there are more than two, or the default set.""" 

289 raw = config.get("kinds") or [] 

290 chosen = [ 

291 str(k).strip() 

292 for k in (raw if isinstance(raw, (list, tuple)) else str(raw).split(",")) 

293 if str(k).strip() and pii.get(str(k).strip()) is not None 

294 ] 

295 if not chosen: 

296 return f"Redacts personal data from the {where}" 

297 if len(chosen) <= 2: 

298 named = " and ".join(pii.get(kind).plural for kind in chosen) 

299 return f"Redacts {named} from the {where}" 

300 return f"Redacts {len(chosen)} kinds of personal data from the {where}" 

301 

302 

303#: The parameter both redaction actions (Input's and Output's) take: which 

304#: kinds of personal data to replace. Its options are the detectors' own registry, so a kind added there 

305#: is offered here with no change to either action. 

306_KINDS_PARAM = ActionParam( 

307 key="kinds", 

308 label="What to redact", 

309 value_type=ValueType.list, 

310 description=( 

311 "The kinds of personal data to replace. Leave empty for the default " 

312 f"set: every kind except " 

313 f"{vocab.one_of([pii.get(k).plural for k in pii.KINDS if k not in pii.DEFAULT_KINDS], quote='', conjunction='and')}." 

314 ), 

315 options=pii.KINDS, 

316 vocabulary="pii_kinds", 

317) 

318 

319 

320# ── Input actions ───────────────────────────────────────────────────────────── 

321 

322 

323@register_action 

324class BlockAction(TextAction): 

325 type = "block" 

326 label = "Block the request" 

327 description = "Refuse the invocation before it reaches the model." 

328 layer = RuleEnum.Layer.input 

329 params = ( 

330 ActionParam( 

331 key="message", 

332 label="Message", 

333 value_type=ValueType.text, 

334 description="Shown to the caller in place of a response.", 

335 default="This request is not permitted.", 

336 ), 

337 ) 

338 

339 def summarise(self, config: dict[str, Any]) -> str: 

340 return "Blocks the request" 

341 

342 def apply( 

343 self, config: dict[str, Any], text: str, context: dict[str, Any] 

344 ) -> ActionOutcome: 

345 message = config.get("message") or "This request is not permitted." 

346 return ActionOutcome(text=text, block=BlockDecision(message=str(message))) 

347 

348 

349@register_action 

350class RedactPromptPiiAction(TextAction): 

351 """Input's redaction. Stored as ``filter_pii`` until migration 105 gave 

352 both layers' redactions one key.""" 

353 

354 type = "redact_pii" 

355 label = "Redact personal data" 

356 description = ( 

357 "Replace personal data in the prompt — and in the conversation history, " 

358 "attached documents and answers sent with it — with placeholders before " 

359 f"any model sees them: the {len(pii.DEFAULT_KINDS)} kinds marked default " 

360 "under 'What to redact' (kinds), or the ones chosen there." 

361 ) 

362 layer = RuleEnum.Layer.input 

363 params = (_KINDS_PARAM,) 

364 

365 def summarise(self, config: dict[str, Any]) -> str: 

366 return _redaction_summary(config, "prompt") 

367 

368 def apply( 

369 self, config: dict[str, Any], text: str, context: dict[str, Any] 

370 ) -> ActionOutcome: 

371 return _redaction(self.type, text, config, context) 

372 

373 

374# ── Access actions ──────────────────────────────────────────────────────────── 

375 

376 

377#: Context key under which the rule engine hands actions a 

378#: :class:`app.services.usage.UsageWindow`. Namespaced so it can never 

379#: collide with a registered condition field. 

380USAGE_CONTEXT_KEY = "__usage_window__" 

381 

382#: Context key under which the rule engine hands a cost cap what a turn like 

383#: this one usually costs (``usage.TurnReserveLookup``), for its ``reserve``. 

384#: Duck-typed, like the usage window: ``.reserve()`` → ``usage.TurnReserve``. 

385RESERVE_CONTEXT_KEY = "__turn_reserve__" 

386 

387 

388class QuotaShare(StrEnum): 

389 """Whose usage a quota's allowance is for.""" 

390 

391 #: One allowance, counting everyone the rule's workspace covers. 

392 shared = "shared" 

393 #: The same allowance for each member, counting their own usage alone. 

394 per_member = "per_member" 

395 

396 

397class QuotaResponse(StrEnum): 

398 """What a quota does once its allowance is used.""" 

399 

400 #: Refuse the invocation. 

401 block = "block" 

402 #: Let it through, and record that the allowance was passed — a soft 

403 #: budget, for a team that wants to know rather than to be stopped. 

404 warn = "warn" 

405 

406 

407class QuotaReserve(StrEnum): 

408 """When a cost cap with a little left lets a turn start. 

409 

410 A turn a cap lets through may spend only what is left of it: svc-ai 

411 stops it there (``X-Spend-Limit``). Started with too little left, it is 

412 cut off part-way through an answer — paid for, and of no use. 

413 """ 

414 

415 #: Start a turn only when what is left covers what a turn like it 

416 #: usually costs (``usage.typical_turn_cost``). 

417 typical = "typical" 

418 #: Start any turn while anything is left; it stops where the cap does. 

419 none = "none" 

420 

421 

422class QuotaAlert(StrEnum): 

423 """When a cost cap tells those who govern its workspace, in their inbox 

424 (``budgets/alerts.py``). Each is sent once per period.""" 

425 

426 half = "50" 

427 most = "80" 

428 used = "100" 

429 #: At the trailing week's rate it is used up before it starts again. 

430 projected = "projected" 

431 

432 

433#: How the builder names each choice — held to the enums at import. 

434QUOTA_SHARE_LABELS: dict[str, str] = { 

435 QuotaShare.shared: "One allowance, shared by everyone it covers", 

436 QuotaShare.per_member: "The same allowance for each member, separately", 

437} 

438QUOTA_RESPONSE_LABELS: dict[str, str] = { 

439 QuotaResponse.block: "Refuse further calls until it frees up", 

440 QuotaResponse.warn: "Let calls through, and record that it was passed", 

441} 

442QUOTA_RESERVE_LABELS: dict[str, str] = { 

443 QuotaReserve.typical: ( 

444 "Keep room to finish: start a turn only if what a turn usually costs is left" 

445 ), 

446 QuotaReserve.none: ( 

447 "Start any turn while anything is left; it stops where the cap does" 

448 ), 

449} 

450vocab.check(QUOTA_SHARE_LABELS, QuotaShare) 

451vocab.check(QUOTA_RESPONSE_LABELS, QuotaResponse) 

452QUOTA_ALERT_LABELS: dict[str, str] = { 

453 QuotaAlert.half: "When half is used", 

454 QuotaAlert.most: "When 80% is used", 

455 QuotaAlert.used: "When it is used up", 

456 QuotaAlert.projected: "When it is heading over before it starts again", 

457} 

458vocab.check(QUOTA_RESERVE_LABELS, QuotaReserve) 

459vocab.check(QUOTA_ALERT_LABELS, QuotaAlert) 

460 

461#: The alerts a cost cap sends when its rule names none — every cap written 

462#: before alerts existed included. 

463DEFAULT_ALERTS: tuple[str, ...] = ( 

464 QuotaAlert.most.value, 

465 QuotaAlert.used.value, 

466 QuotaAlert.projected.value, 

467) 

468 

469 

470def quota_vocabularies() -> dict[str, list[dict[str, Any]]]: 

471 """The catalogue sections the quota parameters name — what the builder 

472 shows for each choice.""" 

473 return { 

474 "quota_periods": period_registry.catalogue(), 

475 "quota_shares": [ 

476 {"key": key, "label": label} for key, label in QUOTA_SHARE_LABELS.items() 

477 ], 

478 "quota_responses": [ 

479 {"key": key, "label": label} for key, label in QUOTA_RESPONSE_LABELS.items() 

480 ], 

481 "quota_reserves": [ 

482 {"key": key, "label": label} for key, label in QUOTA_RESERVE_LABELS.items() 

483 ], 

484 "quota_alerts": [ 

485 {"key": key, "label": label} for key, label in QUOTA_ALERT_LABELS.items() 

486 ], 

487 "execution_types": [ 

488 {"key": key, "label": label} 

489 for key, label in llm_paths.EXECUTION_TYPE_LABELS.items() 

490 ], 

491 } 

492 

493 

494def _period_param(default_label: str) -> ActionParam: 

495 return ActionParam( 

496 key="period", 

497 label="Counted over", 

498 value_type=ValueType.enum, 

499 description=( 

500 f"{default_label} A calendar period (UTC) is a budget: it starts " 

501 "again from nothing at each boundary." 

502 ), 

503 default=period_registry.DEFAULT, 

504 options=period_registry.keys(), 

505 vocabulary="quota_periods", 

506 ) 

507 

508 

509def _window_param(default_seconds: int, default_label: str) -> ActionParam: 

510 return ActionParam( 

511 key="window_seconds", 

512 label="Window (seconds)", 

513 value_type=ValueType.number, 

514 description=f"How far back the trailing window reaches. {default_label}", 

515 default=default_seconds, 

516 shown_when=("period", period_registry.DEFAULT), 

517 ) 

518 

519 

520_SHARE_PARAM = ActionParam( 

521 key="share", 

522 label="Whose usage", 

523 value_type=ValueType.enum, 

524 description=( 

525 "One allowance for everyone the rule covers, or the same allowance " 

526 "for each member on their own." 

527 ), 

528 default=QuotaShare.shared.value, 

529 options=tuple(QuotaShare), 

530 vocabulary="quota_shares", 

531) 

532 

533_TYPES_PARAM = ActionParam( 

534 key="execution_types", 

535 label="Kinds of work", 

536 value_type=ValueType.list, 

537 description=( 

538 "Count only these kinds of work, and stand aside for the rest — a " 

539 "budget for evaluations alone, say. Leave empty for all of it." 

540 ), 

541 options=tuple(UsageEnum.ExecutionType), 

542 vocabulary="execution_types", 

543) 

544 

545_RESERVE_PARAM = ActionParam( 

546 key="reserve", 

547 label="With a little left", 

548 value_type=ValueType.enum, 

549 description=( 

550 "A turn may spend only what is left, and is stopped there. Keep room " 

551 "to finish, and a turn starts only when what a turn like it usually " 

552 "costs is left, rather than being cut off part-way through." 

553 ), 

554 default=QuotaReserve.typical.value, 

555 options=tuple(QuotaReserve), 

556 vocabulary="quota_reserves", 

557) 

558 

559_ALERT_PARAM = ActionParam( 

560 key="alert_at", 

561 label="Alert", 

562 value_type=ValueType.list, 

563 description=( 

564 "Tell those who govern the workspace, in their inbox, when this much " 

565 "is used or when it is heading over — once each period. Leave all " 

566 "unticked for no alerts." 

567 ), 

568 default=list(DEFAULT_ALERTS), 

569 options=tuple(QuotaAlert), 

570 vocabulary="quota_alerts", 

571) 

572 

573_ON_REACH_PARAM = ActionParam( 

574 key="on_reach", 

575 label="When it is reached", 

576 value_type=ValueType.enum, 

577 description=( 

578 "Refuse further calls, or let them through and record that the " 

579 "allowance was passed." 

580 ), 

581 default=QuotaResponse.block.value, 

582 options=tuple(QuotaResponse), 

583 vocabulary="quota_responses", 

584) 

585 

586 

587class _QuotaAction(TextAction): 

588 """Shared shape for the two actions that cap consumption. 

589 

590 Both read a total from the usage ledger and refuse the invocation once it 

591 reaches the allowance — or, set to ``warn``, let it through and record 

592 that it did. Both count over a period (``rules/periods.py``): the 

593 trailing window they always had, or a calendar day, week or month, which 

594 is what a budget is. Both may give each member their own allowance 

595 (``share``) and count only some kinds of work (``execution_types``). 

596 Both are svc-core-only: the ledger lives in ``postgres-core``, and the 

597 point of keeping it there is that a cap can be judged without a 

598 cross-service hop on the inference path. 

599 

600 Both also stand aside when the total cannot be read — no window in the 

601 context, or a failed query. Refusing a request on a number the engine 

602 never obtained would be a worse failure than allowing it: the operator 

603 gets a logged error either way, but only one of them takes the platform 

604 down when the ledger has a bad day. 

605 """ 

606 

607 layer = RuleEnum.Layer.access 

608 enforced_in = Enforcement.core_only 

609 

610 #: Default trailing window, in seconds, when the rule does not say. 

611 default_window_seconds: ClassVar[int] = 3600 

612 

613 def _window_seconds(self, config: dict[str, Any]) -> int: 

614 raw = config.get("window_seconds", self.default_window_seconds) 

615 try: 

616 seconds = int(float(raw)) 

617 except (TypeError, ValueError): 

618 logger.warning( 

619 "%s action has a non-numeric window_seconds %r — falling back to %ds", 

620 self.type, 

621 raw, 

622 self.default_window_seconds, 

623 ) 

624 return self.default_window_seconds 

625 return max(1, seconds) 

626 

627 def _limit(self, config: dict[str, Any], key: str) -> Any: 

628 raw = config.get(key) 

629 if raw is None: 

630 logger.warning( 

631 "%s action has no %s — the rule cannot be enforced and will not fire", 

632 self.type, 

633 key, 

634 ) 

635 return raw 

636 

637 def _period(self, config: dict[str, Any]) -> period_registry.Period: 

638 period = period_registry.get_period(config.get("period") or None) 

639 if period is None: 

640 if config.get("period"): 

641 logger.warning( 

642 "%s action names an unknown period %r — counting over its " 

643 "trailing window", 

644 self.type, 

645 config.get("period"), 

646 ) 

647 period = period_registry.get_period(period_registry.DEFAULT) 

648 assert period is not None 

649 return period 

650 

651 def _types(self, config: dict[str, Any]) -> tuple[str, ...]: 

652 raw = config.get("execution_types") 

653 if not raw: 

654 return () 

655 values = raw if isinstance(raw, (list, tuple)) else str(raw).split(",") 

656 return tuple(str(v).strip() for v in values if str(v).strip()) 

657 

658 def _applies(self, config: dict[str, Any], context: dict[str, Any]) -> bool: 

659 """False when the quota counts only some kinds of work and this 

660 invocation is another kind: it stands aside, as it is not counted.""" 

661 types = self._types(config) 

662 return not types or str(context.get("execution_type") or "") in types 

663 

664 def _span(self, config: dict[str, Any], now: Any) -> tuple[Any, dict[str, Any]]: 

665 """What the ledger counts for this quota, and the figures describing 

666 it on the rule's event: its period, and when it resets.""" 

667 from app.services.usage import Span 

668 from app.util.time import utc_isoformat 

669 

670 period = self._period(config) 

671 seconds = self._window_seconds(config) 

672 member = str(config.get("share") or "") == QuotaShare.per_member 

673 types = self._types(config) 

674 figures: dict[str, Any] = {"period": period.key} 

675 if period.calendar: 

676 span = Span( 

677 since=period.start(now, seconds), member=member, execution_types=types 

678 ) 

679 resets = period.resets_at(now) 

680 if resets is not None: 

681 figures["resets_at"] = utc_isoformat(resets) 

682 else: 

683 span = Span(seconds=seconds, member=member, execution_types=types) 

684 figures["window_seconds"] = seconds 

685 if member: 

686 figures["share"] = QuotaShare.per_member.value 

687 return span, figures 

688 

689 def _warns(self, config: dict[str, Any]) -> bool: 

690 return str(config.get("on_reach") or "") == QuotaResponse.warn 

691 

692 def _allowance_summary(self, config: dict[str, Any], amount: str) -> str: 

693 """ "$100 a month for each member", "50 requests per hour" — the 

694 allowance, its period and whose it is, as a summary says them.""" 

695 per = self._period(config).per(self._window_seconds(config)) 

696 member = str(config.get("share") or "") == QuotaShare.per_member 

697 return f"{amount} {per}{' for each member' if member else ''}" 

698 

699 def _reached( 

700 self, config: dict[str, Any], text: str, figures: dict[str, Any], default: str 

701 ) -> ActionOutcome: 

702 """The quota is used: refuse, or let it through and record that.""" 

703 if self._warns(config): 

704 return ActionOutcome(text=text, events=[{**figures, "warned": True}]) 

705 message = config.get("message") or default 

706 return ActionOutcome( 

707 text=text, events=[figures], block=BlockDecision(message=str(message)) 

708 ) 

709 

710 

711@register_action 

712class RateLimitAction(_QuotaAction): 

713 type = "rate_limit" 

714 label = "Limit the rate" 

715 description = ( 

716 "Refuse the invocation once this many calls have been made in the " 

717 "period. Counted against the rule's scope, so a per-agent limit is not " 

718 "consumed by another agent's traffic." 

719 ) 

720 params = ( 

721 ActionParam( 

722 key="max_invocations", 

723 label="Max invocations", 

724 value_type=ValueType.number, 

725 description="How many calls are allowed in the period.", 

726 required=True, 

727 ), 

728 _period_param("Defaults to a trailing window."), 

729 _window_param(3600, "Defaults to one hour."), 

730 _SHARE_PARAM, 

731 _TYPES_PARAM, 

732 _ON_REACH_PARAM, 

733 ActionParam( 

734 key="message", 

735 label="Message", 

736 value_type=ValueType.text, 

737 description="Shown to the caller when the limit is reached.", 

738 default="Rate limit reached. Please try again later.", 

739 ), 

740 ) 

741 

742 def summarise(self, config: dict[str, Any]) -> str: 

743 try: 

744 count = int(float(config.get("max_invocations"))) 

745 except (TypeError, ValueError): 

746 return "Limits the rate, with no limit set" 

747 allowance = self._allowance_summary( 

748 config, f"{count:,} request{'s' if count != 1 else ''}" 

749 ) 

750 if self._warns(config): 

751 return f"Warns past {allowance}" 

752 return f"Allows {allowance}" 

753 

754 def apply( 

755 self, config: dict[str, Any], text: str, context: dict[str, Any] 

756 ) -> ActionOutcome: 

757 limit = self._limit(config, "max_invocations") 

758 window = context.get(USAGE_CONTEXT_KEY) 

759 if limit is None or window is None or not self._applies(config, context): 

760 return ActionOutcome(text=text) 

761 

762 try: 

763 allowed = int(float(limit)) 

764 except (TypeError, ValueError): 

765 logger.warning( 

766 "rate_limit max_invocations %r is not a number — rule not enforced", 

767 limit, 

768 ) 

769 return ActionOutcome(text=text) 

770 

771 from app.util.time import aware_utcnow 

772 

773 span, figures = self._span(config, aware_utcnow()) 

774 used = window.count(span) 

775 if used is None: 

776 return ActionOutcome(text=text) 

777 figures = {"action": self.type, "limit": allowed, "used": used, **figures} 

778 

779 # The ledger records invocations that already happened, so this one is 

780 # the (used + 1)th. Comparing `used >= allowed` is what makes a limit 

781 # of 1 mean "one call, then refuse" rather than two. 

782 if used < allowed: 

783 return ActionOutcome(text=text, events=[{**figures, "changed": False}]) 

784 return self._reached( 

785 config, text, figures, "Rate limit reached. Please try again later." 

786 ) 

787 

788 

789#: What a cost cap tells the caller once reached, unless it says otherwise. 

790DEFAULT_CAP_MESSAGE = "Spending cap reached for this period." 

791 

792 

793@dataclass(frozen=True) 

794class CapReading: 

795 """A cost cap as it stands: what it allows, what its window has spent, 

796 and what the next invocation it governs would meet. The one reading the 

797 cap's own decision and a budget's page are both made from 

798 (``app/services/budgets``), so the page cannot say "under budget" while 

799 the cap refuses — or the reverse.""" 

800 

801 cap: Decimal 

802 #: None when the ledger could not be read: the cap stands aside. 

803 spent: Decimal | None 

804 #: The ledger rows it counts (``usage.Span``). 

805 span: Any 

806 #: Its period and reset, as its event records them. 

807 figures: dict[str, Any] 

808 #: Set to warn rather than refuse once reached. 

809 warns: bool 

810 #: What a turn must find left to start (``reserve: typical``), or None 

811 #: when the cap starts any turn while anything is left. 

812 reserve: Decimal | None = None 

813 

814 @property 

815 def reached(self) -> bool: 

816 return self.spent is not None and self.spent >= self.cap 

817 

818 @property 

819 def short(self) -> bool: 

820 """Not reached, but with less left than a turn usually costs.""" 

821 return ( 

822 not self.reached 

823 and self.spent is not None 

824 and self.reserve is not None 

825 and self.cap - self.spent < self.reserve 

826 ) 

827 

828 @property 

829 def blocks(self) -> bool: 

830 """Whether the next invocation it governs would be refused: it is 

831 reached, or too little of it is left to finish one.""" 

832 return (self.reached or self.short) and not self.warns 

833 

834 @property 

835 def remaining(self) -> Decimal | None: 

836 if self.spent is None: 

837 return None 

838 return max(self.cap - self.spent, Decimal(0)) 

839 

840 

841@register_action 

842class CostCapAction(_QuotaAction): 

843 type = "cost_cap" 

844 label = "Cap the spend" 

845 description = ( 

846 "Refuse the invocation once spend in the period reaches this amount — " 

847 "over a calendar month, a monthly budget. Spend is what each call " 

848 "cost as measured, with a high estimate for any call that could not " 

849 "be priced." 

850 ) 

851 default_window_seconds = 86_400 

852 params = ( 

853 ActionParam( 

854 key="max_usd", 

855 label="Max spend (USD)", 

856 value_type=ValueType.number, 

857 description="Spend allowed in the period.", 

858 required=True, 

859 ), 

860 _period_param("Defaults to a trailing window."), 

861 _window_param(86_400, "Defaults to one day."), 

862 _SHARE_PARAM, 

863 _TYPES_PARAM, 

864 _ON_REACH_PARAM, 

865 _RESERVE_PARAM, 

866 _ALERT_PARAM, 

867 ActionParam( 

868 key="message", 

869 label="Message", 

870 value_type=ValueType.text, 

871 description="Shown to the caller when the cap is reached.", 

872 default=DEFAULT_CAP_MESSAGE, 

873 ), 

874 ) 

875 

876 def keeps_reserve(self, config: dict[str, Any]) -> bool: 

877 """Whether the cap keeps room to finish a turn (``reserve``).""" 

878 return str(config.get("reserve") or QuotaReserve.typical) != QuotaReserve.none 

879 

880 def reading( 

881 self, 

882 config: dict[str, Any], 

883 window: Any, 

884 now: Any = None, 

885 *, 

886 reserve: Decimal | None = None, 

887 ) -> CapReading | None: 

888 """The cap as it stands against ``window`` (``usage.UsageWindow``), 

889 or None when it cannot be judged: no window, or no usable amount. 

890 

891 ``reserve`` is what a turn is expected to cost; kept only when the 

892 cap keeps room to finish one.""" 

893 limit = self._limit(config, "max_usd") 

894 if limit is None or window is None: 

895 return None 

896 try: 

897 cap = Decimal(str(limit)) 

898 except (InvalidOperation, TypeError, ValueError): 

899 logger.warning( 

900 "cost_cap max_usd %r is not a number — rule not enforced", limit 

901 ) 

902 return None 

903 from app.util.time import aware_utcnow 

904 

905 span, figures = self._span(config, now or aware_utcnow()) 

906 return CapReading( 

907 cap=cap, 

908 spent=window.spent(span), 

909 span=span, 

910 figures=figures, 

911 warns=self._warns(config), 

912 reserve=reserve if self.keeps_reserve(config) else None, 

913 ) 

914 

915 def _turn_reserve(self, config: dict[str, Any], context: dict[str, Any]) -> Any: 

916 """What a turn like this one usually costs (``usage.TurnReserve``), 

917 when the cap keeps room to finish one and the engine can say.""" 

918 lookup = context.get(RESERVE_CONTEXT_KEY) 

919 if lookup is None or not self.keeps_reserve(config): 

920 return None 

921 try: 

922 return lookup.reserve() 

923 except Exception: 

924 logger.warning("Turn reserve lookup failed — none kept", exc_info=True) 

925 return None 

926 

927 def summarise(self, config: dict[str, Any]) -> str: 

928 try: 

929 cap = Decimal(str(config.get("max_usd"))) 

930 except (InvalidOperation, ValueError, TypeError): 

931 return "Caps the spend, with no amount set" 

932 amount = f"${cap:,.0f}" if cap == cap.to_integral_value() else usd_text(cap) 

933 allowance = self._allowance_summary(config, amount) 

934 if self._warns(config): 

935 return f"Warns past {allowance}" 

936 return f"Caps spend at {allowance}" 

937 

938 def apply( 

939 self, config: dict[str, Any], text: str, context: dict[str, Any] 

940 ) -> ActionOutcome: 

941 if not self._applies(config, context): 

942 return ActionOutcome(text=text) 

943 turn = self._turn_reserve(config, context) 

944 reading = self.reading( 

945 config, 

946 context.get(USAGE_CONTEXT_KEY), 

947 reserve=turn.usd if turn is not None else None, 

948 ) 

949 if reading is None or reading.spent is None: 

950 return ActionOutcome(text=text) 

951 figures = { 

952 "action": self.type, 

953 "cap_usd": str(reading.cap), 

954 "spent_usd": str(reading.spent), 

955 **reading.figures, 

956 } 

957 if reading.short: 

958 # Something is left, but less than a turn like this one usually 

959 # costs: started, it would be stopped part-way through an answer. 

960 figures = { 

961 **figures, 

962 "remaining_usd": str(reading.cap - reading.spent), 

963 "reserve_usd": str(reading.reserve), 

964 "reserve_basis": turn.basis, 

965 } 

966 custom = config.get("message") 

967 message = ( 

968 str(custom) 

969 if custom and custom != DEFAULT_CAP_MESSAGE 

970 else short_message(reading) 

971 ) 

972 return self._reached({**config, "message": message}, text, figures, message) 

973 if not reading.reached: 

974 # Under the cap: nothing changed, but the figures go on the record 

975 # — "$31.20 of $50 this month" is what a budget's reader wants. 

976 # What is left is also the most this turn may spend: svc-ai stops 

977 # it there. A cap that only warns sets no such limit. 

978 remaining = reading.cap - reading.spent 

979 return ActionOutcome( 

980 text=text, 

981 events=[{**figures, "remaining_usd": str(remaining), "changed": False}], 

982 spend_limit=None if reading.warns else remaining, 

983 ) 

984 return self._reached(config, text, figures, DEFAULT_CAP_MESSAGE) 

985 

986 

987def usd_text(amount: Decimal) -> str: 

988 """An amount of money as a person reads it: to the cent, and "less than 

989 $0.01" rather than "$0.00" for a fraction of one.""" 

990 if amount <= 0: 

991 return "$0.00" 

992 if amount < Decimal("0.01"): 

993 return "less than $0.01" 

994 return f"${amount:,.2f}" 

995 

996 

997def resets_phrase(figures: dict[str, Any]) -> str: 

998 """When a quota's period starts again, from its event figures.""" 

999 from datetime import datetime 

1000 

1001 raw = figures.get("resets_at") 

1002 if raw: 

1003 try: 

1004 when = datetime.fromisoformat(str(raw)) 

1005 except (TypeError, ValueError): 

1006 when = None 

1007 if when is not None: 

1008 return f"It starts again on {when.day} {when:%B} (UTC)." 

1009 return "It frees up as earlier spend leaves its window." 

1010 

1011 

1012def short_message(reading: CapReading) -> str: 

1013 """Why a cap with something left refused a turn: too little to finish.""" 

1014 left = (reading.cap - reading.spent) if reading.spent is not None else Decimal(0) 

1015 return ( 

1016 "Not enough of this budget is left to finish an answer: " 

1017 f"{usd_text(left)} left, and a turn here usually costs about " 

1018 f"{usd_text(reading.reserve or Decimal(0))}. " 

1019 f"{resets_phrase(reading.figures)}" 

1020 ) 

1021 

1022 

1023#: Context key under which the rule engine hands actions an 

1024#: :class:`app.services.evaluation.evidence.EvidenceLookup`. Namespaced like 

1025#: :data:`USAGE_CONTEXT_KEY`, and duck-typed for the same reason: this module 

1026#: must not import the evaluation package, which imports the rule engine. 

1027EVIDENCE_CONTEXT_KEY = "__evaluation_evidence__" 

1028 

1029#: Execution types the evidence gate never refuses. An evaluation run *is* 

1030#: how an agent version earns its evidence; gating it on having some already 

1031#: would make a new version impossible to evaluate into compliance. 

1032UNGATED_EXECUTION_TYPES = frozenset({"evaluation"}) 

1033 

1034 

1035@register_action 

1036class RequireEvaluationAction(TextAction): 

1037 """Refuse an agent version that has no passing evaluation behind it. 

1038 

1039 Rules govern each invocation; evaluation governs each configuration. This 

1040 is where the two meet: a rule that lets an agent answer only when the 

1041 version in force has been evaluated — as configured, on a completed and 

1042 scored run — and passed. What "passed" means is 

1043 :func:`app.services.evaluation.evidence.gate_verdict`, the same reading 

1044 Governance → Evaluation → Assurance shows, so the page predicts the gate. 

1045 

1046 Stands aside for invocations with no agent (a model has no versions), 

1047 for evaluation runs (see :data:`UNGATED_EXECUTION_TYPES`), and — failing 

1048 open, like the quota actions — when the evidence cannot be read. Missing 

1049 evidence is not unreadable evidence: an agent never evaluated is refused. 

1050 """ 

1051 

1052 type = "require_evaluation" 

1053 label = "Require passing evaluations" 

1054 description = ( 

1055 "Refuse the invocation unless the agent's version in force has passed " 

1056 "an evaluation: a completed, scored run of the agent as configured " 

1057 "that reaches the dataset's pass mark without regressing. Evaluation " 

1058 "runs themselves are never refused." 

1059 ) 

1060 layer = RuleEnum.Layer.access 

1061 enforced_in = Enforcement.core_only 

1062 params = ( 

1063 ActionParam( 

1064 key="dataset_id", 

1065 label="Dataset", 

1066 value_type=ValueType.text, 

1067 description=( 

1068 "The dataset the evidence must come from. Leave empty to " 

1069 "accept any — then every dataset the version was evaluated on " 

1070 "must pass." 

1071 ), 

1072 resource="dataset", 

1073 ), 

1074 ActionParam( 

1075 key="min_score", 

1076 label="Minimum score", 

1077 value_type=ValueType.number, 

1078 description=( 

1079 "The mean score to reach, 0–1. Leave empty to use each " 

1080 "dataset's own pass mark (0.8 unless the dataset sets one)." 

1081 ), 

1082 ), 

1083 ActionParam( 

1084 key="message", 

1085 label="Message", 

1086 value_type=ValueType.text, 

1087 description="Shown to the caller when the agent is refused.", 

1088 default="This agent version has not passed its evaluation.", 

1089 ), 

1090 ) 

1091 

1092 def summarise(self, config: dict[str, Any]) -> str: 

1093 where = "on one dataset" if config.get("dataset_id") else "on every dataset run" 

1094 score = min_score_of(config) 

1095 floor = f", scoring at least {score:.0%}" if score is not None else "" 

1096 return f"Requires a passing evaluation {where}{floor}" 

1097 

1098 def apply( 

1099 self, config: dict[str, Any], text: str, context: dict[str, Any] 

1100 ) -> ActionOutcome: 

1101 agent_id = context.get("agent_id") 

1102 if not agent_id or context.get("execution_type") in UNGATED_EXECUTION_TYPES: 

1103 return ActionOutcome(text=text) 

1104 lookup = context.get(EVIDENCE_CONTEXT_KEY) 

1105 if lookup is None: 

1106 return ActionOutcome(text=text) 

1107 

1108 min_score = min_score_of(config) 

1109 dataset_id = str(config.get("dataset_id") or "").strip() or None 

1110 verdict = lookup.verdict(agent_id, dataset_id=dataset_id, min_score=min_score) 

1111 if verdict is None or verdict.allowed: 

1112 return ActionOutcome(text=text) 

1113 

1114 message = config.get("message") or ( 

1115 "This agent version has not passed its evaluation." 

1116 ) 

1117 return ActionOutcome( 

1118 text=text, 

1119 events=[ 

1120 { 

1121 "action": self.type, 

1122 "agent_version": verdict.version, 

1123 "reason": verdict.reason, 

1124 "dataset_id": dataset_id, 

1125 "min_score": min_score, 

1126 # The runs the refusal rests on, so the activity log can 

1127 # open them — the failing ones, or none when there were 

1128 # none to find. 

1129 "batch_ids": [run.batch_id for run in verdict.runs], 

1130 } 

1131 ], 

1132 block=BlockDecision(message=f"{message} {verdict.reason}".strip()), 

1133 ) 

1134 

1135 

1136def min_score_of(config: dict[str, Any]) -> float | None: 

1137 """A ``require_evaluation`` block's ``min_score``, or None for the 

1138 datasets' own pass marks. Anything that is not a score in 0–1 is 

1139 ignored, with a warning — the pass marks still apply, so an ill-formed 

1140 override never widens the gate to "anything passes".""" 

1141 raw = config.get("min_score") 

1142 if raw in (None, ""): 

1143 return None 

1144 try: 

1145 score = float(raw) 

1146 except (TypeError, ValueError): 

1147 logger.warning("require_evaluation min_score %r is not a number", raw) 

1148 return None 

1149 if not 0.0 <= score <= 1.0: 

1150 logger.warning("require_evaluation min_score %r is outside 0–1", raw) 

1151 return None 

1152 return score 

1153 

1154 

1155# ── Tools actions ───────────────────────────────────────────────────────────── 

1156# 

1157# Where an agent may look things up on the web. Each sets a ``WebPolicy`` on 

1158# the run (``ActionOutcome.web_policy``); the engine merges every Tools rule's 

1159# and svc-ai's web tools — web search, reading a page, fetching a document's 

1160# images — hold to it whatever path reached them. Resolved here, never 

1161# forwarded: svc-ai is handed the policy, not the rules. 

1162 

1163 

1164def _domains_param(description: str) -> ActionParam: 

1165 return ActionParam( 

1166 key="domains", 

1167 label="Sources", 

1168 value_type=ValueType.list, 

1169 description=( 

1170 f"{description} A domain covers its subdomains: gov.uk covers " 

1171 f"www.gov.uk and hmrc.gov.uk. Up to {web_domains.MAX_DOMAINS}." 

1172 ), 

1173 required=True, 

1174 item="domain", 

1175 ) 

1176 

1177 

1178def _truthy(value: Any) -> bool: 

1179 """A stored boolean: True, or the text the builder saves for it.""" 

1180 if isinstance(value, bool): 

1181 return value 

1182 return str(value or "").strip().lower() in {"true", "yes", "1", "on"} 

1183 

1184 

1185def _sources_text(domains: tuple[str, ...]) -> str: 

1186 """ "gov.uk and ico.org.uk", or "4 sources" when there are more than two.""" 

1187 if not domains: 

1188 return "no sources" 

1189 if len(domains) <= 2: 

1190 return " and ".join(domains) 

1191 return f"{len(domains)} sources" 

1192 

1193 

1194class _SourcesAction(TextAction): 

1195 """A Tools action: a list of domains, checked whole on save.""" 

1196 

1197 enforced_in = Enforcement.core_only 

1198 

1199 def _domains(self, config: dict[str, Any]) -> tuple[str, ...]: 

1200 return web_domains.normalise_domains(config.get("domains")) 

1201 

1202 def normalise(self, config: dict[str, Any]) -> dict[str, Any]: 

1203 return {**config, "domains": list(self._domains(config))} 

1204 

1205 def problems(self, config: dict[str, Any]) -> list[str]: 

1206 raw = config.get("domains") 

1207 invalid = web_domains.invalid_domains(raw) 

1208 found: list[str] = [ 

1209 f"'{entry}' is not a web domain (write it as example.com)" 

1210 for entry in invalid[:5] 

1211 ] 

1212 domains = self._domains(config) 

1213 if not domains and not invalid: 

1214 found.append(f"'{self.type}' needs at least one source") 

1215 if len(domains) > web_domains.MAX_DOMAINS: 

1216 found.append( 

1217 f"'{self.type}' names {len(domains)} sources; the most is " 

1218 f"{web_domains.MAX_DOMAINS}" 

1219 ) 

1220 return found 

1221 

1222 

1223@register_action 

1224class TrustedSourcesAction(_SourcesAction): 

1225 type = "trusted_sources" 

1226 label = "Prefer trusted sources" 

1227 description = ( 

1228 "Put these sources first whenever the agent searches the web — or, " 

1229 "with 'Use only these', search and read nothing else." 

1230 ) 

1231 layer = RuleEnum.Layer.tools 

1232 params = ( 

1233 _domains_param("The sources to trust."), 

1234 ActionParam( 

1235 key="only", 

1236 label="Use only these", 

1237 value_type=ValueType.boolean, 

1238 description=( 

1239 "Search and read these sources and nothing else. Off, they " 

1240 "are put first and every other source stays usable." 

1241 ), 

1242 default=False, 

1243 ), 

1244 ) 

1245 

1246 def normalise(self, config: dict[str, Any]) -> dict[str, Any]: 

1247 return {**super().normalise(config), "only": _truthy(config.get("only"))} 

1248 

1249 def summarise(self, config: dict[str, Any]) -> str: 

1250 domains = _sources_text(self._domains(config)) 

1251 if _truthy(config.get("only")): 

1252 return f"Uses only {domains} on the web" 

1253 return f"Puts {domains} first on the web" 

1254 

1255 def apply( 

1256 self, config: dict[str, Any], text: str, context: dict[str, Any] 

1257 ) -> ActionOutcome: 

1258 domains = frozenset(self._domains(config)) 

1259 only = _truthy(config.get("only")) 

1260 return ActionOutcome( 

1261 text=text, 

1262 # Applied on every request it governs: it sets the run's sources. 

1263 events=[{"action": self.type, "domains": sorted(domains), "only": only}], 

1264 web_policy=web_domains.WebPolicy( 

1265 allowed=domains if only else None, preferred=domains 

1266 ), 

1267 ) 

1268 

1269 

1270@register_action 

1271class BlockedSourcesAction(_SourcesAction): 

1272 type = "blocked_sources" 

1273 label = "Never use these sources" 

1274 description = ( 

1275 "Leave these sources out of every web search, and refuse to read " 

1276 "their pages — whatever else trusts them." 

1277 ) 

1278 layer = RuleEnum.Layer.tools 

1279 params = (_domains_param("The sources never to use."),) 

1280 

1281 def summarise(self, config: dict[str, Any]) -> str: 

1282 return f"Never uses {_sources_text(self._domains(config))} on the web" 

1283 

1284 def apply( 

1285 self, config: dict[str, Any], text: str, context: dict[str, Any] 

1286 ) -> ActionOutcome: 

1287 domains = frozenset(self._domains(config)) 

1288 return ActionOutcome( 

1289 text=text, 

1290 events=[{"action": self.type, "domains": sorted(domains)}], 

1291 web_policy=web_domains.WebPolicy(blocked=domains), 

1292 ) 

1293 

1294 

1295# ── Output actions ──────────────────────────────────────────────────────────── 

1296 

1297 

1298#: There is no ``log`` action. It wrote the rule's name to container output 

1299#: and nothing else, and the governance activity log already records every 

1300#: rule evaluated against every invocation, matched or not — so a rule's 

1301#: matches are visible with no action at all. Removed by migration 79. 

1302 

1303 

1304@register_action 

1305class RedactPiiAction(TextAction): 

1306 type = "redact_pii" 

1307 label = "Redact personal data" 

1308 description = ( 

1309 "Replace personal data in the response with placeholders — as it " 

1310 "streams, in its trace and in what is stored — before anyone sees it: " 

1311 f"the {len(pii.DEFAULT_KINDS)} kinds marked default under 'What to " 

1312 "redact' (kinds), or the ones chosen there." 

1313 ) 

1314 layer = RuleEnum.Layer.output 

1315 params = (_KINDS_PARAM,) 

1316 

1317 def summarise(self, config: dict[str, Any]) -> str: 

1318 return _redaction_summary(config, "answer") 

1319 

1320 def apply( 

1321 self, config: dict[str, Any], text: str, context: dict[str, Any] 

1322 ) -> ActionOutcome: 

1323 return _redaction(self.type, text, config, context) 

1324 

1325 

1326@register_action 

1327class FlagForReviewAction(TextAction): 

1328 type = "flag_for_review" 

1329 label = "Send to review" 

1330 description = "Put the answer in the Reviews queue for a person to look at." 

1331 layer = RuleEnum.Layer.output 

1332 params = ( 

1333 ActionParam( 

1334 key="reviewer", 

1335 label="Reviewer", 

1336 value_type=ValueType.text, 

1337 description="Who the flag is addressed to.", 

1338 default="admin", 

1339 ), 

1340 ActionParam( 

1341 key="retention_days", 

1342 label="Keep for (days)", 

1343 value_type=ValueType.number, 

1344 description=( 

1345 "Delete the flag this many days after it is raised. Leave " 

1346 "empty to keep it indefinitely." 

1347 ), 

1348 ), 

1349 ) 

1350 

1351 def summarise(self, config: dict[str, Any]) -> str: 

1352 retention = config.get("retention_days") 

1353 try: 

1354 days = int(float(retention)) if retention not in (None, "") else None 

1355 except (TypeError, ValueError): 

1356 days = None 

1357 if days: 

1358 return ( 

1359 f"Sends the answer to review, kept {days} day{'s' if days != 1 else ''}" 

1360 ) 

1361 return "Sends the answer to review" 

1362 

1363 def apply( 

1364 self, config: dict[str, Any], text: str, context: dict[str, Any] 

1365 ) -> ActionOutcome: 

1366 reviewer = config.get("reviewer") or "admin" 

1367 event: dict[str, Any] = {"action": self.type, "reviewer": str(reviewer)} 

1368 # Carried on the event rather than read from the rule later, because 

1369 # the queue row is written from the event and the rule may have been 

1370 # edited by then. The retention that applies is the one in force when 

1371 # the flag was raised. 

1372 retention = config.get("retention_days") 

1373 if retention not in (None, ""): 

1374 event["retention_days"] = retention 

1375 return ActionOutcome(text=text, events=[event]) 

1376 

1377 

1378#: What people receive in place of an answer a rule withheld, unless the 

1379#: rule says otherwise. 

1380WITHHELD_MESSAGE = "This answer was withheld by one of this workspace's rules." 

1381 

1382 

1383@register_action 

1384class WithholdAction(TextAction): 

1385 """The backstop for an answer that must not reach people as written — a 

1386 customer-facing agent's, say. Forwarded to svc-ai, which can only observe 

1387 it: while a rule like this governs a run, svc-ai keeps nothing of the 

1388 answer (memory, its trace) and svc-core shows nothing of it before the 

1389 rule has run (``app/services/withholding.py``).""" 

1390 

1391 type = "withhold" 

1392 label = "Withhold the answer" 

1393 description = ( 

1394 "Show your message instead of the answer — after every other Output " 

1395 "rule has run on it — and send the answer to review, the one place " 

1396 "it is kept. While a rule like this covers an agent, people see its " 

1397 "answers once they have been checked, not as they are written." 

1398 ) 

1399 layer = RuleEnum.Layer.output 

1400 params = ( 

1401 ActionParam( 

1402 key="message", 

1403 label="Message", 

1404 value_type=ValueType.text, 

1405 description="What people receive instead of the answer.", 

1406 default=WITHHELD_MESSAGE, 

1407 ), 

1408 ActionParam( 

1409 key="review", 

1410 label="Send the answer to review", 

1411 value_type=ValueType.boolean, 

1412 description=( 

1413 "Keep the answer for the workspace's reviewers. Off, it is " 

1414 "kept nowhere." 

1415 ), 

1416 default=True, 

1417 ), 

1418 ) 

1419 

1420 def summarise(self, config: dict[str, Any]) -> str: 

1421 if _truthy(config.get("review", True)): 

1422 return "Withholds the answer and sends it to review" 

1423 return "Withholds the answer" 

1424 

1425 def apply( 

1426 self, config: dict[str, Any], text: str, context: dict[str, Any] 

1427 ) -> ActionOutcome: 

1428 message = str(config.get("message") or WITHHELD_MESSAGE) 

1429 review = _truthy(config.get("review", True)) 

1430 return ActionOutcome( 

1431 # The text is left as it is: the engine replaces it once every 

1432 # other Output rule has run (``WithholdDecision``). 

1433 text=text, 

1434 events=[{"action": self.type, "message": message, "review": review}], 

1435 withhold=WithholdDecision(message=message, review=review), 

1436 )