Spaces:
Running
Running
File size: 14,610 Bytes
fd5dd94 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | """Natural language -> workflow DSL, plus the static checks every definition must pass.
The planner model sees only the DSL rules and the tools that tool search offers for the
request (never tenant data). Its output is schema-validated, then statically checked:
* ``unknown_tool`` / ``tool_not_offered``: every tool must exist in the registry (and, for a
compiled draft, be one of the tools offered to the model);
* ``tier_escalation``: no step may use a tool above the workflow's ``max_tier``;
* ``missing_approval``: T3 steps must say ``requires_approval: true``;
* ``bad_ref`` / ``unknown_arg`` / ``missing_arg`` / ``invalid_args``: references point at
earlier steps (or ``$.item`` inside ``for_each``, ``$.event`` for event/manual triggers) and
arguments match the tool's input schema.
Anything with errors is rejected; warnings are shown to the owner with the dry run.
"""
from __future__ import annotations
import re
import uuid
from dataclasses import dataclass, field
from typing import Any
from pydantic import BaseModel, ValidationError
from core.agent.models import LLM
from core.db.session import Database
from core.tools.registry import ToolRegistry
from core.tools.search import ToolSearch
from core.tools.spec import RiskTier, ToolSpec
from core.workflows import refs
from core.workflows.dsl import (
MAX_ITEMS,
EventTrigger,
ScheduleTrigger,
Step,
WorkflowDefinition,
)
INTERNAL_PREFIX = "workflows." # engine tools (sign-off); never used directly in steps
MAX_OFFERED = 15
@dataclass(frozen=True)
class Issue:
code: str
message: str
step: str | None = None
def as_dict(self) -> dict[str, Any]:
return {"code": self.code, "message": self.message, "step": self.step}
@dataclass
class CheckReport:
errors: list[Issue] = field(default_factory=list)
warnings: list[Issue] = field(default_factory=list)
@property
def ok(self) -> bool:
return not self.errors
def as_dict(self) -> dict[str, Any]:
return {
"ok": self.ok,
"errors": [e.as_dict() for e in self.errors],
"warnings": [w.as_dict() for w in self.warnings],
}
def validation_issues(exc: ValidationError) -> list[Issue]:
out = []
for e in exc.errors(include_url=False):
loc = ".".join(str(x) for x in e.get("loc", ()))
out.append(Issue("schema", f"{loc}: {e.get('msg')}" if loc else str(e.get("msg"))))
return out
def _has_ref(value: Any) -> bool:
return next(refs.refs_in(value), None) is not None
def _check_refs(
report: CheckReport,
step_id: str | None,
values: list[Any],
earlier: dict[str, Step],
*,
loop: bool,
trigger: Any,
) -> list[str]:
"""Report bad references; return the roots used."""
roots: list[str] = []
for value in values:
for ref in refs.refs_in(value):
try:
head = refs.root(ref)
except refs.RefError as exc:
report.errors.append(Issue("bad_ref", str(exc), step_id))
continue
roots.append(head)
if head in ("item", "index"):
if not loop:
report.errors.append(
Issue(
"bad_ref", f"{ref}: $.{head} is only valid in a for_each step", step_id
)
)
elif head == "event":
if isinstance(trigger, ScheduleTrigger):
report.errors.append(
Issue("bad_ref", f"{ref}: a scheduled workflow has no event", step_id)
)
elif head == "trigger":
if not isinstance(trigger, ScheduleTrigger):
report.errors.append(
Issue("bad_ref", f"{ref}: only scheduled runs have $.trigger", step_id)
)
elif head == "workflow":
pass
elif head in ("run", "now"):
report.errors.append(Issue("bad_ref", f"{ref}: $.{head} is not supported", step_id))
elif head not in earlier:
report.errors.append(
Issue(
"bad_ref",
f"{ref}: no earlier step {head!r} (steps can only use outputs of steps "
"before them)",
step_id,
)
)
elif earlier[head].kind != "tool":
report.warnings.append(
Issue("bad_ref", f"{ref}: step {head!r} produces no data", step_id)
)
return roots
def static_check(
defn: WorkflowDefinition,
registry: ToolRegistry,
*,
offered: set[str] | None = None,
) -> CheckReport:
report = CheckReport()
trigger = defn.trigger
po = defn.policy_overrides
if isinstance(trigger, EventTrigger):
for c in trigger.when:
if refs.root(c.left) != "event":
report.errors.append(Issue("bad_ref", f"trigger condition {c.left}: use $.event"))
for name in po.require_approval_for:
if not registry.has(name):
report.warnings.append(Issue("unknown_tool", f"require_approval_for: {name} unknown"))
earlier: dict[str, Step] = {}
for step in defn.steps:
sid = step.id
_check_refs(report, sid, [step.for_each], earlier, loop=False, trigger=trigger)
cond_values = [c.left for c in step.when] + [c.right for c in step.when]
roots = _check_refs(
report,
sid,
[step.args, *cond_values],
earlier,
loop=step.for_each is not None,
trigger=trigger,
)
if step.kind == "tool":
_check_tool_step(report, step, registry, offered, po.max_tier, roots)
earlier[sid] = step
return report
def _check_tool_step(
report: CheckReport,
step: Step,
registry: ToolRegistry,
offered: set[str] | None,
max_tier: int,
roots: list[str],
) -> None:
sid, name = step.id, str(step.tool)
if name.startswith(INTERNAL_PREFIX):
report.errors.append(Issue("reserved_tool", f"{name} is an engine tool", sid))
return
if not registry.has(name):
report.errors.append(Issue("unknown_tool", f"unknown tool {name}", sid))
return
if offered is not None and name not in offered:
report.errors.append(
Issue(
"tool_not_offered", f"{name} was not among the tools offered for this request", sid
)
)
spec = registry.get(name).spec
tier = int(spec.risk_tier)
if tier > max_tier:
report.errors.append(
Issue(
"tier_escalation",
f"{name} is tier T{tier}, above this workflow's max_tier T{max_tier}",
sid,
)
)
if tier >= RiskTier.T3_CRITICAL and not step.requires_approval:
report.errors.append(
Issue(
"missing_approval",
f"{name} is tier T3: the step must declare requires_approval: true",
sid,
)
)
_check_args(report, step, spec)
if "event" in roots and spec.sensitive_args:
used = [a for a in spec.sensitive_args if _uses_event(step.args.get(a))]
if used:
report.warnings.append(
Issue(
"untrusted_sink",
f"untrusted event values reach sensitive args {used}: calls need approval "
"unless a validator confirms them",
sid,
)
)
if step.for_each and tier >= RiskTier.T2_EXTERNAL and step.max_items is None:
report.warnings.append(
Issue("unbounded_loop", f"no max_items: up to {MAX_ITEMS} external calls", sid)
)
def _uses_event(value: Any) -> bool:
return any(refs.root(r) == "event" for r in refs.refs_in(value))
def _check_args(report: CheckReport, step: Step, spec: ToolSpec) -> None:
model: type[BaseModel] = spec.input_model
fields = model.model_fields
unknown = sorted(set(step.args) - set(fields))
if unknown:
report.errors.append(
Issue("unknown_arg", f"{spec.name} has no argument(s) {unknown}", step.id)
)
missing = sorted(n for n, f in fields.items() if f.is_required() and n not in step.args)
if missing:
report.errors.append(
Issue("missing_arg", f"{spec.name} needs argument(s) {missing}", step.id)
)
if not unknown and not missing and not _has_ref(step.args):
try:
model.model_validate(step.args)
except ValidationError as exc:
msgs = "; ".join(i.message for i in validation_issues(exc))
report.errors.append(Issue("invalid_args", f"{spec.name}: {msgs}", step.id))
def check(
data: dict[str, Any] | WorkflowDefinition,
registry: ToolRegistry,
*,
offered: set[str] | None = None,
) -> tuple[WorkflowDefinition | None, CheckReport]:
"""Schema validation + static checks."""
if isinstance(data, WorkflowDefinition):
defn = data
else:
try:
defn = WorkflowDefinition.model_validate(data)
except ValidationError as exc:
return None, CheckReport(errors=validation_issues(exc))
return defn, static_check(defn, registry, offered=offered)
# ------------------------------------------------------------------- NL compiler
DSL_RULES = """\
You turn a business owner's request into a workflow definition (JSON). Rules:
- trigger: {"type": "schedule", "cron": "<5-field cron>", "tz": "Asia/Karachi"} for repeated
times ("every morning at 9" -> "0 9 * * *"); {"type": "event", "event_type": "..."} for
"when X happens"; {"type": "manual"} otherwise.
- steps run in order. A tool step: {"id": "snake_case", "tool": "<one of the tools below>",
"args": {...}}. Use only the tools listed below and only their argument names.
- Reference earlier outputs with strings like "$.<step_id>.<field>" (e.g. "$.find.orders").
To repeat a step for every element of a list, set "for_each": "$.<step_id>.<list field>"
and use "$.item.<field>" in args. A for_each step's output is
{"results": [{"item": ..., "data": ...}]}: a later loop over it uses "$.item.item.<field>"
for the original element and "$.item.data.<field>" for that step's result.
- Use "{{ $.ref }}" inside longer text.
- Filters: "when": [{"left": "$.item.total", "op": "gt", "right": 5000}].
- Tools marked T3 need "requires_approval": true. Never invent tools or recipients.
- Put limits that the request implies into "policy_overrides" (max_messages, max_tier).
"""
def tool_card(spec: ToolSpec) -> str:
schema = spec.input_model.model_json_schema()
props = schema.get("properties", {})
required = set(schema.get("required", []))
args = []
for name, p in props.items():
kind = p.get("type") or "/".join(
str(x.get("type")) for x in p.get("anyOf", []) if x.get("type") != "null"
)
enum = p.get("enum") or next(
(x.get("enum") for x in p.get("anyOf", []) if x.get("enum")), None
)
desc = f"{name}{'' if name in required else '?'}: {kind}"
if enum:
desc += f" one of {enum}"
args.append(desc)
return (
f"- {spec.name} [T{int(spec.risk_tier)}]: {spec.description}\n"
f" args: {', '.join(args) or '(none)'}"
)
def compiler_prompt(specs: list[ToolSpec]) -> str:
cards = "\n".join(tool_card(s) for s in specs)
return f"{DSL_RULES}\nTools you may use:\n{cards}"
@dataclass
class CompileResult:
definition: WorkflowDefinition | None
report: CheckReport
offered: list[str]
def as_dict(self) -> dict[str, Any]:
return {
"definition": self.definition.model_dump(mode="json") if self.definition else None,
**self.report.as_dict(),
"tools_offered": self.offered,
}
async def candidate_tools(
db: Database,
tenant_id: uuid.UUID,
registry: ToolRegistry,
text: str,
*,
search: ToolSearch | None = None,
k: int = MAX_OFFERED,
) -> list[str]:
"""Tools offered to the compiler: hybrid tool search over the index, limited to tools
this process can execute. Falls back to the registry when the index is empty."""
names: list[str] = []
if search is not None:
try:
async with db.session(tenant_id=tenant_id) as s:
names = await search.search(s, text, k=k * 2)
except Exception: # index missing (e.g. not synced yet): fall back below
names = []
names = [n for n in dict.fromkeys(names) if registry.has(n)]
# Fill up from the registry, ranked in process the same way (covers an empty or stale
# index, e.g. tools registered after the last ``sync-tools``).
names += [n for n in rank_locally(registry, text) if n not in names]
return [n for n in names if not n.startswith(INTERNAL_PREFIX)][:k]
def rank_locally(registry: ToolRegistry, text: str) -> list[str]:
from core.tools.search import HashingEmbedder, _search_text
emb = HashingEmbedder()
q = emb.embed(text)
words = set(re.findall(r"[a-z0-9]+", text.lower()))
def score(spec: ToolSpec) -> float:
doc = _search_text(spec)
cosine = sum(a * b for a, b in zip(q, emb.embed(doc), strict=True))
overlap = len(words & set(re.findall(r"[a-z0-9]+", doc.lower())))
return cosine + 0.1 * overlap
return [s.name for s in sorted(registry.specs(), key=score, reverse=True)]
async def compile_nl(
text: str, llm: LLM, registry: ToolRegistry, offered: list[str]
) -> CompileResult:
specs = [registry.get(n).spec for n in offered if registry.has(n)]
try:
draft = await llm.structured(WorkflowDefinition, compiler_prompt(specs), text)
except ValidationError as exc:
return CompileResult(None, CheckReport(errors=validation_issues(exc)), offered)
defn = draft.model_copy(update={"version": None})
return CompileResult(defn, static_check(defn, registry, offered=set(offered)), offered)
|