Coverage for app / services / skill_runs / schema.py: 86%
261 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"""
2What a skill needs from whoever runs it — the form a run implies.
4A skill graph can say what it takes in two ways. The explicit one is its
5``interface.inputs``: typed fields, declared by the author, that seed the
6graph state before the first node runs. The implicit one is everything else a
7node reads that nothing in the graph writes:
9* a worker's ``input_schema`` field left **unbound** on its node — svc-ai
10 auto-binds it from a same-named graph variable (``_bind_inputs`` in
11 ``agents/graph.py``), so a ``research`` worker declaring ``topic: string``
12 is asking for a ``topic`` whether or not the author thought to declare one;
13* a declared ``state`` key with no default that no node writes, and that some
14 node reads;
15* a ``{placeholder}`` in a node's ``prompt_template`` naming such a variable.
17Run inputs seed ``state_vars`` whether declared or not (svc-ai's
18``_seed_interface_inputs`` passes undeclared keys through), so every one of
19these can be filled from a form, and each carries the FieldSpec of whatever
20declared it — which is what makes an ``object`` input a JSON editor and an
21``enum`` a select rather than a text box.
23The same schema validates what a run is given, so the form and the API agree
24on what "valid input" means and a missing required field is a 422 naming it,
25not a run that starts and then warns in a log nobody reads.
26"""
28from __future__ import annotations
30import json
31import re
32from dataclasses import dataclass, field
33from enum import StrEnum
34from typing import Any, Callable, Iterable
36#: Mirrors ``_PLACEHOLDER_RE`` in crud_schemas and svc-ai's operations module.
37_PLACEHOLDER_RE = re.compile(r"\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_]+)*)\}")
38_FIELD_TYPES = frozenset(
39 {"string", "number", "integer", "boolean", "enum", "array", "object"}
40)
41#: Variables every graph has without anyone supplying them.
42_IMPLICIT_VARS = frozenset({"input", "inputs"})
45class FieldSource(StrEnum):
46 """Where a run field was declared — shown so the author can see why the
47 form is asking for it."""
49 #: ``interface.inputs`` — the skill's explicit contract.
50 interface = "interface"
51 #: A declared ``state`` key nothing writes and nothing defaults.
52 state = "state"
53 #: An unbound ``input_schema`` field of a node's worker.
54 node = "node"
55 #: A ``{placeholder}`` in a node's prompt template.
56 template = "template"
59@dataclass
60class RunField:
61 """One value a run can be given. The FieldSpec shape, plus provenance."""
63 name: str
64 type: str = "string"
65 description: str = ""
66 required: bool = False
67 default: Any = None
68 values: list[str] = field(default_factory=list)
69 items: str = "string"
70 source: FieldSource = FieldSource.interface
71 #: Nodes that read it, in graph order.
72 consumers: list[str] = field(default_factory=list)
74 def as_dict(self) -> dict[str, Any]:
75 return {
76 "name": self.name,
77 "type": self.type,
78 "description": self.description,
79 "required": self.required,
80 "default": self.default,
81 "values": list(self.values),
82 "items": self.items,
83 "source": self.source.value,
84 "consumers": list(self.consumers),
85 }
88@dataclass
89class RunSchema:
90 fields: list[RunField] = field(default_factory=list)
91 #: False when a worker's interface could not be looked up (svc-ai down),
92 #: so the form may be missing fields. Validation is then lenient about
93 #: keys it does not recognise rather than refuse a field it cannot see.
94 complete: bool = True
96 @property
97 def requires_prompt(self) -> bool:
98 """A skill with no fields has nothing to run on but the task text."""
99 return not self.fields
101 def get(self, name: str) -> RunField | None:
102 return next((f for f in self.fields if f.name == name), None)
104 def as_dict(self) -> dict[str, Any]:
105 return {
106 "fields": [f.as_dict() for f in self.fields],
107 "requires_prompt": self.requires_prompt,
108 "complete": self.complete,
109 }
112#: Looks up worker ``input_schema`` lists by ``agent_name``. Names it cannot
113#: resolve are simply absent; raising means "could not look anything up".
114DefinitionLookup = Callable[[set[str]], dict[str, list[dict]]]
117def _roots(value: Any) -> set[str]:
118 """Root variable names referenced by a binding, template or structure."""
119 if isinstance(value, str):
120 return {m.split(".", 1)[0] for m in _PLACEHOLDER_RE.findall(value)}
121 if isinstance(value, dict):
122 return set().union(*(_roots(v) for v in value.values())) if value else set()
123 if isinstance(value, list):
124 return set().union(*(_roots(v) for v in value)) if value else set()
125 return set()
128def _node_reads(node: dict[str, Any]) -> set[str]:
129 """Every variable a node references explicitly."""
130 roots = _roots(node.get("inputs") or {})
131 roots |= _roots(node.get("prompt_template") or "")
132 roots |= {str(k).split(".", 1)[0] for k in node.get("input_keys") or [] if k}
133 tool = node.get("tool")
134 if isinstance(tool, dict):
135 roots |= _roots(tool.get("args") or {})
136 op = node.get("operation")
137 if isinstance(op, dict):
138 kind = op.get("op")
139 if kind == "template":
140 roots |= _roots(op.get("template") or "")
141 elif kind == "merge":
142 roots |= {str(k).split(".", 1)[0] for k in op.get("keys") or [] if k}
143 elif kind in ("select", "parse") and op.get("key"):
144 roots.add(str(op["key"]).split(".", 1)[0])
145 elif kind == "compose":
146 roots |= _roots(op.get("fields") or {})
147 return roots
150def _ordered_nodes(graph: dict[str, Any]) -> list[tuple[str, dict[str, Any]]]:
151 """Nodes breadth-first from the start node, then any the walk missed —
152 so a form lists what the first node needs before what the last one does."""
153 nodes = graph.get("nodes") if isinstance(graph.get("nodes"), dict) else {}
154 nodes = {str(k): v for k, v in nodes.items() if isinstance(v, dict)}
155 adjacency: dict[str, list[str]] = {}
156 for edge in graph.get("edges") or []:
157 if isinstance(edge, (list, tuple)) and len(edge) == 2:
158 adjacency.setdefault(str(edge[0]), []).append(str(edge[1]))
159 for src, cfg in (graph.get("conditional_edges") or {}).items():
160 if not isinstance(cfg, dict):
161 continue
162 targets = [
163 b.get("target") for b in cfg.get("branches") or [] if isinstance(b, dict)
164 ]
165 targets += list((cfg.get("edge_map") or {}).values())
166 targets.append(cfg.get("default"))
167 adjacency.setdefault(str(src), []).extend(str(t) for t in targets if t)
169 order: list[str] = []
170 frontier = [str(graph.get("start_node") or "")]
171 while frontier:
172 current = frontier.pop(0)
173 if current in nodes and current not in order:
174 order.append(current)
175 frontier.extend(adjacency.get(current, []))
176 order += [n for n in nodes if n not in order]
177 return [(n, nodes[n]) for n in order]
180def _spec_field(raw: dict[str, Any], source: FieldSource) -> RunField | None:
181 name = raw.get("name")
182 if not isinstance(name, str) or not name:
183 return None
184 kind = raw.get("type") if raw.get("type") in _FIELD_TYPES else "string"
185 return RunField(
186 name=name,
187 type=kind,
188 description=str(raw.get("description") or ""),
189 required=bool(raw.get("required", True)) and raw.get("default") is None,
190 default=raw.get("default"),
191 values=[str(v) for v in raw.get("values") or []],
192 items=raw.get("items") if raw.get("items") in _FIELD_TYPES else "string",
193 source=source,
194 )
197def build_run_schema(
198 graph: dict[str, Any], lookup: DefinitionLookup | None = None
199) -> RunSchema:
200 """The fields a run of ``graph`` can be given, in the order it reads them.
202 ``lookup`` resolves the ``input_schema`` of workers a node names without
203 carrying one inline. Without it, or when it raises, those nodes contribute
204 nothing and the schema says it is incomplete.
205 """
206 graph = graph or {}
207 ordered = _ordered_nodes(graph)
208 node_ids = {n for n, _ in ordered}
209 output_keys = {str(c["output_key"]) for _, c in ordered if c.get("output_key")}
210 produced = node_ids | output_keys | _IMPLICIT_VARS
212 state_spec = graph.get("state") if isinstance(graph.get("state"), dict) else {}
213 defaulted_state = {
214 k
215 for k, v in state_spec.items()
216 if isinstance(v, dict) and v.get("default") is not None
217 }
219 fields: dict[str, RunField] = {}
220 schema = RunSchema()
222 # 1. The declared contract, authoritative for anything it names.
223 interface = (
224 graph.get("interface") if isinstance(graph.get("interface"), dict) else {}
225 )
226 for raw in interface.get("inputs") or []:
227 if isinstance(raw, dict):
228 spec = _spec_field(raw, FieldSource.interface)
229 if spec is not None and spec.name not in fields:
230 fields[spec.name] = spec
232 # Worker interfaces for agent nodes that do not carry their own.
233 wanted = {
234 str(cfg.get("agent_name"))
235 for _, cfg in ordered
236 if (cfg.get("type") or "agent") == "agent"
237 and cfg.get("agent_name")
238 and cfg.get("input_schema") is None
239 }
240 definitions: dict[str, list[dict]] = {}
241 if wanted:
242 if lookup is None:
243 schema.complete = False
244 else:
245 try:
246 definitions = lookup(wanted)
247 except Exception: # noqa: BLE001 — a lookup failure degrades, never fails
248 schema.complete = False
250 def _supplied(name: str) -> bool:
251 return name in produced or name in defaulted_state
253 def _consume(name: str, node_id: str) -> None:
254 run_field = fields.get(name)
255 if run_field is not None and node_id not in run_field.consumers:
256 run_field.consumers.append(node_id)
258 for node_id, cfg in ordered:
259 reads = _node_reads(cfg)
260 bound = set((cfg.get("inputs") or {}).keys())
262 # 2. Unbound worker inputs: auto-bound by name from the graph state.
263 if (cfg.get("type") or "agent") == "agent":
264 raw_schema = cfg.get("input_schema")
265 if raw_schema is None:
266 raw_schema = definitions.get(str(cfg.get("agent_name") or ""), [])
267 for raw in raw_schema or []:
268 if not isinstance(raw, dict) or raw.get("name") in bound:
269 continue
270 name = str(raw.get("name") or "")
271 if not name or _supplied(name):
272 continue
273 if name not in fields:
274 spec = _spec_field(raw, FieldSource.node)
275 if spec is None:
276 continue
277 fields[name] = spec
278 _consume(name, node_id)
280 for root in sorted(reads):
281 if root in fields:
282 _consume(root, node_id)
283 continue
284 if _supplied(root):
285 continue
286 # 3. A declared state key nothing writes or defaults.
287 if root in state_spec and isinstance(state_spec[root], dict):
288 declared = state_spec[root]
289 fields[root] = RunField(
290 name=root,
291 type=declared.get("type")
292 if declared.get("type") in _FIELD_TYPES
293 else "string",
294 description=str(declared.get("description") or ""),
295 source=FieldSource.state,
296 consumers=[node_id],
297 )
298 # 4. A template placeholder naming nothing else. Only templates:
299 # every other kind of reference is checked at save time, so an
300 # unknown root there cannot exist.
301 elif root in _roots(cfg.get("prompt_template") or ""):
302 fields[root] = RunField(
303 name=root, source=FieldSource.template, consumers=[node_id]
304 )
306 schema.fields = list(fields.values())
307 return schema
310# ── Validation ────────────────────────────────────────────────────────────────
312_TRUE = {"true", "1", "yes", "y", "on"}
313_FALSE = {"false", "0", "no", "n", "off"}
316class _Invalid(ValueError):
317 pass
320def _coerce_scalar(kind: str, value: Any, values: Iterable[str] = ()) -> Any:
321 if kind == "string":
322 if isinstance(value, (dict, list)):
323 return json.dumps(value, ensure_ascii=False)
324 return str(value)
325 if kind in ("number", "integer"):
326 if isinstance(value, bool):
327 raise _Invalid("expected a number, got true/false")
328 try:
329 number = float(value)
330 except (TypeError, ValueError):
331 raise _Invalid(f"{value!r} is not a number") from None
332 if kind == "number":
333 return (
334 int(number)
335 if number.is_integer() and isinstance(value, int)
336 else number
337 )
338 if not number.is_integer():
339 raise _Invalid(f"{value!r} is not a whole number")
340 return int(number)
341 if kind == "boolean":
342 if isinstance(value, bool):
343 return value
344 text = str(value).strip().lower()
345 if text in _TRUE:
346 return True
347 if text in _FALSE:
348 return False
349 raise _Invalid(f"{value!r} is not true or false")
350 if kind == "enum":
351 allowed = list(values)
352 text = str(value)
353 if not allowed or text in allowed:
354 return text
355 folded = {v.lower(): v for v in allowed}
356 if text.lower() in folded:
357 return folded[text.lower()]
358 raise _Invalid(f"must be one of {', '.join(allowed)}")
359 return value
362def coerce_value(run_field: RunField, value: Any) -> Any:
363 """``value`` as ``run_field``'s type, or ``ValueError`` saying why not.
365 Lenient where the conversion is unambiguous, the same way svc-ai's
366 ``coerce_value`` is — a form sends numbers as strings and arrays as JSON.
367 """
368 kind = run_field.type
369 if kind == "array":
370 if isinstance(value, str):
371 text = value.strip()
372 if text.startswith("["):
373 try:
374 value = json.loads(text)
375 except json.JSONDecodeError as exc:
376 raise _Invalid(f"not a valid JSON list ({exc.msg})") from None
377 else:
378 # svc-ai splits on commas; one item per line is what a text
379 # box gives, and a line may itself contain commas.
380 sep = "\n" if "\n" in text else ","
381 value = [part.strip() for part in text.split(sep) if part.strip()]
382 if not isinstance(value, list):
383 value = [value]
384 return [_coerce_scalar(run_field.items, item) for item in value]
385 if kind == "object":
386 if isinstance(value, str):
387 try:
388 value = json.loads(value)
389 except json.JSONDecodeError as exc:
390 raise _Invalid(f"not valid JSON ({exc.msg})") from None
391 if not isinstance(value, dict):
392 raise _Invalid("expected a JSON object")
393 return value
394 return _coerce_scalar(kind, value, run_field.values)
397def _blank(value: Any) -> bool:
398 return value is None or (isinstance(value, str) and not value.strip())
401def validate_inputs(
402 schema: RunSchema, values: dict[str, Any]
403) -> tuple[dict[str, Any], dict[str, str]]:
404 """``(coerced, errors)`` — errors keyed by field name.
406 Blank values are dropped, so an optional field left empty in a form is
407 absent rather than an empty string that would shadow its default.
408 """
409 coerced: dict[str, Any] = {}
410 errors: dict[str, str] = {}
411 for name, value in (values or {}).items():
412 run_field = schema.get(name)
413 if run_field is None:
414 if schema.complete:
415 errors[name] = "this skill does not take an input by that name"
416 elif not _blank(value):
417 coerced[name] = value
418 continue
419 if _blank(value):
420 continue
421 try:
422 coerced[name] = coerce_value(run_field, value)
423 except ValueError as exc:
424 errors[name] = str(exc)
425 for run_field in schema.fields:
426 if run_field.required and run_field.name not in coerced:
427 errors.setdefault(run_field.name, "required")
428 return coerced, errors
431# ── Task text ─────────────────────────────────────────────────────────────────
434def _render(value: Any) -> str:
435 if isinstance(value, str):
436 return value if "\n" not in value else "\n " + value.replace("\n", "\n ")
437 return json.dumps(value, ensure_ascii=False)
440def compose_task(
441 skill_name: str,
442 description: str | None,
443 prompt: str | None,
444 inputs: dict[str, Any],
445) -> str:
446 """The task text a run hands svc-ai.
448 The inputs reach the graph as state either way; they are written into the
449 task as well so the pipeline's own nodes (gate, planner, synthesis) see
450 what was asked, and so the policy rules evaluate the same text the model
451 is given — a block rule on a word in a form field applies to that field.
452 """
453 parts: list[str] = []
454 if prompt and prompt.strip():
455 parts.append(prompt.strip())
456 else:
457 header = f"Run the “{skill_name}” workflow"
458 parts.append(
459 f"{header}: {description.strip()}" if description else f"{header}."
460 )
461 if inputs:
462 parts.append("Inputs:\n" + render_values(inputs))
463 return "\n\n".join(parts)
466def render_values(values: dict[str, Any]) -> str:
467 """Named values as a bullet list, one per line — how a run's inputs and
468 outputs are written into text that rules and models read."""
469 return "\n".join(f"- {name}: {_render(value)}" for name, value in values.items())