Coverage for app / db / postgres / crud_schemas.py: 98%
2021 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# ---------------------------------------------------------------------------
2# Graph definition validation helpers (skill graph schema v3)
3#
4# Mirrors svc-ai's AgentFactory.from_graph_definition format. Every field
5# beyond the v1 core (agent_name/config_overrides/edges/start/end) is
6# optional, so stored v1 and v2 definitions remain valid.
7#
8# v2 added typed nodes (agent | tool | transform), a declared state block and
9# node state bindings. v3 adds typed worker interfaces (input_schema /
10# output_schema FieldSpecs), typed input bindings (``inputs``), deterministic
11# conditional edges (``branches`` with predicates over graph variables, or
12# ``route_field`` on a structured output) and a skill-level ``interface``.
13# ---------------------------------------------------------------------------
14import re as _re
15from datetime import date
16from typing import Annotated, Any, Literal
17from uuid import UUID
19from pydantic import (
20 AfterValidator,
21 BaseModel,
22 BeforeValidator,
23 EmailStr,
24 Field,
25 field_validator,
26 model_validator,
27)
29from .enums import (
30 BackgroundEnum,
31 DashboardEnum,
32 EvaluationEnum,
33 GenerationEnum,
34 GovernanceEnum,
35 HistoryEnum,
36 ReviewEnum,
37 RuleEnum,
38 RunnableEnum,
39 SimulationEnum,
40)
41from app.util import knowledge_categories, knowledge_config
42from app.util.cost_profiles import CostProfile
43from app.util.knowledge_categories import KnowledgeCategory
44from app.util.time import UTCDateTime
46_TRANSFORM_OPS = {"template", "merge", "select", "compose", "parse", "literal"}
47_FIELD_TYPES = {"string", "number", "integer", "boolean", "enum", "array", "object"}
48_UNARY_OPS = {"exists", "not_exists", "empty", "not_empty", "truthy", "falsy"}
49_BINARY_OPS = {
50 "eq",
51 "ne",
52 "gt",
53 "gte",
54 "lt",
55 "lte",
56 "in",
57 "not_in",
58 "contains",
59 "not_contains",
60 "starts_with",
61 "ends_with",
62 "matches",
63}
64_CONDITION_OPS = _UNARY_OPS | _BINARY_OPS
65_IDENT_RE = _re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
66_PATH_RE = _re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_]+)*$")
67_PLACEHOLDER_RE = _re.compile(r"\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_]+)*)\}")
68# Variables every graph can reference without declaring them.
69_IMPLICIT_VARS = {"input", "inputs"}
72def _path_root(path: str) -> str:
73 return path.split(".", 1)[0]
76def _binding_roots(value: Any) -> set[str]:
77 """Root variable names referenced by a binding value (recursive)."""
78 roots: set[str] = set()
79 if isinstance(value, str):
80 roots.update(_path_root(m) for m in _PLACEHOLDER_RE.findall(value))
81 elif isinstance(value, dict):
82 for v in value.values():
83 roots |= _binding_roots(v)
84 elif isinstance(value, list):
85 for v in value:
86 roots |= _binding_roots(v)
87 return roots
90class _FieldSpec(BaseModel):
91 """One typed field of a worker / skill interface (mirrors svc-ai FieldSpec)."""
93 name: str
94 type: str = "string"
95 description: str = ""
96 required: bool = True
97 default: Any = None
98 values: list[str] = []
99 items: str = "string"
101 @field_validator("name")
102 @classmethod
103 def _valid_name(cls, v: str) -> str:
104 if not _IDENT_RE.fullmatch(v):
105 raise ValueError(
106 f"field name {v!r} must be an identifier (letters, digits, underscore)"
107 )
108 return v
110 @field_validator("type", "items")
111 @classmethod
112 def _valid_type(cls, v: str) -> str:
113 if v not in _FIELD_TYPES:
114 raise ValueError(
115 f"unknown field type {v!r} — expected one of {sorted(_FIELD_TYPES)}"
116 )
117 return v
119 @model_validator(mode="after")
120 def _enum_values(self) -> "_FieldSpec":
121 if self.type == "enum" and not self.values:
122 raise ValueError(f"enum field {self.name!r} requires non-empty 'values'")
123 if self.type == "array" and self.items in ("array", "object", "enum"):
124 raise ValueError(f"array field {self.name!r} items must be a scalar type")
125 return self
128def _validate_field_list(fields: list[_FieldSpec], label: str) -> None:
129 seen: set[str] = set()
130 for f in fields:
131 if f.name in seen:
132 raise ValueError(f"{label} declares field {f.name!r} more than once")
133 seen.add(f.name)
136class _InterfaceOutput(BaseModel):
137 """One declared skill output: ``name`` projected from ``from`` (a path)."""
139 name: str
140 from_: str = Field(default="", alias="from")
141 description: str = ""
143 model_config = {"populate_by_name": True}
145 @field_validator("name")
146 @classmethod
147 def _valid_name(cls, v: str) -> str:
148 if not _IDENT_RE.fullmatch(v):
149 raise ValueError(f"output name {v!r} must be an identifier")
150 return v
152 @field_validator("from_")
153 @classmethod
154 def _valid_from(cls, v: str) -> str:
155 if v and not _PATH_RE.fullmatch(v):
156 raise ValueError(f"output 'from' {v!r} must be a dotted variable path")
157 return v
159 @property
160 def source(self) -> str:
161 return self.from_ or self.name
164class _InterfaceSpec(BaseModel):
165 """Skill-level typed contract."""
167 inputs: list[_FieldSpec] = []
168 outputs: list[_InterfaceOutput] = []
170 @model_validator(mode="after")
171 def _unique(self) -> "_InterfaceSpec":
172 _validate_field_list(self.inputs, "interface.inputs")
173 seen: set[str] = set()
174 for o in self.outputs:
175 if o.name in seen:
176 raise ValueError(
177 f"interface.outputs declares {o.name!r} more than once"
178 )
179 seen.add(o.name)
180 return self
183class _StateFieldSpec(BaseModel):
184 """One user-declared skill state variable."""
186 description: str = ""
187 default: Any = None
188 type: str = ""
190 @field_validator("type")
191 @classmethod
192 def _valid_type(cls, v: str) -> str:
193 if v and v not in _FIELD_TYPES:
194 raise ValueError(f"unknown state type {v!r}")
195 return v
198class _ToolNodeSpec(BaseModel):
199 """Deterministic builtin tool call for a type="tool" node."""
201 name: str
202 args: dict[str, Any] = {}
203 config: dict[str, Any] = {}
206class _NodeConfigOverrides(BaseModel):
207 """
208 Per-node overrides of the worker definition's own defaults.
210 svc-ai's ``AgentFactory.from_definition`` takes a handful of these by name
211 and merges everything else into the node's ``ModelConfig``. That made this
212 an untyped passthrough, which is the wrong shape for two of the keys:
214 * ``provider`` / ``model`` choose which model answers *this node*, so a
215 hallucinated pair from a generative flow used to reach the provider and
216 fail the run. They are checked against svc-ai's catalogue at save time.
217 * ``mcp_server_ids`` reference ``MCPServer`` rows whose ``connection_config``
218 holds credentials. Only the ids are ever stored; svc-core resolves them
219 to connection descriptors at execution time. A client may therefore not
220 send ``mcp_servers`` directly — accepting descriptors here would let a
221 request author credentials into a stored graph.
223 Unknown keys are refused rather than forwarded. They previously fell
224 through to ``ModelConfig``, which ignores what it does not recognise, so a
225 misspelt override silently did nothing for the life of the skill.
226 """
228 system_prompt: str | None = None
229 temperature: float | None = Field(default=None, ge=0.0, le=2.0)
230 max_tokens: int | None = Field(default=None, ge=1, le=200_000)
231 # svc-ai's ModelConfig.effort — Anthropic's output_config.effort and
232 # OpenAI's reasoning_effort share these names. Dropped automatically for
233 # models that do not take the control (app.services.model_capabilities).
234 effort: Literal["low", "medium", "high", "xhigh", "max"] | None = None
235 tools_enabled: bool | None = None
236 provider: str | None = None
237 model: str | None = None
238 mcp_server_ids: list[UUID] = []
240 model_config = {"extra": "forbid", "protected_namespaces": ()}
242 @model_validator(mode="before")
243 @classmethod
244 def _normalise_legacy(cls, v: Any) -> Any:
245 """Accept what earlier builders wrote, so a stored graph still saves.
247 ``effort_level`` was the builder's name for what svc-ai calls
248 ``effort``; ``enable_thinking`` was never read by anything, so it is
249 dropped rather than migrated to a field that would imply it now does
250 something.
251 """
252 if not isinstance(v, dict):
253 return v
254 v = dict(v)
255 if "mcp_servers" in v:
256 raise ValueError(
257 "mcp_servers cannot be set directly — reference servers by "
258 "mcp_server_ids and svc-core will resolve them at execution "
259 "time, so credentials are never stored in a graph."
260 )
261 legacy_effort = v.pop("effort_level", None)
262 if legacy_effort is not None and v.get("effort") is None:
263 v["effort"] = legacy_effort
264 v.pop("enable_thinking", None)
265 return {k: val for k, val in v.items() if val is not None}
268class _ApprovalGate(BaseModel):
269 """Pause for a person before a node runs (svc-ai ``GraphNode.approval``)."""
271 #: What the reviewer is asked to check.
272 message: str = Field(default="", max_length=1000)
275class _GraphNodeConfig(BaseModel):
276 """
277 One node in a skill graph.
279 type:
280 agent — full LLM invocation of a WorkerAgentDefinition.
281 tool — one deterministic builtin tool call (no LLM); ``args``
282 values may reference variables via {path} placeholders.
283 transform — pure state operation (no LLM): template | merge | select
284 | compose | parse | literal.
286 State bindings (any type):
287 output_key — write this node's result to state_vars[output_key].
288 prompt_template — (agent) replaces the default task content; {path}
289 placeholders render from graph variables.
290 input_keys — (agent) state variables surfaced as context.
292 Typed bindings (schema v3, any type):
293 inputs — worker input field → binding ("{path}" or literal).
294 input_schema — per-node override of the worker's input interface.
295 output_schema — per-node override of the worker's output interface;
296 non-empty makes the node return a structured dict.
298 Per-node behaviour (agent):
299 config_overrides — see ``_NodeConfigOverrides``. Beyond the prompt and
300 sampling controls it carries ``provider``/``model``
301 (which model answers this node) and
302 ``mcp_server_ids`` (which MCP servers' tools it can
303 reach), both validated at save time.
304 """
306 type: Literal["agent", "tool", "transform"] = "agent"
307 # agent nodes
308 agent_name: str = ""
309 config_overrides: _NodeConfigOverrides = Field(
310 default_factory=lambda: _NodeConfigOverrides()
311 )
312 prompt_template: str = ""
313 input_keys: list[str] = []
314 # tool nodes
315 tool: _ToolNodeSpec | None = None
316 # transform nodes
317 operation: dict[str, Any] | None = None
318 # any type
319 output_key: str = ""
320 description: str = ""
321 inputs: dict[str, Any] = {}
322 input_schema: list[_FieldSpec] | None = None
323 output_schema: list[_FieldSpec] | None = None
324 # Human in the loop. ``approval`` pauses the run *before* this node and
325 # shows the work so far; rejecting stops the run. ``ask_user`` lets an
326 # agent node put clarifying questions to the person running it.
327 approval: _ApprovalGate | None = None
328 ask_user: bool = False
330 @field_validator("output_key")
331 @classmethod
332 def _valid_output_key(cls, v: str) -> str:
333 if v and not _IDENT_RE.fullmatch(v):
334 raise ValueError(f"output_key {v!r} must be an identifier")
335 return v
337 @model_validator(mode="after")
338 def validate_by_type(self) -> "_GraphNodeConfig":
339 if self.type == "agent" and not self.agent_name:
340 raise ValueError("agent nodes require 'agent_name'")
341 if self.type == "tool" and (self.tool is None or not self.tool.name):
342 raise ValueError("tool nodes require 'tool.name'")
343 if self.type == "transform":
344 op = (self.operation or {}).get("op", "")
345 if op not in _TRANSFORM_OPS:
346 raise ValueError(
347 f"transform nodes require 'operation.op' to be one of "
348 f"{sorted(_TRANSFORM_OPS)}, got {op!r}"
349 )
350 for name in self.inputs:
351 if not _IDENT_RE.fullmatch(name):
352 raise ValueError(f"inputs key {name!r} must be an identifier")
353 if self.ask_user and self.type != "agent":
354 raise ValueError(
355 "only agent nodes can ask the user questions — a tool or "
356 "transform node calls no model to ask with"
357 )
358 if self.input_schema is not None:
359 _validate_field_list(self.input_schema, "input_schema")
360 if self.output_schema is not None:
361 _validate_field_list(self.output_schema, "output_schema")
362 return self
364 def referenced_roots(self) -> set[str]:
365 """Root variables this node's typed bindings and tool args reference."""
366 roots = _binding_roots(self.inputs)
367 if self.tool is not None:
368 roots |= _binding_roots(self.tool.args)
369 if self.operation:
370 op = self.operation
371 if op.get("op") == "template":
372 roots |= _binding_roots(op.get("template", ""))
373 elif op.get("op") == "merge":
374 roots |= {_path_root(str(k)) for k in op.get("keys", []) if k}
375 elif op.get("op") in ("select", "parse") and op.get("key"):
376 roots.add(_path_root(str(op["key"])))
377 elif op.get("op") == "compose":
378 roots |= _binding_roots(op.get("fields") or {})
379 return roots
382class _Condition(BaseModel):
383 """A routing predicate — a leaf comparison or all / any / not composition."""
385 var: str | None = None
386 op: str | None = None
387 value: Any = None
388 all: list["_Condition"] | None = None
389 any: list["_Condition"] | None = None
390 not_: "_Condition | None" = Field(default=None, alias="not")
392 model_config = {"populate_by_name": True}
394 @model_validator(mode="after")
395 def _shape(self) -> "_Condition":
396 composites = [c for c in (self.all, self.any, self.not_) if c is not None]
397 if len(composites) > 1:
398 raise ValueError("a condition may use only one of all / any / not")
399 if composites:
400 if self.var is not None or self.op is not None:
401 raise ValueError("composite conditions cannot also set var/op")
402 if isinstance(composites[0], list) and not composites[0]:
403 raise ValueError("all/any require at least one sub-condition")
404 return self
405 if not self.var:
406 raise ValueError("leaf conditions require 'var'")
407 if not _PATH_RE.fullmatch(self.var):
408 raise ValueError(f"invalid variable path {self.var!r}")
409 if self.op not in _CONDITION_OPS:
410 raise ValueError(
411 f"unknown op {self.op!r} — expected one of {sorted(_CONDITION_OPS)}"
412 )
413 if self.op in _BINARY_OPS and self.value is None:
414 raise ValueError(f"op {self.op!r} requires a 'value'")
415 return self
417 def referenced_paths(self) -> list[str]:
418 if self.all:
419 return [p for c in self.all for p in c.referenced_paths()]
420 if self.any:
421 return [p for c in self.any for p in c.referenced_paths()]
422 if self.not_:
423 return self.not_.referenced_paths()
424 return [self.var] if self.var else []
427_Condition.model_rebuild()
430class _BranchSpec(BaseModel):
431 """One ordered branch of a conditional edge."""
433 key: str
434 target: str
435 when: _Condition | None = None
436 description: str = ""
438 @field_validator("key", "target")
439 @classmethod
440 def _non_empty(cls, v: str) -> str:
441 if not v or not v.strip():
442 raise ValueError("branch key and target must be non-empty")
443 return v
446class _ConditionalEdgeConfig(BaseModel):
447 """
448 Conditional routing from a single source node — three forms:
450 branches (v3) — ordered predicates over graph variables; the first
451 ``when`` that holds wins, else ``default``.
452 route_field — read a field of the source's structured output and
453 map it through ``edge_map`` (keys = ``route_keys``).
454 legacy router — ``route_keys`` become RouterAgent.candidates and
455 ``edge_map`` maps the LLM's choice to a target.
457 Every target may be a node id or ``"end"``.
458 """
460 branches: list[_BranchSpec] = []
461 default: str = ""
462 route_field: str = ""
463 route_keys: list[str] = []
464 edge_map: dict[str, str] = {}
466 @model_validator(mode="after")
467 def validate_keys(self) -> "_ConditionalEdgeConfig":
468 if self.branches:
469 seen: set[str] = set()
470 for b in self.branches:
471 if b.key in seen:
472 raise ValueError(f"branch key {b.key!r} is declared more than once")
473 seen.add(b.key)
474 return self
475 if not self.route_keys:
476 raise ValueError(
477 "conditional edge requires either 'branches' or non-empty 'route_keys'"
478 )
479 if self.route_field and not _PATH_RE.fullmatch(self.route_field):
480 raise ValueError(f"route_field {self.route_field!r} must be a dotted path")
481 extra = set(self.edge_map.keys()) - set(self.route_keys)
482 if extra:
483 raise ValueError(
484 f"edge_map contains keys not in route_keys: {sorted(extra)}"
485 )
486 if not self.edge_map:
487 raise ValueError("edge_map must map at least one route key to a target")
488 return self
490 def targets(self) -> list[str]:
491 out = [b.target for b in self.branches] + list(self.edge_map.values())
492 if self.default:
493 out.append(self.default)
494 return out
496 def referenced_paths(self) -> list[str]:
497 return [p for b in self.branches if b.when for p in b.when.referenced_paths()]
500class _GraphDefinitionSchema(BaseModel):
501 """
502 Validates the structure of a Skill's graph_definition JSON blob.
504 Validates that:
505 - Referenced start/end nodes exist
506 - Every edge endpoint references an existing node (fan-out/fan-in is
507 expressed by listing multiple edges from/to the same node)
508 - Conditional edge sources and every branch / edge_map / default target
509 exist (or are "end"); branch predicates are well-formed
510 - Variable references (node ``inputs`` bindings, tool args, transform
511 keys, condition ``var`` paths, interface output sources) resolve to a
512 declared state key, a node output_key, a node id, an interface input,
513 or the implicit ``input`` variable
514 - Node state bindings (input_keys) reference resolvable state keys
515 - Complete graphs (start_node + end_nodes set): every node is reachable
516 from an entry point, and node-produced references come from strict
517 ancestors (skipped when conditional edges make ordering dynamic)
518 """
520 state: dict[str, _StateFieldSpec] = {}
521 nodes: dict[str, _GraphNodeConfig]
522 edges: list[list[str]] = []
523 start_node: str = ""
524 end_nodes: list[str] = []
525 conditional_edges: dict[str, _ConditionalEdgeConfig] = {}
526 interface: _InterfaceSpec | None = None
528 @model_validator(mode="after")
529 def validate_graph_structure(self) -> "_GraphDefinitionSchema":
530 node_ids = set(self.nodes.keys())
531 if not node_ids:
532 return self # allow empty graph (draft)
533 for nid in node_ids:
534 if not _IDENT_RE.fullmatch(nid):
535 raise ValueError(
536 f"node id {nid!r} must be an identifier (letters, digits, underscore) "
537 "so it can be referenced as a variable"
538 )
539 if self.start_node and self.start_node not in node_ids:
540 raise ValueError(f"start_node '{self.start_node}' not found in nodes")
541 for en in self.end_nodes:
542 if en not in node_ids:
543 raise ValueError(f"end_node '{en}' not found in nodes")
544 for edge in self.edges:
545 if len(edge) != 2:
546 raise ValueError(f"edge {edge} must be a [from, to] pair")
547 src, tgt = edge
548 if src not in node_ids:
549 raise ValueError(f"edge source '{src}' not found in nodes")
550 if tgt != "end" and tgt not in node_ids:
551 raise ValueError(f"edge target '{tgt}' not found in nodes")
552 for src, ce in self.conditional_edges.items():
553 if src not in node_ids:
554 raise ValueError(f"conditional_edge source '{src}' not found in nodes")
555 for tgt in ce.targets():
556 if tgt != "end" and tgt not in node_ids:
557 raise ValueError(
558 f"conditional_edge '{src}' target '{tgt}' not found in nodes"
559 )
560 if ce.route_field:
561 src_node = self.nodes[src]
562 if src_node.type == "agent" and src_node.output_schema is not None:
563 names = {f.name for f in src_node.output_schema}
564 if _path_root(ce.route_field) not in names:
565 raise ValueError(
566 f"conditional_edge '{src}' route_field "
567 f"'{ce.route_field}' is not a field of the node's output_schema"
568 )
570 # Variable namespace every reference must resolve into.
571 declared_state = set(self.state.keys())
572 output_keys = {n.output_key for n in self.nodes.values() if n.output_key}
573 interface_inputs = (
574 {f.name for f in self.interface.inputs} if self.interface else set()
575 )
576 available = (
577 declared_state | output_keys | node_ids | interface_inputs | _IMPLICIT_VARS
578 )
580 for node_id, node in self.nodes.items():
581 unknown = set(node.input_keys) - available
582 if unknown:
583 raise ValueError(
584 f"node '{node_id}' input_keys reference undeclared state "
585 f"keys {sorted(unknown)} — declare them in 'state' or bind "
586 f"a node output_key to them"
587 )
588 unknown = node.referenced_roots() - available
589 if unknown:
590 raise ValueError(
591 f"node '{node_id}' references unknown variables {sorted(unknown)} "
592 "— bindings may use 'input', declared state keys, node "
593 "output_keys, node ids, or interface inputs"
594 )
595 if node_id in node.referenced_roots():
596 raise ValueError(f"node '{node_id}' cannot reference its own output")
597 for src, ce in self.conditional_edges.items():
598 unknown = {_path_root(p) for p in ce.referenced_paths()} - available
599 if unknown:
600 raise ValueError(
601 f"conditional_edge '{src}' conditions reference unknown "
602 f"variables {sorted(unknown)}"
603 )
604 if self.interface:
605 for out in self.interface.outputs:
606 if _path_root(out.source) not in available:
607 raise ValueError(
608 f"interface output '{out.name}' source '{out.source}' "
609 "does not resolve to a state key, node id or output_key"
610 )
612 # Executability checks apply only to graphs that claim to be complete
613 # (both start_node and end_nodes set) — partial drafts pass through.
614 if not self.start_node or not self.end_nodes:
615 return self
617 # Adjacency over plain edges plus conditional edge targets ("end" is
618 # a termination marker, not a node).
619 adjacency: dict[str, set[str]] = {nid: set() for nid in node_ids}
620 for src, tgt in self.edges:
621 if tgt != "end":
622 adjacency[src].add(tgt)
623 for src, ce in self.conditional_edges.items():
624 for tgt in ce.targets():
625 if tgt != "end":
626 adjacency[src].add(tgt)
628 # Reachability — every node must be reachable from an entry point or
629 # it can never execute. Entry points are the start_node plus any node
630 # with no incoming edges (parallel sources of a fan-out).
631 has_incoming: set[str] = set()
632 for targets in adjacency.values():
633 has_incoming.update(targets)
634 roots = {self.start_node} | (node_ids - has_incoming)
635 reachable: set[str] = set()
636 frontier: list[str] = list(roots)
637 while frontier:
638 current = frontier.pop()
639 if current in reachable:
640 continue
641 reachable.add(current)
642 frontier.extend(adjacency[current])
643 unreachable = sorted(node_ids - reachable)
644 if unreachable:
645 raise ValueError(
646 f"nodes unreachable from any entry point "
647 f"(start_node '{self.start_node}' or a node without incoming "
648 f"edges): {unreachable}"
649 )
651 # Dataflow — a node-produced value must come from a strict ancestor;
652 # a value written by a later or parallel node renders empty at
653 # runtime. Skipped when conditional edges are present: dynamic
654 # routing makes node ordering undecidable statically.
655 if not self.conditional_edges:
656 producer_by_key: dict[str, str] = {}
657 for nid, n in self.nodes.items():
658 if not n.output_key:
659 continue
660 if n.output_key in producer_by_key:
661 raise ValueError(
662 f"output_key '{n.output_key}' is written by more than one node"
663 )
664 producer_by_key[n.output_key] = nid
666 def _descendants(root: str) -> set[str]:
667 seen: set[str] = set()
668 stack = list(adjacency[root])
669 while stack:
670 current = stack.pop()
671 if current in seen:
672 continue
673 seen.add(current)
674 stack.extend(adjacency[current])
675 return seen
677 for node_id, node in self.nodes.items():
678 refs = set(node.input_keys) | node.referenced_roots()
679 for key in refs:
680 if (
681 key in _IMPLICIT_VARS
682 or key in declared_state
683 or key in interface_inputs
684 ):
685 continue
686 producer = producer_by_key.get(key) or (
687 key if key in node_ids else None
688 )
689 if (
690 producer
691 and producer != node_id
692 and node_id not in _descendants(producer)
693 ):
694 raise ValueError(
695 f"node '{node_id}' references '{key}', produced "
696 f"by '{producer}', which does not run before it"
697 )
698 return self
701def _validate_interface_schema(v: list[dict] | None) -> list[dict] | None:
702 """Validate a worker input/output schema; returns the normalised list."""
703 if v is None:
704 return None
705 try:
706 fields = [f if isinstance(f, _FieldSpec) else _FieldSpec(**f) for f in v]
707 _validate_field_list(fields, "interface")
708 except Exception as exc:
709 raise ValueError(f"invalid interface schema: {exc}") from exc
710 return [f.model_dump() for f in fields]
713# ---------------------------------------------------------------------------
714# Ownership mixin for Pydantic schemas
715# ---------------------------------------------------------------------------
718class _OwnerFields(BaseModel):
719 """Exactly one of these must be set — mirrors the DB CheckConstraint."""
721 owner_user_id: UUID | None = None
722 owner_organisation_id: UUID | None = None
723 owner_project_id: UUID | None = None
726class _GenerationTag(BaseModel):
727 """AI-generation flag surfaced on Read schemas, plus the run behind it.
729 ``is_ai_generated`` tolerates None because the column default is applied
730 at flush — an unflushed ORM instance still carries None.
732 ``generation_id`` is served alongside the flag rather than only on the
733 version trail. "This was generated" is not an answer on its own: a reader
734 looking at the resource needs the invocation — the flow, the arguments and
735 the model — without first having to open its history and find the version
736 that happens to carry the id. It resolves through
737 ``GET /app/generations/{id}``.
738 """
740 is_ai_generated: bool = False
741 generation_id: UUID | None = None
743 @field_validator("is_ai_generated", mode="before")
744 @classmethod
745 def default_flag(cls, v: Any) -> Any:
746 return False if v is None else v
749class _SystemTag(BaseModel):
750 """Whether the row is platform-managed — CHAINR Bot, its guide, a
751 built-in skillset and its skills, a gold dataset, a built-in rule, a
752 built-in dashboard or a platform benchmark experiment.
753 Readable by every user, changeable by none; clients use it to render the
754 row read-only and apart from what the user built.
756 Read-only by construction: no ``Create`` / ``Update`` schema carries it,
757 so a client cannot claim it. Tolerates None for the reason
758 ``is_ai_generated`` does: the column default is applied at flush.
759 """
761 is_system: bool = False
763 @field_validator("is_system", mode="before")
764 @classmethod
765 def default_system(cls, v: Any) -> Any:
766 return False if v is None else v
769class _WorkspaceTag(BaseModel):
770 """Where a row sits relative to the workspace it was listed in
771 (``app/services/workspace.py``). Set only on a listing that names a
772 workspace (``?workspace=``); None otherwise.
774 ``origin`` is why it is in that workspace — ``own``, ``inherited`` from
775 the project's parent, ``required`` (a parent rule that applies to every
776 project, or this one), or ``built_in``. ``home_workspace`` is the key of
777 the workspace that owns it (None for a built-in), so a client can render
778 an inherited row read-only and say whose it is.
779 """
781 origin: Literal["own", "inherited", "required", "built_in"] | None = None
782 home_workspace: str | None = None
783 #: The row it was copied from, and that row's version then
784 #: (``app/services/copying.py``); None when it was not a copy.
785 cloned_from_id: UUID | None = None
786 cloned_from_version: int | None = None
789class _GenerationFields(_GenerationTag):
790 """Provenance for resources creatable by the generative setup flow."""
792 generated_by_agent_id: UUID | None = None
795class _ExperimentVariantCreate(BaseModel):
796 """A variant's own fields — what ``POST .../variants`` takes, and what an
797 experiment's create body may carry inline. Module-level so the two can
798 share it: a nested class cannot be referenced before its parent exists.
799 """
801 name: str
802 prompt: str | None = None
803 config: dict | None = None
806#: Criteria items per dataset or case, and facts per case.
807MAX_CRITERIA = 30
808MAX_FACTS = 20
811#: What a case expects the agent to do — ``criteria.BEHAVIOURS``' keys.
812ExpectedBehaviour = Literal["answer", "clarify", "decline"]
815class CriterionItem(BaseModel):
816 """One thing a good answer does. A ``gate`` fails the case when unmet."""
818 text: str = Field(min_length=1, max_length=1000)
819 gate: bool = False
822def _criteria_items(value: Any) -> Any:
823 """Accept criteria as items, strings, or one block of text (older clients
824 and imports wrote text) — normalised by the one function that reads them
825 everywhere else."""
826 from app.services.evaluation.criteria import items
828 return None if value is None else items(value)
831#: Criteria as ``[{text, gate}]``; text and plain strings are read as items.
832CriteriaField = Annotated[
833 Annotated[list[CriterionItem], Field(max_length=MAX_CRITERIA)] | None,
834 BeforeValidator(_criteria_items),
835]
838#: A dataset's pass mark: a mean score between 0 and 1, or None for the
839#: platform default.
840PassMark = Annotated[float | None, Field(ge=0.0, le=1.0)]
843class CaseFact(BaseModel):
844 """Something a correct answer states, checked by code.
846 ``value`` is a number (matched within ``tolerance_pct``, default 1%) or
847 text / a list of accepted spellings (matched case-insensitively).
848 """
850 label: str | None = Field(default=None, max_length=200)
851 value: float | str | list[str]
852 tolerance_pct: float | None = Field(default=None, ge=0, le=100)
853 gate: bool = False
856def _validated_expectation(value: Any) -> Any:
857 """Checks with their ``facts`` validated, so a malformed fact is a 422
858 rather than a check that silently never runs."""
859 if not isinstance(value, dict) or "facts" not in value:
860 return value
861 raw = value["facts"]
862 if not isinstance(raw, list):
863 # ValueError, not TypeError: pydantic turns only ValueError into a 422.
864 raise ValueError("expectation.facts must be a list.") # noqa: TRY004
865 if len(raw) > MAX_FACTS:
866 raise ValueError(f"A case holds at most {MAX_FACTS} facts.")
867 checked = [
868 CaseFact.model_validate(entry).model_dump(exclude_none=True) for entry in raw
869 ]
870 return {**value, "facts": checked}
873ExpectationField = Annotated[dict | None, AfterValidator(_validated_expectation)]
875#: Graded examples a case may carry. Enough to anchor a scale at several
876#: points; few enough that every judge call can include all of them.
877MAX_CASE_EXAMPLES = 8
880class CaseExample(BaseModel):
881 """One answer graded in advance — a point on the judge's scale."""
883 output: str = Field(min_length=1, max_length=8000)
884 score: float = Field(ge=0.0, le=1.0)
885 #: Why it earns that score. Shown to the judge beside the answer.
886 note: str | None = Field(default=None, max_length=2000)
889class _TestCaseCreate(BaseModel):
890 """A case's own fields — what ``POST .../cases`` takes, and what an
891 evaluation's create body may carry to make a dataset alongside."""
893 name: str | None = None
894 input: dict
895 expected_output: str | None = None
896 #: What a good answer to this question must do, as items. Added to the
897 #: dataset's criteria.
898 criteria: CriteriaField = None
899 #: Answers graded in advance.
900 examples: list[CaseExample] | None = Field(
901 default=None, max_length=MAX_CASE_EXAMPLES
902 )
903 #: What the agent should do: answer, ask for clarification, or decline.
904 expected_behaviour: ExpectedBehaviour | None = None
905 #: Mechanical checks: ``format``, ``schema``, ``must_contain``,
906 #: ``must_not_contain``, ``pattern``.
907 expectation: ExpectationField = None
908 #: The situation the question arrives in: ``history``, ``variables``.
909 situation: dict | None = None
910 tags: list | None = None
913#: The longest cost-centre code (``organisations`` / ``projects``, migration 100).
914COST_CENTRE_MAX = 64
917def _cost_centre(value: Any) -> Any:
918 """A cost-centre code as stored: trimmed, blank for none, at most
919 :data:`COST_CENTRE_MAX` characters."""
920 if value is None:
921 return None
922 if not isinstance(value, str):
923 raise ValueError("A cost centre is text")
924 code = value.strip()
925 if not code:
926 return None
927 if len(code) > COST_CENTRE_MAX:
928 raise ValueError(f"A cost centre is at most {COST_CENTRE_MAX} characters")
929 return code
932class Schema:
933 class User:
934 class Base(BaseModel):
935 email: EmailStr
936 name: str | None = None
938 class Create(Base):
939 auth0_id: str
941 class Update(BaseModel):
942 email: EmailStr | None = None
943 name: str | None = None
944 is_active: bool | None = None
946 class Read(Base):
947 id: UUID
948 auth0_id: str
950 email_verified: bool
951 is_active: bool
952 is_superuser: bool
953 #: Assigned in Auth0 (app/services/platform_roles.py); a user can
954 #: neither set nor change them here.
955 platform_roles: list[str] = []
957 created_at: UTCDateTime
958 updated_at: UTCDateTime
960 @field_validator("platform_roles", mode="before")
961 @classmethod
962 def none_is_no_roles(cls, value: Any) -> Any:
963 # A row not yet flushed has no column default applied.
964 return [] if value is None else value
966 class Config:
967 from_attributes = True
969 class Organisation:
970 class Base(BaseModel):
971 name: str
972 auth0_org_id: str | None = None
973 #: What finance files its spend under (a cost centre, a budget
974 #: line): at most 64 characters, blank for none.
975 cost_centre: str | None = None
977 @field_validator("cost_centre", mode="before")
978 @classmethod
979 def check_cost_centre(cls, value: Any) -> Any:
980 return _cost_centre(value)
982 class Create(Base):
983 pass
985 class Update(BaseModel):
986 name: str | None = None
987 auth0_org_id: str | None = None
988 cost_centre: str | None = None
990 @field_validator("cost_centre", mode="before")
991 @classmethod
992 def check_cost_centre(cls, value: Any) -> Any:
993 return _cost_centre(value)
995 class Read(Base):
996 id: UUID
997 created_at: UTCDateTime
999 class Config:
1000 from_attributes = True
1002 class Project:
1003 class Base(_OwnerFields):
1004 name: str
1005 description: str | None = None
1006 #: What finance files its spend under, as an organisation's.
1007 cost_centre: str | None = None
1009 @field_validator("cost_centre", mode="before")
1010 @classmethod
1011 def check_cost_centre(cls, value: Any) -> Any:
1012 return _cost_centre(value)
1014 class Create(Base):
1015 pass
1017 class Update(BaseModel):
1018 name: str | None = None
1019 description: str | None = None
1020 cost_centre: str | None = None
1022 @field_validator("cost_centre", mode="before")
1023 @classmethod
1024 def check_cost_centre(cls, value: Any) -> Any:
1025 return _cost_centre(value)
1027 class Read(Base):
1028 id: UUID
1029 created_at: UTCDateTime
1031 class Config:
1032 from_attributes = True
1034 class Provider:
1035 class Base(BaseModel):
1036 name: str
1037 display_name: str
1038 base_url: str | None = None
1039 is_enabled: bool = True
1040 config: dict | None = None
1042 class Read(Base):
1043 id: UUID
1044 created_at: UTCDateTime
1045 updated_at: UTCDateTime
1047 class Config:
1048 from_attributes = True
1050 class ChatMessageSegment:
1051 class Read(BaseModel):
1052 id: UUID
1053 message_id: UUID
1054 worker_slug: str
1055 content: str
1056 sequence: int
1058 class Config:
1059 from_attributes = True
1061 class Model:
1062 """
1063 Read-only view of a model sourced from svc-ai.
1064 svc-core no longer manages model records locally.
1065 """
1067 class Read(BaseModel):
1068 id: UUID
1069 provider_id: UUID
1070 model_name: str
1071 display_name: str | None = None
1072 description: str | None = None
1073 is_chat: bool = True
1074 is_embedding: bool = False
1075 is_vision: bool = False
1076 is_available: bool = True
1077 is_default: bool = False
1078 is_recommended: bool = False
1079 context_window: int | None = None
1080 max_output_tokens: int | None = None
1081 # Pricing, residency and the comparative bands svc-ai records.
1082 # This schema is what ``GET /app/models/{id}`` returns, so a field
1083 # missing here is a field the models page cannot show however
1084 # faithfully svc-ai serves it — cost and data_region were absent
1085 # and rendered as em dashes on every model's detail page.
1086 # Typed as strings/plain values rather than svc-ai's enums: these
1087 # are svc-ai's records, and svc-core should not fail to pass one
1088 # through because a new band was added upstream.
1089 input_cost_per_token: str | None = None
1090 output_cost_per_token: str | None = None
1091 # The rest of svc-ai's price card: cache read / write rates and
1092 # the long-context tier (svc-ai services/provider_usage.py).
1093 cache_read_cost_per_token: str | None = None
1094 cache_write_cost_per_token: str | None = None
1095 cache_write_1h_cost_per_token: str | None = None
1096 long_context_threshold: int | None = None
1097 long_context_input_multiplier: str | None = None
1098 long_context_output_multiplier: str | None = None
1099 data_region: str | None = None
1100 effort: str | None = None
1101 latency: str | None = None
1102 knowledge_cutoff: date | None = None
1103 # Which request controls the model honours, from svc-ai's
1104 # capability table. None when svc-ai did not say (an older
1105 # svc-ai, or a row read without its provider).
1106 supports_temperature: bool | None = None
1107 supports_effort: bool | None = None
1108 # Whose service runs the model on this deployment: the vendor's
1109 # API (``direct``) or Amazon Bedrock (``bedrock``). The provider
1110 # stays the model's vendor either way, so Settings → Data names
1111 # who receives a prompt from this.
1112 inference_backend: str | None = None
1113 # Default inference settings (temperature, max_tokens, top_p),
1114 # not credentials — svc-ai keeps no secrets on this row. The
1115 # detail page renders a Configuration section from it, which
1116 # could not appear while the field was omitted here.
1117 config: dict | None = None
1118 # Set when svc-ai took the model out of the catalogue. Archived
1119 # models reach svc-core only from a read that asked for them, to
1120 # name what old conversations and traces ran on.
1121 archived_at: UTCDateTime | None = None
1123 class Config:
1124 from_attributes = True
1126 class ReadWithProvider(Read):
1127 provider: "Schema.Provider.Read"
1129 class Prompt(BaseModel):
1130 prompt: str
1131 conversation_id: UUID | None = None
1132 system_messages: list[str] = []
1134 class Agent:
1135 class Base(_OwnerFields):
1136 name: str
1137 description: str | None = None
1138 # Presentation, chosen in the UI and mirrored from Dashboard:
1139 # a lucide icon name and an accent key. Unknown values fall back
1140 # client-side, so neither is validated against a closed set here.
1141 icon: str | None = None
1142 accent: str | None = None
1143 system_prompt: str
1144 tools: list[dict] | None = None
1145 config: dict | None = None
1146 ai_model_id: UUID | None = None
1147 # Ask clarifying questions in chat when a request's scope is
1148 # ambiguous, before any work starts (see Agent.clarify_scope).
1149 clarify_scope: bool = True
1150 # How much pipeline work a turn does (Agent.cost_profile).
1151 cost_profile: CostProfile = CostProfile.thorough
1152 created_at: UTCDateTime | None = None
1154 @field_validator("cost_profile", mode="before")
1155 @classmethod
1156 def _no_profile_is_the_default(cls, value: Any) -> Any:
1157 # A row not yet flushed has not had its column default.
1158 return CostProfile.thorough if value is None else value
1160 class Create(Base):
1161 pass
1163 class Update(BaseModel):
1164 name: str | None = None
1165 description: str | None = None
1166 icon: str | None = None
1167 accent: str | None = None
1168 system_prompt: str | None = None
1169 tools: list[dict] | None = None
1170 config: dict | None = None
1171 ai_model_id: UUID | None = None
1172 clarify_scope: bool | None = None
1173 cost_profile: CostProfile | None = None
1175 class Read(Base, _GenerationTag, _SystemTag, _WorkspaceTag):
1176 id: UUID
1178 class Config:
1179 from_attributes = True
1181 class Prompt(BaseModel):
1182 prompt: str
1183 conversation_id: UUID | None = None
1184 system_messages: list[str] = []
1185 # A chat command's form values, when ``prompt`` opens with one
1186 # (app/services/chat_commands.py); validated against its form.
1187 command_inputs: dict[str, Any] | None = None
1188 # Documents of the workspace's library this message attaches
1189 # (app/services/attachments.py): sent beside the words.
1190 file_ids: list[UUID] = []
1192 class Knowledge:
1193 class Base(_OwnerFields):
1194 name: str
1195 description: str
1196 source_type: str
1197 source_config: dict
1199 class Create(Base):
1200 pass
1202 class Edit(BaseModel):
1203 owner_user_id: UUID | None = None
1204 owner_organisation_id: UUID | None = None
1205 owner_project_id: UUID | None = None
1206 name: str | None = None
1207 description: str | None = None
1208 source_type: str | None = None
1209 source_config: dict | None = None
1211 class Read(Base, _GenerationFields, _SystemTag, _WorkspaceTag):
1212 """A source as anyone who can read it is served it: its config
1213 is the reader's view (``knowledge_config.reader_config``), never
1214 a database's connection string or an API's auth value. Only
1215 ``GET /knowledge/{id}`` serves the whole config, to a caller who
1216 may change the source (its edit form needs it)."""
1218 id: UUID
1219 created_at: UTCDateTime | None = None
1221 @model_validator(mode="after")
1222 def _reader_config(self):
1223 self.source_config = knowledge_config.reader_config(
1224 self.source_type, self.source_config
1225 )
1226 return self
1228 class KnowledgeDocument:
1229 class Read(BaseModel):
1230 id: UUID
1231 knowledge_id: UUID
1232 source_id: str
1233 folder_path: str = ""
1234 document_metadata: dict | None = None
1235 created_at: UTCDateTime
1237 class Config:
1238 from_attributes = True
1240 # ── Website knowledge ────────────────────────────────────────────────
1241 # A website source's crawls, its pages (one document each) and every
1242 # stored snapshot of a page. See services/knowledge/web_crawl.py.
1244 class KnowledgeCrawl:
1245 class Read(BaseModel):
1246 id: UUID
1247 knowledge_id: UUID
1248 trigger: str
1249 status: str
1250 actor_user_id: UUID | None = None
1251 started_at: UTCDateTime
1252 finished_at: UTCDateTime | None = None
1253 pages_fetched: int = 0
1254 pages_new: int = 0
1255 pages_changed: int = 0
1256 pages_unchanged: int = 0
1257 pages_failed: int = 0
1258 pages_gone: int = 0
1259 pages_expired: int = 0
1260 #: ``{calls, prompt_tokens, estimated_cost_usd, unpriced_calls}``
1261 #: — the crawl's embedding spend, or null if it indexed nothing.
1262 usage: dict | None = None
1263 note: str | None = None
1265 @field_validator("pages_expired", mode="before")
1266 @classmethod
1267 def _none_is_zero(cls, v: Any) -> Any:
1268 return 0 if v is None else v
1270 class Config:
1271 from_attributes = True
1273 class WebPage:
1274 class Read(BaseModel):
1275 """One page of a website source, as of its most recent crawl."""
1277 document_id: UUID
1278 url: str
1279 title: str | None = None
1280 #: active | gone | blocked | failed
1281 status: str
1282 version_count: int = 0
1283 last_fetched_at: str | None = None
1284 last_changed_at: str | None = None
1285 last_error: str | None = None
1286 index_status: str | None = None
1287 first_seen_at: UTCDateTime
1288 #: ``crawled`` (in the source's scope) or ``linked`` (on another
1289 #: site, read because a crawled page links to it).
1290 origin: str = "crawled"
1291 #: For a linked page: the crawled pages that link to it, each
1292 #: ``{url, title, text}`` — the chain a deep citation shows.
1293 linked_from: list[dict] = []
1295 class WebGraph:
1296 class Node(BaseModel):
1297 #: The page's document id — the same id the pages list uses.
1298 id: UUID
1299 url: str
1300 title: str | None = None
1301 status: str
1302 origin: str = "crawled"
1303 host: str
1304 is_seed: bool = False
1305 version_count: int = 0
1306 #: Shortest link path from a seed URL; None when no stored link
1307 #: reaches the page (found in a sitemap, or its linker has gone).
1308 depth: int | None = None
1309 #: Links on the page to anything the source did not store.
1310 unfollowed_links: int = 0
1311 in_links: int = 0
1312 out_links: int = 0
1314 class Edge(BaseModel):
1315 source: UUID
1316 target: UUID
1317 text: str = ""
1318 #: ``internal`` (same site) or ``external`` (a hop off-site)
1319 kind: str
1321 class Read(BaseModel):
1322 """Which stored page links to which — see
1323 services/knowledge/web_graph.py."""
1325 nodes: list["Schema.WebGraph.Node"]
1326 edges: list["Schema.WebGraph.Edge"]
1327 truncated: bool = False
1329 class WebPageVersion:
1330 class Read(BaseModel):
1331 id: UUID
1332 document_id: UUID
1333 crawl_id: UUID | None = None
1334 version_number: int
1335 url: str
1336 title: str | None = None
1337 content_hash: str
1338 http_status: int | None = None
1339 fetched_at: UTCDateTime
1340 size_bytes: int = 0
1341 has_html: bool = False
1343 class Content(BaseModel):
1344 version: "Schema.WebPageVersion.Read"
1345 markdown: str
1347 class Preview(BaseModel):
1348 """A snapshot's HTML reduced to inert, network-free markup for the
1349 sandboxed preview — see services/knowledge/html_preview.py."""
1351 version: "Schema.WebPageVersion.Read"
1352 html: str
1353 truncated: bool = False
1355 class Diff(BaseModel):
1356 """Two snapshots of a page, line by line. ``text_diff`` has the
1357 shape of a history field diff, so the same viewer renders it;
1358 long unchanged runs are folded to a ``skip`` line."""
1360 from_version: "Schema.WebPageVersion.Read | None" = None
1361 to_version: "Schema.WebPageVersion.Read"
1362 text_diff: list[dict[str, str]]
1363 added_lines: int = 0
1364 removed_lines: int = 0
1366 class WebCrawlPages:
1367 """A website source as one crawl left it, beside how it is now. See
1368 services/knowledge/web_as_of.py."""
1370 class Page(BaseModel):
1371 document_id: UUID
1372 url: str
1373 title: str | None = None
1374 #: The page's standing now: active | gone | blocked | failed
1375 status: str
1376 origin: str = "crawled"
1377 #: The version in force after the crawl; null if the page was
1378 #: first stored later.
1379 then: "Schema.WebPageVersion.Read | None" = None
1380 #: The newest version.
1381 now: "Schema.WebPageVersion.Read"
1382 #: What the crawl did to the page: ``new`` | ``changed``, or null
1383 #: when it stored nothing for it.
1384 written: str | None = None
1385 #: ``now`` against ``then``: added | changed | unchanged
1386 since: str
1388 class Read(BaseModel):
1389 crawl: "Schema.KnowledgeCrawl.Read"
1390 pages: list["Schema.WebCrawlPages.Page"]
1391 #: Pages later crawls removed for ageing out of the source's
1392 #: window. Their versions went with them, so they are counted
1393 #: here and cannot be listed.
1394 expired_since: int = 0
1396 class KnowledgeRepository:
1397 class Base(_OwnerFields):
1398 name: str
1399 description: str | None = None
1400 # Presentation, chosen in the UI and mirrored from Dashboard and
1401 # Agent: a lucide icon name and an accent key. Unknown values
1402 # fall back client-side, so neither is validated against a
1403 # closed set here.
1404 icon: str | None = None
1405 accent: str | None = None
1406 # What kind of knowledge it holds (KnowledgeRepository.category),
1407 # which decides how an agent uses it.
1408 category: KnowledgeCategory = knowledge_categories.DEFAULT
1410 @field_validator("category", mode="before")
1411 @classmethod
1412 def _no_category_is_the_default(cls, value: Any) -> Any:
1413 # A row not yet flushed has not had its column default.
1414 return knowledge_categories.DEFAULT if value is None else value
1416 class Create(Base):
1417 pass
1419 class Edit(BaseModel):
1420 name: str | None = None
1421 description: str | None = None
1422 icon: str | None = None
1423 accent: str | None = None
1424 category: KnowledgeCategory | None = None
1426 class Read(Base, _GenerationFields, _SystemTag, _WorkspaceTag):
1427 id: UUID
1428 created_at: UTCDateTime | None = None
1430 class Config:
1431 from_attributes = True
1433 class ReadWithMembers(Read):
1434 knowledge_ids: list[UUID] = []
1436 class Detail(ReadWithMembers):
1437 """``GET /repositories/{id}``: the repository, and whether the
1438 caller may change it here (``may_change_here``)."""
1440 can_change: bool = False
1442 class AgentGrant(BaseModel):
1443 """One of the caller's agents a repository is granted to."""
1445 agent_id: UUID
1446 name: str
1448 class Category(BaseModel):
1449 """``GET /repositories/categories``: a kind of knowledge a
1450 repository may hold (``app/util/knowledge_categories.py``)."""
1452 key: KnowledgeCategory
1453 label: str
1454 #: What it holds.
1455 purpose: str
1456 #: What an agent does with it.
1457 use: str
1459 class RepositoryKnowledge:
1460 class Add(BaseModel):
1461 knowledge_id: UUID
1463 class Read(BaseModel):
1464 repository_id: UUID
1465 knowledge_id: UUID
1467 class Config:
1468 from_attributes = True
1470 class KnowledgeFigures:
1471 """The knowledge pages' figures (``services/knowledge/stats.py``,
1472 ``usage.py``): what a source holds and how it is kept, and — in the
1473 request workspace only — who reaches it and how often answers cite
1474 it. See ``docs/guides/knowledge.md#figures``."""
1476 class Documents(BaseModel):
1477 total: int
1478 #: Per indexing state (``stats.INDEX_STATES``, plus ``held``).
1479 by_state: dict[str, int]
1480 unrecorded: int
1481 #: A website's pages per ``web_crawl.PageStatus``; empty otherwise.
1482 pages: dict[str, int]
1483 chunks: int
1484 size_bytes: int
1485 page_versions: int
1487 class Crawl(BaseModel):
1488 #: The newest crawl's ``status``, or ``never``.
1489 status: str
1490 started_at: UTCDateTime | None = None
1491 finished_at: UTCDateTime | None = None
1492 pages_failed: int = 0
1493 last_success_at: UTCDateTime | None = None
1494 cadence: str | None = None
1495 next_due_at: UTCDateTime | None = None
1497 class Ref(BaseModel):
1498 id: UUID
1499 name: str
1501 class Source(BaseModel):
1502 knowledge_id: UUID
1503 source_type: str
1504 items: int
1505 documents: "Schema.KnowledgeFigures.Documents"
1506 crawl: "Schema.KnowledgeFigures.Crawl | None" = None
1507 last_updated_at: UTCDateTime | None = None
1508 repositories: list["Schema.KnowledgeFigures.Ref"]
1509 agents: int
1510 #: Answers citing it in the last 30 days, and per day (oldest first).
1511 citations: int
1512 citations_daily: list[int]
1513 #: Answers in 30 days whose turn kept its passages for the agent
1514 #: (the retrieval record): what it is retrieved for, beside how
1515 #: often that is cited.
1516 retrieved: int = 0
1517 #: The trust signals asking for a look (``trust.needs_attention``).
1518 attention: list[str]
1519 config_summary: str | None = None
1521 class Repository(BaseModel):
1522 repository_id: UUID
1523 sources: int
1524 by_type: dict[str, int]
1525 items: int
1526 documents_indexed: int
1527 documents_total: int
1528 attention_sources: int
1529 agents: int
1530 citations: int
1531 citations_daily: list[int]
1532 #: Answers in 30 days whose turn kept its passages for the agent
1533 #: (the retrieval record): what it is retrieved for, beside how
1534 #: often that is cited.
1535 retrieved: int = 0
1536 last_updated_at: UTCDateTime | None = None
1538 class RepositoryDetail(BaseModel):
1539 """``GET /repositories/{id}/stats``: the repository's figures and
1540 each member source's, for its page's table."""
1542 repository: "Schema.KnowledgeFigures.Repository"
1543 sources: list["Schema.KnowledgeFigures.Source"]
1545 class Day(BaseModel):
1546 day: date
1547 answers: int
1549 class Ranked(BaseModel):
1550 """An agent, source or document by the answers citing it; ``id``
1551 None for one deleted since, or a source cited whole."""
1553 id: UUID | None = None
1554 name: str
1555 answers: int
1556 is_system: bool = False
1557 url: str | None = None
1558 knowledge_id: UUID | None = None
1560 class RecentAnswer(BaseModel):
1561 message_id: UUID
1562 conversation_id: UUID
1563 agent_id: UUID | None = None
1564 agent_name: str | None = None
1565 cited_at: UTCDateTime
1567 class Usage(BaseModel):
1568 days: int
1569 since: UTCDateTime
1570 answers: int
1571 previous_answers: int
1572 daily: list["Schema.KnowledgeFigures.Day"]
1573 agents: list["Schema.KnowledgeFigures.Ranked"]
1574 documents: list["Schema.KnowledgeFigures.Ranked"]
1575 #: A repository's only: its sources by answers.
1576 sources: list["Schema.KnowledgeFigures.Ranked"] = []
1577 #: The viewer's own answers — a conversation is its person's.
1578 recent: list["Schema.KnowledgeFigures.RecentAnswer"]
1580 class SourceMap:
1581 """A repository's sources connected by evidence
1582 (``services/knowledge/source_map``): never by hand. Each edge says
1583 why it is there — each kind's count, score and examples."""
1585 class Example(BaseModel):
1586 label: str
1587 url: str | None = None
1589 class Evidence(BaseModel):
1590 kind: str
1591 count: float
1592 score: float
1593 contribution: float
1594 examples: list["Schema.SourceMap.Example"]
1596 class Node(BaseModel):
1597 id: str
1598 #: ``source`` (in the repository), ``suggestion`` (a workspace
1599 #: source the evidence ties to it) or ``agent``.
1600 kind: str
1601 ref_id: UUID
1602 label: str
1603 meta: dict[str, Any]
1605 class Edge(BaseModel):
1606 source: str
1607 target: str
1608 #: ``evidence`` between sources; ``cited_by`` from an agent.
1609 kind: str
1610 weight: float
1611 evidence: list["Schema.SourceMap.Evidence"] = []
1613 class Kind(BaseModel):
1614 key: str
1615 label: str
1616 description: str
1617 strength: float
1618 tau: float
1619 #: What its count counts ("document in both"); null where the
1620 #: count is a weighting and the examples say it.
1621 unit_one: str | None = None
1622 unit_many: str | None = None
1624 class Read(BaseModel):
1625 nodes: list["Schema.SourceMap.Node"]
1626 edges: list["Schema.SourceMap.Edge"]
1627 #: The kinds of evidence, for the legend.
1628 kinds: list["Schema.SourceMap.Kind"]
1629 summary: dict[str, Any]
1630 truncated: bool
1632 class KnowledgeTrust:
1633 """Trust signals (``services/knowledge/trust.py``): what is on record
1634 about whether a source can be relied on — states, never a score."""
1636 class Signal(BaseModel):
1637 key: str
1638 label: str
1639 description: str
1640 attention: bool
1642 class Fact(BaseModel):
1643 label: str
1644 value: str
1645 ref_kind: str | None = None
1646 ref_id: UUID | None = None
1647 url: str | None = None
1648 at: UTCDateTime | None = None
1650 class Result(BaseModel):
1651 key: str
1652 state: str
1653 summary: str
1654 facts: list["Schema.KnowledgeTrust.Fact"]
1656 class Source(BaseModel):
1657 knowledge_id: UUID
1658 signals: list["Schema.KnowledgeTrust.Result"]
1659 attention: list[str]
1661 class Repository(BaseModel):
1662 sources: list["Schema.KnowledgeTrust.Source"]
1663 #: Per signal, how many member sources are in each state.
1664 summary: dict[str, dict[str, int]]
1666 class KnowledgeRecommendations:
1667 """What to change about a workspace's knowledge, with the evidence
1668 and the flow that would change it
1669 (``services/knowledge/recommendations``). Read-only: an action
1670 opens a flow, which acts only when the person does."""
1672 class Kind(BaseModel):
1673 key: str
1674 label: str
1675 description: str
1676 section: str
1677 section_label: str
1679 class Subject(BaseModel):
1680 kind: str
1681 id: str
1682 name: str
1684 class Figure(BaseModel):
1685 label: str
1686 value: int
1688 class Example(BaseModel):
1689 #: One of the viewer's own questions, as the record kept it.
1690 text: str
1691 detail: str | None = None
1692 at: UTCDateTime | None = None
1694 class Prefill(BaseModel):
1695 category: str | None = None
1696 from_turns: list[UUID] = []
1697 agent_id: UUID | None = None
1698 agent_name: str | None = None
1699 repository_id: UUID | None = None
1700 repository_name: str | None = None
1701 knowledge_id: UUID | None = None
1702 knowledge_name: str | None = None
1703 tab: str | None = None
1704 url: str | None = None
1705 name: str | None = None
1706 refresh: str | None = None
1707 max_age_days: int | None = None
1709 class Action(BaseModel):
1710 flow: str
1711 label: str
1712 prefill: "Schema.KnowledgeRecommendations.Prefill"
1714 class Item(BaseModel):
1715 kind: str
1716 section: str
1717 subject: "Schema.KnowledgeRecommendations.Subject"
1718 title: str
1719 why: str
1720 figures: list["Schema.KnowledgeRecommendations.Figure"]
1721 examples: list["Schema.KnowledgeRecommendations.Example"]
1722 actions: list["Schema.KnowledgeRecommendations.Action"]
1723 #: What the evidence reads; sent back to set it aside.
1724 fingerprint: str
1726 class List(BaseModel):
1727 items: list["Schema.KnowledgeRecommendations.Item"]
1728 #: Kinds that could not be read now, and why — never "none".
1729 unavailable: dict[str, str] = {}
1730 #: Whether the viewer may act on them and set them aside here.
1731 can_change: bool = False
1733 class Dismiss(BaseModel):
1734 kind: str = Field(min_length=1, max_length=48)
1735 subject: str = Field(min_length=1, max_length=200)
1736 fingerprint: str = Field(min_length=1, max_length=64)
1738 class Dismissed(BaseModel):
1739 id: UUID
1740 kind: str
1741 subject: str
1742 dismissed_at: UTCDateTime
1744 class AgentContext:
1745 """What an agent draws on, in eight kinds, each from the feature that
1746 owns it (``services/agent_context``)."""
1748 class Fact(BaseModel):
1749 label: str
1750 value: str
1752 class Place(BaseModel):
1753 #: ``tab`` (of the agent's page) or ``page``.
1754 kind: str
1755 target: str
1757 class Suggestion(BaseModel):
1758 """A built-in repository a missing kind could be granted."""
1760 id: UUID
1761 name: str
1762 description: str
1764 class Kind(BaseModel):
1765 key: str
1766 label: str
1767 description: str
1768 owner: str
1769 owner_label: str
1770 #: ``present``, ``missing`` or ``unavailable``.
1771 state: str
1772 summary: str
1773 facts: list["Schema.AgentContext.Fact"] = []
1774 place: "Schema.AgentContext.Place | None" = None
1775 #: The knowledge category, for the three knowledge kinds.
1776 category: str | None = None
1777 #: A missing kind of knowledge's built-ins, best match first.
1778 suggestions: list["Schema.AgentContext.Suggestion"] = []
1780 class Read(BaseModel):
1781 agent_id: UUID
1782 kinds: list["Schema.AgentContext.Kind"]
1784 # --------------------
1785 # Skill
1786 # --------------------
1787 class Skill:
1788 class Base(_OwnerFields):
1789 name: str
1790 description: str | None = None
1791 tags: list[str] = []
1792 graph_definition: dict
1794 class Create(Base):
1795 @field_validator("graph_definition", mode="before")
1796 @classmethod
1797 def validate_graph_definition(cls, v: Any) -> Any:
1798 if v:
1799 try:
1800 _GraphDefinitionSchema(**v)
1801 except Exception as exc:
1802 raise ValueError(f"Invalid graph_definition: {exc}") from exc
1803 return v
1805 class Update(BaseModel):
1806 name: str | None = None
1807 description: str | None = None
1808 tags: list[str] | None = None
1809 graph_definition: dict | None = None
1811 @field_validator("graph_definition", mode="before")
1812 @classmethod
1813 def validate_graph_definition(cls, v: Any) -> Any:
1814 if v:
1815 try:
1816 _GraphDefinitionSchema(**v)
1817 except Exception as exc:
1818 raise ValueError(f"Invalid graph_definition: {exc}") from exc
1819 return v
1821 class Read(Base, _GenerationFields, _SystemTag, _WorkspaceTag):
1822 id: UUID
1823 created_at: UTCDateTime
1825 class Config:
1826 from_attributes = True
1828 class SkillRun:
1829 """A standalone run of a skill (``services/skill_runs``)."""
1831 class Create(BaseModel):
1832 #: Optional when the skill has a form: the task text is then
1833 #: composed from the inputs.
1834 prompt: str = ""
1835 #: Values for the skill's run schema (``GET …/run-schema``).
1836 inputs: dict[str, Any] = {}
1838 class Summary(BaseModel):
1839 """A row of the runs list — everything but the run's body."""
1841 id: UUID
1842 skill_id: UUID | None = None
1843 skill_name: str
1844 skill_version: int | None = None
1845 status: str
1846 prompt: str | None = None
1847 inputs: dict[str, Any] = {}
1848 error: str | None = None
1849 input_tokens: int = 0
1850 output_tokens: int = 0
1851 latency_ms: int | None = None
1852 #: What svc-ai measured, every segment summed. None when nothing
1853 #: could be priced — never 0 for "unknown".
1854 cost_usd: float | None = None
1855 llm_calls: int = 0
1856 #: Calls svc-ai could not price; >0 makes ``cost_usd`` a floor.
1857 unpriced_calls: int = 0
1858 started_at: UTCDateTime
1859 finished_at: UTCDateTime | None = None
1861 class Config:
1862 from_attributes = True
1864 class Read(Summary):
1865 #: Per-model rows: provider, model, calls, tokens, cost.
1866 cost_detail: list[dict[str, Any]] | None = None
1867 #: What the run paused on (``awaiting_input``), or last paused on.
1868 interrupt: dict[str, Any] | None = None
1869 #: Every answer given to a pause, in order.
1870 responses: list[dict[str, Any]] | None = None
1871 task: str | None = None
1872 output: str | None = None
1873 outputs: dict[str, Any] | None = None
1874 state: dict[str, Any] | None = None
1875 steps: list[dict[str, Any]] | None = None
1876 citations: list[dict[str, Any]] | None = None
1877 rule_trace: list[dict[str, Any]] | None = None
1878 warnings: list[str] | None = None
1879 invocation_id: UUID | None = None
1881 class Respond(BaseModel):
1882 """An answer to a paused run: ``approved`` (+ ``feedback``) for an
1883 approval gate, ``answers`` (question id → values) for questions."""
1885 approved: bool | None = None
1886 feedback: str = ""
1887 answers: dict[str, Any] | None = None
1889 class AgentRepository:
1890 class Add(BaseModel):
1891 repository_id: UUID
1892 config: dict | None = None # overrides applied to every member KB
1894 class Read(BaseModel):
1895 agent_id: UUID
1896 repository_id: UUID
1897 config: dict | None = None
1899 class Config:
1900 from_attributes = True
1902 class ReadWithDetail(BaseModel):
1903 agent_id: UUID
1904 repository_id: UUID
1905 config: dict | None = None
1906 repository: "Schema.KnowledgeRepository.Read"
1908 class Config:
1909 from_attributes = True
1911 # --------------------
1912 # Toolkit — a named collection of tools and MCP servers, granted to an
1913 # agent as a single unit (mirrors KnowledgeRepository/Skillset).
1914 # --------------------
1915 class Toolkit:
1916 class Base(_OwnerFields):
1917 name: str
1918 description: str | None = None
1920 class Create(Base):
1921 pass
1923 class Edit(BaseModel):
1924 name: str | None = None
1925 description: str | None = None
1927 class Read(Base, _GenerationFields):
1928 id: UUID
1929 created_at: UTCDateTime | None = None
1931 class Config:
1932 from_attributes = True
1934 class ReadWithMembers(Read):
1935 mcp_server_ids: list[UUID] = []
1937 class ToolkitMCPServer:
1938 class Add(BaseModel):
1939 mcp_server_id: UUID
1941 class Read(BaseModel):
1942 toolkit_id: UUID
1943 mcp_server_id: UUID
1945 class Config:
1946 from_attributes = True
1948 class AgentToolkit:
1949 class Add(BaseModel):
1950 toolkit_id: UUID
1951 config: dict | None = None # overrides applied to every member
1953 class Read(BaseModel):
1954 agent_id: UUID
1955 toolkit_id: UUID
1956 config: dict | None = None
1958 class Config:
1959 from_attributes = True
1961 class ReadWithDetail(BaseModel):
1962 agent_id: UUID
1963 toolkit_id: UUID
1964 config: dict | None = None
1965 toolkit: "Schema.Toolkit.Read"
1967 class Config:
1968 from_attributes = True
1970 # --------------------
1971 # Skillset — a named collection of skills, granted to an agent as a
1972 # single unit (mirrors KnowledgeRepository/Toolkit).
1973 # --------------------
1974 class Skillset:
1975 class Base(_OwnerFields):
1976 name: str
1977 description: str | None = None
1979 class Create(Base):
1980 pass
1982 class Edit(BaseModel):
1983 name: str | None = None
1984 description: str | None = None
1986 class Read(Base, _GenerationFields, _SystemTag, _WorkspaceTag):
1987 id: UUID
1988 created_at: UTCDateTime | None = None
1990 class Config:
1991 from_attributes = True
1993 class ReadWithMembers(Read):
1994 skill_ids: list[UUID] = []
1996 class SkillsetSkill:
1997 class Add(BaseModel):
1998 skill_id: UUID
2000 class Read(BaseModel):
2001 skillset_id: UUID
2002 skill_id: UUID
2004 class Config:
2005 from_attributes = True
2007 class AgentSkillset:
2008 class Add(BaseModel):
2009 skillset_id: UUID
2010 config: dict | None = None # overrides applied to every member
2012 class Read(BaseModel):
2013 agent_id: UUID
2014 skillset_id: UUID
2015 config: dict | None = None
2017 class Config:
2018 from_attributes = True
2020 class ReadWithDetail(BaseModel):
2021 agent_id: UUID
2022 skillset_id: UUID
2023 config: dict | None = None
2024 skillset: "Schema.Skillset.Read"
2026 class Config:
2027 from_attributes = True
2029 # --------------------
2030 # Custom Worker
2031 # --------------------
2032 class CustomWorker:
2033 class Base(_OwnerFields):
2034 name: str
2035 description: str | None = None
2036 # Clone defaults from this builtin/definition; None = from scratch
2037 base_worker: str | None = None
2038 role: str | None = None
2039 system_prompt: str | None = None
2040 tags: list[str] = []
2041 # Optional model override: {provider, model, temperature, max_tokens}
2042 model_overrides: dict | None = None
2043 # Single toggle for the full general toolset
2044 tools_enabled: bool = True
2045 # MCPServer row UUIDs (as strings) whose tools this worker loads
2046 mcp_server_ids: list[str] = []
2047 # Typed interface (schema v3) — see _FieldSpec
2048 input_schema: list[dict] = []
2049 output_schema: list[dict] = []
2051 @field_validator("input_schema", "output_schema")
2052 @classmethod
2053 def _valid_schema(cls, v: list[dict]) -> list[dict]:
2054 return _validate_interface_schema(v) or []
2056 class Create(Base):
2057 pass
2059 class Update(BaseModel):
2060 name: str | None = None
2061 description: str | None = None
2062 system_prompt: str | None = None
2063 tags: list[str] | None = None
2064 model_overrides: dict | None = None
2065 tools_enabled: bool | None = None
2066 mcp_server_ids: list[str] | None = None
2067 input_schema: list[dict] | None = None
2068 output_schema: list[dict] | None = None
2070 @field_validator("input_schema", "output_schema")
2071 @classmethod
2072 def _valid_schema(cls, v: list[dict] | None) -> list[dict] | None:
2073 return _validate_interface_schema(v)
2075 class Read(Base, _GenerationFields):
2076 id: UUID
2077 created_at: UTCDateTime
2078 # Registered name in svc-ai — usable as a skill-graph agent_name
2079 definition_name: str | None = None
2081 class Config:
2082 from_attributes = True
2084 # --------------------
2085 # Industry
2086 # --------------------
2087 class ResourceIndustry:
2088 class Base(BaseModel):
2089 name: str
2091 class Create(Base):
2092 name: str
2094 class Update(BaseModel):
2095 name: str | None = None
2097 class Read(Base):
2098 id: UUID
2099 name: str
2100 created_at: UTCDateTime
2102 class Config:
2103 from_attributes = True
2105 # --------------------
2106 # Role
2107 # --------------------
2108 class ResourceRole:
2109 class Base(BaseModel):
2110 name: str
2112 class Create(Base):
2113 name: str
2115 class Update(BaseModel):
2116 name: str | None = None
2118 class Read(Base):
2119 id: UUID
2120 name: str
2121 created_at: UTCDateTime
2123 class Config:
2124 from_attributes = True
2126 # --------------------
2127 # Experiment
2128 # --------------------
2129 class Experiment:
2130 """An evaluation: one dataset, one scorer, its variants. See the model."""
2132 class Base(_OwnerFields):
2133 name: str
2134 description: str | None = None
2135 status: EvaluationEnum.Status = EvaluationEnum.Status.draft
2136 scorer: EvaluationEnum.Scorer = EvaluationEnum.Scorer.manual
2137 scorer_config: dict | None = None
2138 judge: dict | None = None
2139 config: dict | None = None
2141 class Create(Base):
2142 name: str = Field(min_length=1, max_length=255)
2143 # Where the cases come from — exactly one of the three:
2144 # an existing dataset; inline ``cases`` that create a dataset of
2145 # the same name alongside; or a Quick try to adopt, whose case,
2146 # scorer and variants the server derives from what actually ran.
2147 dataset_id: UUID | None = None
2148 cases: list[_TestCaseCreate] | None = None
2149 comparison_id: UUID | None = None
2150 # Variants to create in the same transaction as the evaluation.
2151 # One body, one transaction, one version — created as separate
2152 # requests, a failure after the first left an evaluation with
2153 # half its variants and nothing to say so. Not with a
2154 # ``comparison_id``, which brings its own.
2155 variants: list[_ExperimentVariantCreate] | None = None
2157 class Update(BaseModel):
2158 name: str | None = Field(default=None, min_length=1, max_length=255)
2159 description: str | None = None
2160 status: EvaluationEnum.Status | None = None
2161 dataset_id: UUID | None = None
2162 scorer: EvaluationEnum.Scorer | None = None
2163 scorer_config: dict | None = None
2164 judge: dict | None = None
2165 config: dict | None = None
2167 class Read(Base, _GenerationTag, _WorkspaceTag, _SystemTag):
2168 id: UUID
2169 dataset_id: UUID
2170 created_at: UTCDateTime
2172 class Config:
2173 from_attributes = True
2175 # --------------------
2176 # Experiment Variant
2177 # --------------------
2178 class ExperimentVariant:
2179 class Base(BaseModel):
2180 experiment_id: UUID
2181 name: str
2182 prompt: str | None = None
2183 config: dict | None = None
2185 # The parent is in the path and the handler takes it from there, so
2186 # requiring it in the body only ever produced a 422 for a client that
2187 # had already said which experiment it meant.
2188 class Create(_ExperimentVariantCreate):
2189 pass
2191 class Update(BaseModel):
2192 name: str | None = None
2193 prompt: str | None = None
2194 config: dict | None = None
2196 class Read(Base):
2197 id: UUID
2198 created_at: UTCDateTime
2200 class Config:
2201 from_attributes = True
2203 # --------------------
2204 # Experiment Run
2205 # --------------------
2206 class ExperimentRun:
2207 """One scored (target, case) cell, as the runner writes it.
2209 Read-only: cells are produced by ``runner.execute_batch`` and nothing
2210 else, so a result row can always be traced to the batch, the target
2211 and the case that made it. There is deliberately no ``Create`` — an
2212 endpoint that inserted a bare row would put a score on record that no
2213 invocation produced.
2214 """
2216 class Read(BaseModel):
2217 id: UUID
2218 experiment_id: UUID | None = None
2219 variant_id: UUID | None = None
2220 batch_id: UUID | None = None
2221 test_case_id: UUID | None = None
2222 input: dict | None = None
2223 output: str | None = None
2224 score: dict | None = None
2225 score_reason: str | None = None
2226 scorer: EvaluationEnum.Scorer | None = None
2227 passed: bool | None = None
2228 run_metadata: dict | None = None
2229 status: RunnableEnum.Status | None = None
2230 started_at: UTCDateTime | None = None
2231 finished_at: UTCDateTime | None = None
2232 created_at: UTCDateTime
2234 class Config:
2235 from_attributes = True
2237 # --------------------
2238 # Test Suite
2239 # --------------------
2240 class TestSuite:
2241 """A dataset: cases only. See the model for why nothing else is here."""
2243 class Base(_OwnerFields):
2244 name: str
2245 description: str | None = None
2246 status: EvaluationEnum.Status = EvaluationEnum.Status.draft
2247 #: What every good answer in the dataset must do; each case adds
2248 #: its own.
2249 criteria: CriteriaField = None
2250 #: The mean score a model or agent must reach to pass the
2251 #: dataset. None is the platform default (0.8).
2252 pass_mark: PassMark = None
2253 config: dict | None = None
2255 class Create(Base):
2256 name: str = Field(min_length=1, max_length=255)
2258 class Update(BaseModel):
2259 name: str | None = Field(default=None, min_length=1, max_length=255)
2260 description: str | None = None
2261 status: EvaluationEnum.Status | None = None
2262 criteria: CriteriaField = None
2263 pass_mark: PassMark = None
2264 config: dict | None = None
2266 class Read(Base, _GenerationTag, _SystemTag, _WorkspaceTag):
2267 id: UUID
2268 created_at: UTCDateTime
2269 #: How many cases it holds — served on the listing so the gold
2270 #: datasets' cards can say so without a request per dataset.
2271 case_count: int | None = None
2273 class Config:
2274 from_attributes = True
2276 class Copy(_OwnerFields):
2277 """Copy a dataset — a gold one, usually — into one of your own.
2279 ``name`` defaults to the source's; the copy belongs to the caller
2280 unless an organisation or project is named.
2281 """
2283 name: str | None = Field(default=None, min_length=1, max_length=255)
2285 # --------------------
2286 # Test Case
2287 # --------------------
2288 class TestCase:
2289 class Base(BaseModel):
2290 test_suite_id: UUID
2291 name: str | None = None
2292 input: dict
2293 expected_output: str | None = None
2294 criteria: CriteriaField = None
2295 examples: list[CaseExample] | None = None
2296 expected_behaviour: ExpectedBehaviour | None = None
2297 expectation: dict | None = None
2298 situation: dict | None = None
2299 tags: list | None = None
2301 # See ``ExperimentVariant.Create``: the suite is in the path.
2302 class Create(_TestCaseCreate):
2303 pass
2305 class Update(BaseModel):
2306 name: str | None = None
2307 input: dict | None = None
2308 expected_output: str | None = None
2309 criteria: CriteriaField = None
2310 examples: list[CaseExample] | None = Field(
2311 default=None, max_length=MAX_CASE_EXAMPLES
2312 )
2313 expected_behaviour: ExpectedBehaviour | None = None
2314 expectation: ExpectationField = None
2315 situation: dict | None = None
2316 tags: list | None = None
2318 class Read(Base):
2319 id: UUID
2320 created_at: UTCDateTime
2321 #: The governed turn it was made from ("Add to dataset" on a
2322 #: decision record); None for a case written by hand.
2323 source_invocation_id: UUID | None = None
2325 class Config:
2326 from_attributes = True
2328 # --------------------
2329 # MCPServer
2330 # --------------------
2331 class MCPServer:
2332 class Base(_OwnerFields):
2333 name: str
2334 description: str | None = None
2335 template_key: str | None = None
2336 connection_type: str
2337 connection_config: dict = {}
2338 is_active: bool = True
2340 class Create(Base):
2341 pass
2343 class Update(BaseModel):
2344 name: str | None = None
2345 description: str | None = None
2346 connection_config: dict | None = None
2347 tools_cache: list[str] | None = None
2348 is_active: bool | None = None
2350 class Read(Base):
2351 id: UUID
2352 tools_cache: list[str] | None = None
2353 created_at: UTCDateTime
2355 class Config:
2356 from_attributes = True
2358 # --------------------
2359 # SimulationWorld
2360 # --------------------
2361 class SimulationWorld:
2362 class Base(_OwnerFields):
2363 name: str
2364 description: str | None = None
2365 status: SimulationEnum.Status = SimulationEnum.Status.draft
2366 rules: dict | None = None
2367 logic: dict | None = None
2369 class Create(Base):
2370 pass
2372 class Update(BaseModel):
2373 name: str | None = None
2374 description: str | None = None
2375 status: SimulationEnum.Status | None = None
2376 rules: dict | None = None
2377 logic: dict | None = None
2379 class Read(Base):
2380 id: UUID
2381 created_at: UTCDateTime
2383 class Config:
2384 from_attributes = True
2386 # --------------------
2387 # SimulationScenario
2388 # --------------------
2389 class SimulationScenario:
2390 class Base(BaseModel):
2391 world_id: UUID
2392 name: str
2393 description: str | None = None
2394 strategy: SimulationEnum.Strategy = SimulationEnum.Strategy.custom
2395 tags: list | None = None
2396 config: dict | None = None
2397 status: SimulationEnum.Status = SimulationEnum.Status.draft
2399 # See ``ExperimentVariant.Create``: the world is in the path.
2400 class Create(BaseModel):
2401 name: str
2402 description: str | None = None
2403 strategy: SimulationEnum.Strategy = SimulationEnum.Strategy.custom
2404 tags: list | None = None
2405 config: dict | None = None
2406 status: SimulationEnum.Status = SimulationEnum.Status.draft
2408 class Update(BaseModel):
2409 name: str | None = None
2410 description: str | None = None
2411 strategy: SimulationEnum.Strategy | None = None
2412 tags: list | None = None
2413 config: dict | None = None
2414 status: SimulationEnum.Status | None = None
2416 class Read(Base):
2417 id: UUID
2418 created_at: UTCDateTime
2420 class Config:
2421 from_attributes = True
2423 # --------------------
2424 # Simulation
2425 # --------------------
2426 class Simulation:
2427 # See ``ExperimentVariant.Create``: the world is in the path.
2428 class Create(BaseModel):
2429 scenario_id: UUID | None = None
2430 name: str | None = None
2431 description: str | None = None
2432 agent_ids: list | None = None
2433 run_metadata: dict | None = None
2435 class Update(BaseModel):
2436 name: str | None = None
2437 description: str | None = None
2438 agent_ids: list | None = None
2439 results: dict | None = None
2440 run_metadata: dict | None = None
2442 class Read(Create):
2443 id: UUID
2444 results: dict | None = None
2445 status: str | None = None
2446 started_at: UTCDateTime | None = None
2447 finished_at: UTCDateTime | None = None
2448 created_at: UTCDateTime
2450 class Config:
2451 from_attributes = True
2453 # --------------------
2454 # Rule
2455 # --------------------
2456 class Rule:
2457 class Base(_OwnerFields):
2458 name: str
2459 description: str | None = None
2460 #: Where in a request it acts (``app/services/rules/layers.py``).
2461 layer: RuleEnum.Layer
2462 scope_type: RuleEnum.Scope = RuleEnum.Scope.global_
2463 scope_id: UUID | None = None
2464 conditions: list[dict] = []
2465 actions: list[dict] = []
2466 is_active: bool = True
2467 priority: int = 0
2468 #: Applies in every project of its owner, declared or not
2469 #: (``app/services/inheritance.py``). Not for a project's rule.
2470 required_for_projects: bool = False
2472 @field_validator("required_for_projects", mode="before")
2473 @classmethod
2474 def default_required(cls, v: Any) -> Any:
2475 # None on an unflushed row: the column default applies at
2476 # flush, as for ``is_system``.
2477 return False if v is None else v
2479 class Create(Base):
2480 #: The built-in rule this one was started from, when it was. The
2481 #: server checks it names a built-in and records which release of
2482 #: it; the content is whatever the client sends, edits included.
2483 based_on_rule_id: UUID | None = None
2485 class Update(BaseModel):
2486 name: str | None = None
2487 description: str | None = None
2488 layer: RuleEnum.Layer | None = None
2489 scope_type: RuleEnum.Scope | None = None
2490 scope_id: UUID | None = None
2491 conditions: list[dict] | None = None
2492 actions: list[dict] | None = None
2493 is_active: bool | None = None
2494 priority: int | None = None
2495 required_for_projects: bool | None = None
2497 class Read(Base, _GenerationFields, _SystemTag, _WorkspaceTag):
2498 id: UUID
2499 created_at: UTCDateTime
2500 updated_at: UTCDateTime
2501 based_on_rule_id: UUID | None = None
2502 #: The built-in's version number when this rule was created from it.
2503 based_on_version: int | None = None
2504 #: What the rule does, in words — one line per action, as its
2505 #: card shows it ("Caps spend at $100 a month";
2506 #: ``app/services/rules/summary.py``). Derived, never stored.
2507 summaries: list[str] = []
2509 @model_validator(mode="after")
2510 def _summarise(self) -> "Schema.Rule.Read":
2511 # Imported here: the action registry reaches services this
2512 # module must not import at load.
2513 from app.services.rules import summary
2515 self.summaries = summary.summaries(self.layer, self.actions)
2516 return self
2518 class Config:
2519 from_attributes = True
2521 class Detail(Read):
2522 """``GET /rules/{id}``: the rule, whether the caller may change
2523 it here (``may_change_here``: a Governance editor of the
2524 workspace that owns it, in that workspace — never a built-in, nor
2525 what a project inherits or is required to apply), and the name of
2526 the workspace that owns it, which is where a reader who may not
2527 is sent to have it changed."""
2529 can_change: bool = False
2530 home_workspace_name: str | None = None
2532 # -- Vocabulary catalogue -------------------------------------------
2533 #
2534 # The grammar a rule may be written in, served from the backend
2535 # registries in ``app.services.rules``. The visual rule builder reads
2536 # these instead of hard-coding field, operator and action lists, so
2537 # widening the vocabulary is a backend class rather than a matched
2538 # pair of changes that can drift.
2540 class OperatorSpec(BaseModel):
2541 """One comparison a condition can make."""
2543 key: str
2544 label: str
2545 description: str
2546 #: Field value types this operator may be paired with.
2547 applies_to: list[str]
2548 #: What the builder should collect as the comparison value.
2549 operand: str
2551 class FieldSpec(BaseModel):
2552 """One value a condition can be written against."""
2554 key: str
2555 label: str
2556 description: str
2557 group: str
2558 value_type: str
2559 #: input | output — when this field has a value.
2560 phases: list[str]
2561 #: Closed value set — an ``enum`` field's choices, or the members
2562 #: a ``list`` field can hold; empty otherwise.
2563 options: list[str] = Field(default_factory=list)
2564 #: The catalogue section describing ``options`` ("pii_kinds").
2565 vocabulary: str | None = None
2566 #: Operator keys legal for this field, precomputed for the builder.
2567 operators: list[str] = Field(default_factory=list)
2569 class ActionParamSpec(BaseModel):
2570 """One configurable parameter on an action block."""
2572 key: str
2573 label: str
2574 value_type: str
2575 description: str
2576 required: bool
2577 default: Any = None
2578 options: list[str] = Field(default_factory=list)
2579 #: The kind of resource the value names by id ("dataset"), for a
2580 #: picker instead of an id field. Null for a plain value.
2581 resource: str | None = None
2582 #: The catalogue section describing ``options`` ("pii_kinds").
2583 vocabulary: str | None = None
2584 #: ``{"param", "value"}``: shown only while another parameter
2585 #: holds that value — a trailing window's length, say.
2586 shown_when: dict[str, str] | None = None
2587 #: What each item of a list is ("domain"), for an input that
2588 #: reads it as one. Null for plain text.
2589 item: str | None = None
2591 class VocabularyEntry(BaseModel):
2592 """One choice a parameter offers, as the builder labels it."""
2594 key: str
2595 label: str
2596 description: str = ""
2597 #: For a quota period: whether it starts again at a boundary.
2598 calendar: bool | None = None
2600 class ActionSpec(BaseModel):
2601 """One effect a matched rule can have."""
2603 type: str
2604 label: str
2605 description: str
2606 layer: RuleEnum.Layer
2607 #: "both" or "core_only". Quota actions (rate_limit, cost_cap)
2608 #: read svc-core's usage ledger, so they are enforced here and
2609 #: never forwarded to svc-ai. The builder surfaces the difference
2610 #: rather than leaving it to be discovered from behaviour.
2611 enforced_in: str = "both"
2612 params: list["Schema.Rule.ActionParamSpec"] = Field(default_factory=list)
2614 class LayerSpec(BaseModel):
2615 """One layer of a request, and the fields and actions its rules
2616 may use (``app/services/rules/layers.py``)."""
2618 layer: RuleEnum.Layer
2619 label: str
2620 #: The question its rules answer ("May it run?").
2621 summary: str
2622 description: str
2623 #: 1-based place in the flow, the order a request meets layers.
2624 position: int
2625 #: The evaluation phase its conditions run in, which is what
2626 #: determines the fields it can see.
2627 phase: str
2628 fields: list["Schema.Rule.FieldSpec"]
2629 actions: list["Schema.Rule.ActionSpec"]
2631 class ScopeSpec(BaseModel):
2632 """One kind of thing a rule can be written about.
2634 Served as a spec rather than a bare enum key so the builder's
2635 scope picker knows what each scope governs, whether it can be
2636 pinned to a single resource, and how to phrase "all of them" —
2637 the same reason fields and actions are specs.
2638 """
2640 key: RuleEnum.Scope
2641 label: str
2642 description: str
2643 #: How narrowly the scope aims, broad (0) to narrow. Orders the
2644 #: picker, and orders rules at equal priority in the engine.
2645 specificity: int
2646 #: False for ``global``, which has exactly one of itself.
2647 targets_resource: bool
2648 #: Label for the "every resource of this kind" option.
2649 plural: str
2651 class ScopeTarget(BaseModel):
2652 """One resource a rule can be pinned to."""
2654 id: str
2655 label: str
2656 scope_type: RuleEnum.Scope
2658 class ScopeTargets(BaseModel):
2659 """Everything the current user may scope a rule to, by scope.
2661 One call rather than the builder fanning out to six routers. It
2662 is also what lets a rule list resolve ``scope_id`` to a name, so
2663 "applies to 7f3c…" can read "applies to Support Agent".
2664 """
2666 targets: dict[RuleEnum.Scope, list["Schema.Rule.ScopeTarget"]]
2668 class PiiKindSpec(BaseModel):
2669 """One kind of personal data the PII detectors know."""
2671 key: str
2672 #: As it reads mid-sentence ("email address", "IBAN"); the builder
2673 #: capitalises it for a label.
2674 label: str
2675 plural: str
2676 #: One value in its commonest written form.
2677 example: str
2678 #: What qualifies the example ("after a keyword such as 'BSN'").
2679 note: str
2680 #: Plural, example and note as one phrase.
2681 description: str
2682 #: Where the identifier is issued — how the picker groups kinds.
2683 region: str
2684 region_label: str
2685 category: str
2686 category_label: str
2687 #: Part of what a rule redacts when it names no kinds.
2688 default: bool
2690 class Catalogue(BaseModel):
2691 """The full rule vocabulary, for the builder."""
2693 #: Listed once; which fields each may pair with is recorded on
2694 #: every field's ``operators``.
2695 operators: list["Schema.Rule.OperatorSpec"]
2696 scopes: list["Schema.Rule.ScopeSpec"]
2697 #: In flow order.
2698 layers: list["Schema.Rule.LayerSpec"]
2699 #: What a field or parameter with ``vocabulary: "pii_kinds"``
2700 #: holds, described for the picker.
2701 pii_kinds: list["Schema.Rule.PiiKindSpec"] = Field(default_factory=list)
2702 #: The quota actions' choices (``actions.quota_vocabularies``).
2703 quota_periods: list["Schema.Rule.VocabularyEntry"] = Field(
2704 default_factory=list
2705 )
2706 quota_shares: list["Schema.Rule.VocabularyEntry"] = Field(
2707 default_factory=list
2708 )
2709 quota_responses: list["Schema.Rule.VocabularyEntry"] = Field(
2710 default_factory=list
2711 )
2712 quota_reserves: list["Schema.Rule.VocabularyEntry"] = Field(
2713 default_factory=list
2714 )
2715 quota_alerts: list["Schema.Rule.VocabularyEntry"] = Field(
2716 default_factory=list
2717 )
2718 execution_types: list["Schema.Rule.VocabularyEntry"] = Field(
2719 default_factory=list
2720 )
2722 # --------------------
2723 # Audit review queue — where flag_for_review lands
2724 # --------------------
2725 class Review:
2726 class Read(BaseModel):
2727 """One flagged invocation awaiting, or past, a person's judgement."""
2729 id: UUID
2730 owner_user_id: UUID | None = None
2731 #: ``rule`` (an audit rule's flag), ``regression`` (a run that
2732 #: scored worse than its last comparable run) or ``withheld`` (an
2733 #: answer an Output rule withheld, kept for review).
2734 kind: str = "rule"
2736 # Rule identity is denormalised onto the flag: a rule can be
2737 # renamed or deleted, and a flag that resolved to nothing is
2738 # exactly the evidence an audit needs.
2739 rule_id: UUID | None = None
2740 rule_name: str | None = None
2741 rule_version: int | None = None
2742 scope_type: RuleEnum.Scope | None = None
2743 scope_id: UUID | None = None
2744 reviewer: str | None = None
2746 execution_type: str | None = None
2747 conversation_id: UUID | None = None
2748 agent_id: UUID | None = None
2749 ai_model_id: UUID | None = None
2750 #: The flagged turn: the key of its decision record.
2751 invocation_id: UUID | None = None
2752 #: The question the flagged answer was for (the stored question,
2753 #: after the policy rules ran; a skill run's request), read from
2754 #: the turn by ``review.questions``. None for a regression and for
2755 #: flags from before turns had ids.
2756 question: str | None = None
2757 excerpt: str | None = None
2758 experiment_id: UUID | None = None
2759 batch_id: UUID | None = None
2761 status: ReviewEnum.Status
2762 reviewed_by_user_id: UUID | None = None
2763 reviewed_at: UTCDateTime | None = None
2764 reviewer_note: str | None = None
2766 created_at: UTCDateTime | None = None
2767 expires_at: UTCDateTime | None = None
2769 class Config:
2770 from_attributes = True
2772 class Queued(Read):
2773 """A review item as its queue serves it to those who may review
2774 it: with the answer a ``withheld`` item keeps. Never the shape of
2775 an item anywhere else — the decision record lists a turn's items
2776 to the person whose turn it was, and the answer was withheld
2777 from them."""
2779 withheld_text: str | None = None
2781 class List(BaseModel):
2782 flags: list["Schema.Review.Queued"]
2783 total: int
2785 class Resolve(BaseModel):
2786 """A reviewer's decision. Terminal — there is no reopen, which is
2787 what lets the single ``reviewed_by``/``reviewed_at`` pair on the
2788 row stand in for a full history trail."""
2790 status: Literal["reviewed", "dismissed"]
2791 note: str | None = None
2792 #: A verdict on the flagged answer itself, recorded as its
2793 #: decision outcome (``source`` review): the flag can be
2794 #: warranted and the answer still right, or not. Edits are made
2795 #: on the decision record, where the answer is.
2796 verdict: Literal["accepted", "rejected"] | None = None
2798 class Summary(BaseModel):
2799 """Counts per status, for the queue header and a stat widget."""
2801 pending: int = 0
2802 reviewed: int = 0
2803 dismissed: int = 0
2804 total: int = 0
2806 # --------------------
2807 # Governance activity — the record of rules actually running
2808 # --------------------
2809 class GovernanceActivity:
2810 class Read(BaseModel):
2811 """One rule, evaluated once, against one invocation."""
2813 id: UUID
2814 owner_user_id: UUID | None = None
2816 # Denormalised for the same reason a review flag's is: the event
2817 # has to stay readable after the rule is renamed or deleted.
2818 rule_id: UUID | None = None
2819 rule_name: str | None = None
2820 rule_version: int | None = None
2821 layer: RuleEnum.Layer
2822 scope_type: RuleEnum.Scope | None = None
2823 scope_id: UUID | None = None
2825 phase: GovernanceEnum.Phase
2826 outcome: GovernanceEnum.Outcome
2827 enforced_in: GovernanceEnum.EnforcedIn = GovernanceEnum.EnforcedIn.core
2828 #: Action types that ran, in order. Empty when the conditions did
2829 #: not hold — the rule never reached its actions.
2830 actions: list[str] = []
2831 #: Per-action specifics, keyed by action type: redaction kinds and
2832 #: counts, a block's message, the figures a quota was judged
2833 #: against. Never the text that matched.
2834 detail: dict[str, Any] = {}
2836 #: The turn this evaluation belongs to — see
2837 #: ``GovernanceEvent.invocation_id``. Both phases of one message
2838 #: share it, which is what the page groups on.
2839 invocation_id: UUID | None = None
2840 execution_type: str | None = None
2841 #: Filled in after the turn is persisted — see
2842 #: ``governance_activity.link_invocation``. Absent when the turn
2843 #: never persisted, which is itself worth being able to see.
2844 conversation_id: UUID | None = None
2845 message_id: UUID | None = None
2846 agent_id: UUID | None = None
2847 ai_model_id: UUID | None = None
2849 created_at: UTCDateTime | None = None
2851 class Config:
2852 from_attributes = True
2854 class Group(BaseModel):
2855 """Every rule that ran on one message, and what each came to.
2857 The unit the log is read in. A row per rule is what happened; a
2858 card per turn is what a person monitoring several agents is
2859 actually looking at — "this message was governed by four rules,
2860 one of which redacted something".
2861 """
2863 invocation_id: UUID | None = None
2864 occurred_at: UTCDateTime | None = None
2865 execution_type: str | None = None
2866 #: What to open to read the message these rules ran on.
2867 conversation_id: UUID | None = None
2868 message_id: UUID | None = None
2869 agent_id: UUID | None = None
2870 ai_model_id: UUID | None = None
2871 #: Resolved server-side so the card can say "Support Agent"
2872 #: rather than a UUID. Null when the resource has since been
2873 #: deleted — the events outlive it.
2874 subject: str | None = None
2875 #: Counts per outcome within this turn, for the card's header.
2876 outcomes: dict[str, int] = {}
2877 events: list["Schema.GovernanceActivity.Read"] = []
2879 class Summary(BaseModel):
2880 """Counts per outcome over the filtered set.
2882 ``no_change`` and ``not_matched`` are first-class figures rather
2883 than an "other" bucket: a rule that ran and found nothing to do is
2884 working, and a reader needs to see that it ran at all.
2885 """
2887 blocked: int = 0
2888 applied: int = 0
2889 no_change: int = 0
2890 not_matched: int = 0
2891 total: int = 0
2893 class List(BaseModel):
2894 """One page of *invocations*, newest first.
2896 ``total`` counts turns rather than events, because that is what
2897 the page pages by: cutting a turn in half at a page boundary
2898 would show a reader half its governance.
2899 """
2901 groups: list["Schema.GovernanceActivity.Group"] = []
2902 total: int
2903 summary: "Schema.GovernanceActivity.Summary"
2905 # --------------------
2906 # Network — how agents, knowledge and memory connect
2907 # (services/network/)
2908 # --------------------
2909 class Network:
2910 class Node(BaseModel):
2911 #: ``<kind>:<resource id>``, unique across kinds.
2912 id: str
2913 #: agent, repository, knowledge, memory, conversation or
2914 #: memory_entry.
2915 kind: str
2916 label: str
2917 #: The resource the node stands for; None when it is not one.
2918 ref_id: str | None = None
2919 #: Kind-specific figures. Timestamps in it carry an offset.
2920 meta: dict[str, Any] = {}
2922 class Edge(BaseModel):
2923 source: str
2924 target: str
2925 #: grant, member, memory, conversation or entry.
2926 kind: str
2928 class Read(BaseModel):
2929 nodes: list["Schema.Network.Node"]
2930 edges: list["Schema.Network.Edge"]
2931 summary: dict[str, Any] = {}
2932 #: True when a layer was capped and the graph drew only part of it.
2933 truncated: bool = False
2935 # --------------------
2936 # Dashboards — user-composed boards of widgets
2937 # --------------------
2938 # --------------------
2939 # Swarm
2940 # --------------------
2941 class Swarm:
2942 """A team of agents in a shape (``app/services/swarms``). The shape's
2943 settings and the roster are checked by the swarm service, against
2944 the shape's catalogue, before anything is stored."""
2946 class Base(_OwnerFields):
2947 name: str = Field(min_length=1, max_length=255)
2948 description: str | None = None
2949 topology: str
2950 params: dict[str, Any] = Field(default_factory=dict)
2951 roster: list[dict[str, Any]] = Field(default_factory=list)
2952 defaults: dict[str, Any] = Field(default_factory=dict)
2954 class Create(Base):
2955 pass
2957 class Edit(BaseModel):
2958 name: str | None = Field(default=None, min_length=1, max_length=255)
2959 description: str | None = None
2960 topology: str | None = None
2961 params: dict[str, Any] | None = None
2962 roster: list[dict[str, Any]] | None = None
2963 defaults: dict[str, Any] | None = None
2965 class Read(Base, _GenerationTag, _WorkspaceTag):
2966 id: UUID
2967 created_at: UTCDateTime | None = None
2968 updated_at: UTCDateTime | None = None
2970 class Config:
2971 from_attributes = True
2973 class Dashboard:
2974 class Base(_OwnerFields):
2975 name: str
2976 description: str | None = None
2977 icon: str | None = None
2978 accent: str | None = None
2979 is_home: bool = False
2980 position: int = 0
2982 class Create(Base):
2983 # Widgets may be supplied inline so a board can be created from a
2984 # template in one request.
2985 widgets: list["Schema.DashboardWidget.Create"] = []
2987 # Set by the frontend when this board is a reviewed proposal from
2988 # POST /dashboards/generate. There is no create-from-config for
2989 # dashboards — generated and hand-built boards take the same path
2990 # in — so this id is the only thing that distinguishes them, and
2991 # what makes a generated board traceable to its invocation.
2992 generation_id: UUID | None = None
2994 class Update(BaseModel):
2995 name: str | None = None
2996 description: str | None = None
2997 icon: str | None = None
2998 accent: str | None = None
2999 position: int | None = None
3001 class Read(Base, _GenerationTag, _SystemTag, _WorkspaceTag):
3002 id: UUID
3003 created_at: UTCDateTime | None = None
3004 updated_at: UTCDateTime | None = None
3005 widget_count: int = 0
3007 class Config:
3008 from_attributes = True
3010 class ReadWithWidgets(Read):
3011 widgets: list["Schema.DashboardWidget.Read"] = []
3012 #: True when at least one dynamic widget was queued for refresh by
3013 #: this request, so the client knows to poll.
3014 refreshing: bool = False
3016 class GenerateRequest(BaseModel):
3017 """Ask for a board to be composed from a description."""
3019 description: str = Field(min_length=20, max_length=2000)
3020 ai_model_id: UUID | None = None
3022 class ProposedWidget(BaseModel):
3023 """One tile in a generated board, already validated server-side."""
3025 widget_type: DashboardEnum.WidgetType
3026 title: str
3027 config: dict = Field(default_factory=dict)
3028 x: int = 0
3029 y: int = 0
3030 w: int = 4
3031 h: int = 4
3032 position: int = 0
3033 refresh_interval_seconds: int | None = None
3034 #: Why the model put this tile on the board.
3035 rationale: str = ""
3036 #: Surfaced in review so the fact/inference mix is visible before
3037 #: the board is created, not after.
3038 data_kind: DashboardEnum.DataKind
3039 #: The agent (or model) a model-backed tile will run on, by name,
3040 #: so the review says which; None for every other tile.
3041 runs_on: str | None = None
3043 class GenerationModel(BaseModel):
3044 provider: str
3045 model_name: str
3046 ai_model_id: UUID | None = None
3048 class GenerationProposal(BaseModel):
3049 """A reviewable board. Creates nothing until posted back."""
3051 name: str
3052 description: str = ""
3053 icon: str | None = None
3054 accent: str | None = None
3055 reasoning: str = ""
3056 widgets: list["Schema.Dashboard.ProposedWidget"] = []
3057 #: What was dropped or adjusted, and why.
3058 warnings: list[str] = []
3059 model: "Schema.Dashboard.GenerationModel"
3060 #: Pass back on POST /dashboards to keep the board traceable to
3061 #: the description and model that produced it.
3062 generation_id: UUID
3064 class Reorder(BaseModel):
3065 """New display order, as dashboard ids in the desired sequence."""
3067 dashboard_ids: list[UUID]
3069 class DashboardWidget:
3070 class Base(BaseModel):
3071 widget_type: DashboardEnum.WidgetType
3072 title: str | None = None
3073 config: dict = Field(default_factory=dict)
3074 x: int = 0
3075 y: int = 0
3076 w: int = 4
3077 h: int = 4
3078 position: int = 0
3079 refresh_interval_seconds: int | None = None
3081 @field_validator("refresh_interval_seconds")
3082 @classmethod
3083 def _sane_interval(cls, v: int | None) -> int | None:
3084 # A floor of 60s stops a misconfigured widget from invoking a
3085 # model on every single board load.
3086 if v is not None and v < 60:
3087 raise ValueError(
3088 "refresh_interval_seconds must be at least 60 seconds"
3089 )
3090 return v
3092 class Create(Base):
3093 pass
3095 class Update(BaseModel):
3096 title: str | None = None
3097 config: dict | None = None
3098 x: int | None = None
3099 y: int | None = None
3100 w: int | None = None
3101 h: int | None = None
3102 position: int | None = None
3103 refresh_interval_seconds: int | None = None
3105 class Read(Base):
3106 id: UUID
3107 dashboard_id: UUID
3108 cache_status: DashboardEnum.RefreshStatus = (
3109 DashboardEnum.RefreshStatus.empty
3110 )
3112 @field_validator("cache_status", mode="before")
3113 @classmethod
3114 def _default_status(cls, v: Any) -> Any:
3115 # Mirrors _GenerationTag: the column default lands at flush,
3116 # so an unflushed row still carries None.
3117 return DashboardEnum.RefreshStatus.empty if v is None else v
3119 cache_payload: dict | None = None
3120 cache_error: str | None = None
3121 cached_at: UTCDateTime | None = None
3122 created_at: UTCDateTime | None = None
3123 updated_at: UTCDateTime | None = None
3125 class Config:
3126 from_attributes = True
3128 class Placement(BaseModel):
3129 """One tile's position in a bulk layout save."""
3131 id: UUID
3132 x: int
3133 y: int
3134 w: int
3135 h: int
3137 class LayoutUpdate(BaseModel):
3138 placements: list["Schema.DashboardWidget.Placement"]
3140 class SaveItem(BaseModel):
3141 """One chat message appended to a saved-messages widget."""
3143 content: str
3144 role: str = "assistant"
3145 note: str | None = None
3146 source_label: str | None = None
3147 conversation_id: UUID | None = None
3148 message_id: UUID | None = None
3150 class ListTarget(BaseModel):
3151 """A saved-messages widget the user can save into.
3153 Served flat so the "save to dashboard" picker is one request
3154 rather than a board fetch per board.
3155 """
3157 dashboard_id: UUID
3158 dashboard_name: str
3159 dashboard_is_home: bool
3160 widget_id: UUID
3161 widget_title: str | None = None
3162 item_count: int = 0
3164 class TypeSpec(BaseModel):
3165 """Catalogue entry describing a widget type to the UI.
3167 Served from the backend registry so adding a renderer surfaces a
3168 new card in the widget picker without a frontend release.
3169 """
3171 type: DashboardEnum.WidgetType
3172 label: str
3173 description: str
3174 category: str
3175 #: stored | platform | feed | generated — lets the UI mark which
3176 #: tiles are exact data and which are a model's judgement.
3177 data_kind: DashboardEnum.DataKind
3178 is_dynamic: bool
3179 default_size: dict[str, int]
3180 default_config: dict = Field(default_factory=dict)
3181 default_refresh_interval_seconds: int | None = None
3183 # --------------------
3184 # Resource version history (audit trail)
3185 # --------------------
3186 class History:
3187 class GenerationRef(BaseModel):
3188 """The invocation behind a version, inlined into history lists.
3190 Enough to label the row ("generated by agent setup, gpt-4o")
3191 without a second request; ``GET /app/generations/{id}`` has the
3192 arguments.
3193 """
3195 id: UUID
3196 flow: GenerationEnum.Flow
3197 status: GenerationEnum.Status
3198 provider: str | None = None
3199 model_name: str | None = None
3200 created_at: UTCDateTime | None = None
3202 class VersionSummary(BaseModel):
3203 id: UUID
3204 version_number: int
3205 action: HistoryEnum.Action
3206 actor_user_id: UUID | None = None
3207 actor_name: str | None = None
3208 actor_email: str | None = None
3209 #: Who made the change, as a kind. ``user`` — a user, named
3210 #: above. ``platform`` — CHAIN-R itself: every version of a
3211 #: built-in resource is a release, written with no actor, and so
3212 #: is a version a release wrote on a user's resource (``origin``).
3213 #: ``unknown`` — no actor on a user's resource, which means the
3214 #: user has since been deleted (the actor link is SET NULL).
3215 actor_kind: Literal["user", "platform", "unknown"] = "unknown"
3216 changed_fields: list[str] = []
3217 is_ai_generated: bool | None = None
3218 generation_id: UUID | None = None
3219 generation: "Schema.History.GenerationRef | None" = None
3220 created_at: UTCDateTime | None = None
3222 class VersionList(BaseModel):
3223 versions: list["Schema.History.VersionSummary"]
3224 total: int
3226 class TextDiffLine(BaseModel):
3227 op: Literal["equal", "insert", "delete"]
3228 line: str
3230 class FieldDiff(BaseModel):
3231 field: str
3232 change_type: Literal["added", "removed", "changed", "unchanged"]
3233 old_value: Any = None
3234 new_value: Any = None
3235 text_diff: list["Schema.History.TextDiffLine"] | None = None
3237 class ChildrenDiffEntry(BaseModel):
3238 added: list[str] = []
3239 removed: list[str] = []
3241 class DiffResponse(BaseModel):
3242 from_version: int | None
3243 to_version: int
3244 fields: list["Schema.History.FieldDiff"]
3245 children_diff: dict[str, "Schema.History.ChildrenDiffEntry"] = {}
3247 class Generation:
3248 """Read models for generative invocations.
3250 There is no Create/Update pair: a run is written by the flow that
3251 performs it, never by a client.
3252 """
3254 class ProducedResource(BaseModel):
3255 """One resource a run created, for the "what came of this?" view."""
3257 resource_type: HistoryEnum.ResourceType
3258 resource_id: UUID
3259 name: str | None = None
3261 class Read(BaseModel):
3262 id: UUID
3263 flow: GenerationEnum.Flow
3264 status: GenerationEnum.Status
3265 arguments: dict[str, Any] = {}
3266 ai_model_id: UUID | None = None
3267 provider: str | None = None
3268 model_name: str | None = None
3269 target_resource_type: HistoryEnum.ResourceType | None = None
3270 target_resource_id: UUID | None = None
3271 warnings: list[str] | None = None
3272 error: str | None = None
3273 actor_user_id: UUID | None = None
3274 actor_name: str | None = None
3275 created_at: UTCDateTime | None = None
3276 applied_at: UTCDateTime | None = None
3278 class Config:
3279 from_attributes = True
3281 class ReadWithProduced(Read):
3282 produced: list["Schema.Generation.ProducedResource"] = []
3284 class List(BaseModel):
3285 generations: list["Schema.Generation.Read"]
3286 total: int
3288 class Activity:
3289 """Read models for the account-wide activity feed.
3291 ``Schema.History`` answers "what happened to *this* resource";
3292 these answer "what has happened, across everything". The rows
3293 underneath are the same ``ResourceVersion`` records — the feed is the
3294 audit trail read *across* resources rather than down one — so an
3295 event carries the same provenance a version does.
3296 """
3298 class Event(BaseModel):
3299 """One resource change, denormalised enough to render a feed row
3300 without a follow-up request per event."""
3302 id: UUID
3303 resource_type: HistoryEnum.ResourceType
3304 resource_id: UUID
3305 #: Pulled from the snapshot, so a deleted resource still has a
3306 #: name in the feed long after the row itself is gone.
3307 resource_name: str | None = None
3308 action: HistoryEnum.Action
3309 version_number: int
3310 changed_fields: list[str] = []
3311 actor_user_id: UUID | None = None
3312 actor_name: str | None = None
3313 actor_email: str | None = None
3314 is_ai_generated: bool | None = None
3315 generation_id: UUID | None = None
3316 generation: "Schema.History.GenerationRef | None" = None
3317 created_at: UTCDateTime | None = None
3319 class EventList(BaseModel):
3320 events: list["Schema.Activity.Event"]
3321 total: int
3323 class EventDetail(Event):
3324 """One event with the payload a detail panel needs: the snapshot
3325 taken at the time, and the diff against the version before it."""
3327 snapshot: dict[str, Any] = {}
3328 children_snapshot: dict[str, Any] | None = None
3329 diff: "Schema.History.DiffResponse | None" = None
3331 class TypeCount(BaseModel):
3332 resource_type: HistoryEnum.ResourceType
3333 count: int
3335 class Summary(BaseModel):
3336 """Counts over the same window the feed is showing, for the
3337 headline strip above it."""
3339 total: int = 0
3340 created: int = 0
3341 updated: int = 0
3342 deleted: int = 0
3343 ai_generated: int = 0
3344 by_resource_type: list["Schema.Activity.TypeCount"] = []
3346 class BackgroundEvent(BaseModel):
3347 """One piece of work done for the caller outside a request — a
3348 tile regenerated, a website re-crawled, flags deleted by
3349 retention. ``subject_type`` is in the resource vocabulary above,
3350 so the client links it the way it links a change."""
3352 id: UUID
3353 kind: BackgroundEnum.Kind
3354 trigger: BackgroundEnum.Trigger
3355 status: BackgroundEnum.Status
3356 subject_type: str | None = None
3357 subject_id: UUID | None = None
3358 subject_name: str | None = None
3359 summary: str
3360 detail: dict[str, Any] | None = None
3361 reference: dict[str, str] | None = None
3362 error: str | None = None
3363 started_at: UTCDateTime | None = None
3364 finished_at: UTCDateTime
3365 duration_ms: int | None = None
3367 class Config:
3368 from_attributes = True
3370 class BackgroundEventList(BaseModel):
3371 events: list["Schema.Activity.BackgroundEvent"]
3372 total: int
3373 #: How many days a row is kept before the retention job deletes
3374 #: it; None when retention is off. Served so the feed can say
3375 #: why older work is missing rather than look incomplete.
3376 retention_days: int | None = None