Spaces:
Running

WorkPilot-AI / core /rules /ast.py
Aynkhn's picture
Deploy WorkPilot demo
fd5dd94 verified
Raw History Blame Contribute Delete
9.88 kB
"""The rule AST, its deterministic Cedar and plain-language renderings, and rule tests.
The planner model never writes Cedar. It fills ``RuleAST`` (a closed vocabulary: three
effects, six comparison operators, known tools and known arguments only), the AST is
validated against the live tool catalog, and Cedar is *rendered* from it by code.
Effects and how the gateway's policy engine treats them:
* ``require_approval`` -> ``forbid`` annotated ``@id("review.…")``: a matching call is not
denied but held for a human (``core.gateway.policy``: review-only forbids -> REVIEW);
* ``forbid`` -> plain ``forbid``: a matching call is denied, even with approval;
* ``permit`` -> ``permit``: a matching call to a tool of tier T2 or lower runs without
approval. Only by explicit owner choice, and never for T3 (the engine keeps T3 in review).
``require_approval`` and ``forbid`` can only tighten (Cedar: forbid always wins).
"""
from __future__ import annotations
import itertools
import re
from dataclasses import dataclass, field
from typing import Any, Literal
import cedarpy
from pydantic import BaseModel, Field
from core.gateway.policy import REVIEW_PREFIX
Op = Literal["gt", "ge", "lt", "le", "eq", "ne"]
OPS = {"gt": ">", "ge": ">=", "lt": "<", "le": "<=", "eq": "==", "ne": "!="}
WORDS = {
"gt": "is more than",
"ge": "is at least",
"lt": "is less than",
"le": "is at most",
"eq": "is",
"ne": "is not",
}
NUMERIC = ("integer", "number")
_STR_VALUE = re.compile(r"^[\w .@:/+#,-]{0,100}$", re.UNICODE)
_ARG = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
_TOOL = re.compile(r"^[A-Za-z0-9_.:-]{1,200}$")
class Condition(BaseModel):
arg: str = Field(description="argument name of the tool, exactly as listed")
op: Op
value: bool | int | str = Field(description="whole numbers for amounts (10k = 10000)")
class RuleAST(BaseModel):
effect: Literal["require_approval", "forbid", "permit"]
tools: list[str] = Field(min_length=1, max_length=10, description="tool names, as listed")
conditions: list[Condition] = Field(default_factory=list, max_length=5)
principal: Literal["any", "agent", "user"] = Field(
default="any", description="agent = the AI agent, user = a human operator"
)
class RuleDraft(BaseModel):
"""What the planner model returns."""
understood: bool
rule: RuleAST | None = None
question: str | None = Field(default=None, description="clarifying question if not")
@dataclass(frozen=True)
class ToolInfo:
name: str
description: str
tier: int
args: dict[str, str] = field(default_factory=dict) # field name -> json type
Catalog = dict[str, ToolInfo]
def validate_rule(rule: RuleAST, catalog: Catalog) -> list[str]:
errors: list[str] = []
for t in rule.tools:
if t not in catalog or not _TOOL.match(t):
errors.append(f"unknown tool {t!r}")
if len(set(rule.tools)) != len(rule.tools):
errors.append("a tool is listed twice")
for c in rule.conditions:
if not _ARG.match(c.arg):
errors.append(f"invalid argument name {c.arg!r}")
continue
for t in rule.tools:
info = catalog.get(t)
if info is None:
continue
kind = info.args.get(c.arg)
if kind is None:
errors.append(f"tool {t} has no argument {c.arg!r}")
elif c.op in ("gt", "ge", "lt", "le"):
if kind not in NUMERIC or isinstance(c.value, bool) or not isinstance(c.value, int):
errors.append(f"{c.arg} on {t}: '{c.op}' needs a numeric argument and value")
elif kind == "boolean" and not isinstance(c.value, bool):
errors.append(f"{c.arg} on {t} is yes/no; the value must be true or false")
elif kind == "string" and not isinstance(c.value, str):
errors.append(f"{c.arg} on {t} is text; the value must be text")
elif kind in NUMERIC and (isinstance(c.value, bool) or not isinstance(c.value, int)):
errors.append(f"{c.arg} on {t} is a number; the value must be a whole number")
if isinstance(c.value, str) and not _STR_VALUE.match(c.value):
errors.append(f"value for {c.arg} has unsupported characters")
if rule.effect == "permit":
for t in rule.tools:
info = catalog.get(t)
if info is not None and info.tier >= 3:
errors.append(f"{t} is tier T3: it always needs a human and cannot be permitted")
return errors
def _literal(value: bool | int | str) -> str:
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, int):
return str(value)
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
def policy_id(rule: RuleAST, rule_id: str) -> str:
kind = {
"require_approval": f"{REVIEW_PREFIX}rule",
"forbid": "forbid.rule",
"permit": "permit.rule",
}
return f"{kind[rule.effect]}.{rule_id}"
def render_cedar(rule: RuleAST, rule_id: str) -> str:
actions = ", ".join(f'Action::"{t}"' for t in rule.tools)
conds = [
f"(context.args has {c.arg} && context.args.{c.arg} {OPS[c.op]} {_literal(c.value)})"
for c in rule.conditions
]
if rule.principal != "any":
conds.insert(0, f'principal.kind == "{rule.principal}"')
effect = "permit" if rule.effect == "permit" else "forbid"
when = f"\nwhen {{ {' && '.join(conds)} }}" if conds else ""
return (
f'@id("{policy_id(rule, rule_id)}")\n'
f"{effect} (principal, action in [{actions}], resource){when};"
)
def _value_text(v: bool | int | str) -> str:
if isinstance(v, bool):
return "yes" if v else "no"
if isinstance(v, int):
return f"{v:,}"
return f'"{v}"'
def render_plain(rule: RuleAST) -> str:
who = {"any": "", "agent": " made by the AI agent", "user": " made by a team member"}
tools = ", ".join(rule.tools)
where = " and ".join(f"{c.arg} {WORDS[c.op]} {_value_text(c.value)}" for c in rule.conditions)
scope = f"Calls to {tools}{who[rule.principal]}" + (f" where {where}" if where else "")
then = {
"require_approval": "need your approval before they run.",
"forbid": "are blocked, even with approval.",
"permit": "may run automatically without approval (unless another rule blocks them).",
}
return f"{scope} {then[rule.effect]}"
def check_syntax(cedar: str) -> None:
"""Raises ``ValueError`` if Cedar cannot parse the text."""
cedarpy.policies_to_json_str(cedar)
# -------------------------------------------------------------------------- tests
def _just(c: Condition, satisfy: bool) -> bool | int | str:
v = c.value
if isinstance(v, bool):
return v if (c.op == "eq") == satisfy else (not v)
if isinstance(v, int):
inside = {"gt": v + 1, "ge": v, "lt": v - 1, "le": v, "eq": v, "ne": v + 1}
outside = {"gt": v, "ge": v - 1, "lt": v, "le": v + 1, "eq": v + 1, "ne": v}
return inside[c.op] if satisfy else outside[c.op]
other = f"{v}_other" if v else "other"
if c.op == "eq":
return v if satisfy else other
return other if satisfy else v
def sample_calls(rule: RuleAST) -> list[dict[str, Any]]:
"""Boundary samples: one that matches every condition, one per condition that misses it,
for the first tool; both principals when the rule names one."""
tool = rule.tools[0]
actors = ["agent", "user"] if rule.principal != "any" else ["agent"]
out: list[dict[str, Any]] = []
for actor, miss in itertools.product(actors, [None, *range(len(rule.conditions))]):
if actor != actors[0] and miss is not None:
continue
args = {c.arg: _just(c, i != miss) for i, c in enumerate(rule.conditions)}
out.append({"tool": tool, "args": args, "actor": actor})
return out
def evaluate_samples(
rule: RuleAST, cedar: str, samples: list[dict[str, Any]]
) -> list[dict[str, Any]]:
"""Evaluate the rule *alone* against sample calls: does it match, and what happens then."""
base = "" if rule.effect == "permit" else "\npermit (principal, action, resource);"
effect = {
"require_approval": "needs approval",
"forbid": "blocked",
"permit": "runs automatically",
}[rule.effect]
results = []
for sample in samples:
actor = str(sample.get("actor") or "agent")
kind = "user" if actor == "user" else "agent"
ptype = "User" if kind == "user" else "Agent"
args = {k: v for k, v in (sample.get("args") or {}).items() if v is not None}
request = {
"principal": f'{ptype}::"sample"',
"action": f'Action::"{sample["tool"]}"',
"resource": 'Tenant::"sample"',
"context": {"args": args},
}
entities = [
{"uid": {"type": ptype, "id": "sample"}, "attrs": {"kind": kind}, "parents": []}
]
r = cedarpy.is_authorized(request, cedar + base, entities)
errors = [str(e) for e in r.diagnostics.errors]
allowed = r.decision == cedarpy.Decision.Allow
matched = allowed if rule.effect == "permit" else not allowed
results.append(
{
"tool": sample["tool"],
"args": args,
"actor": kind,
"matched": matched and not errors,
"outcome": effect if matched and not errors else "not affected by this rule",
"errors": errors,
}
)
return results