Spaces:
Running
Running
File size: 11,583 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 | """Natural-language rules -> Cedar: compile, preview, confirm, version, roll back.
Flow (owner-facing)::
"refunds over 10k need my approval"
-> planner model fills a ``RuleDraft`` (constrained AST, structured output only)
-> AST validated against the live tool catalog (pack + tenant tools, arg types)
-> Cedar rendered by code (``core.rules.ast.render_cedar``), parsed by cedarpy
-> plain-language rendering + the rule tested against boundary sample calls
-> stored as a *draft* version; nothing changes yet
owner confirms -> version becomes ``active``; the previous active version is superseded
-> ``tenants.settings.rule_policies`` is rebuilt from the active versions; the
gateway evaluates them with the tenant's other policies on the next call.
Rollback re-activates the previous version (or leaves the rule with none active).
"""
from __future__ import annotations
import typing
import uuid
from datetime import UTC, datetime
from typing import Any
from sqlalchemy import func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from core.agent.models import LLM
from core.gateway.policy import PolicyEngine
from core.rules.ast import (
Catalog,
RuleAST,
RuleDraft,
ToolInfo,
check_syntax,
evaluate_samples,
render_cedar,
render_plain,
sample_calls,
validate_rule,
)
from core.rules.models import PolicyRule
from core.tenancy.models import Tenant
from core.tools.registry import ToolRegistry
from core.tools.spec import ToolSpec
from core.tools.tenant_tools import TenantToolStore
MAX_TEXT = 500
class RuleError(ValueError):
"""Compile/confirm failed; ``question`` is a clarifying question for the owner."""
def __init__(
self, message: str, *, errors: list[str] | None = None, question: str | None = None
):
super().__init__(message)
self.errors = errors or []
self.question = question
def _json_type(annotation: Any) -> str:
args = [a for a in typing.get_args(annotation) if a is not type(None)]
if args and typing.get_origin(annotation) is not None and len(args) == 1:
annotation = args[0]
if annotation is bool:
return "boolean"
if annotation is int:
return "integer"
if annotation is float:
return "number"
if annotation is str or typing.get_origin(annotation) is typing.Literal:
return "string"
return "other"
def tool_info(spec: ToolSpec) -> ToolInfo:
args = {n: _json_type(f.annotation) for n, f in spec.input_model.model_fields.items()}
return ToolInfo(
name=spec.name, description=spec.description, tier=int(spec.risk_tier), args=args
)
async def build_catalog(
s: AsyncSession, registry: ToolRegistry, store: TenantToolStore | None
) -> Catalog:
catalog = {spec.name: tool_info(spec) for spec in registry.specs()}
if store is not None:
for row in await store.list_tools(s):
if row.blocked_reason is None:
catalog[row.name] = tool_info(store.spec(row))
return catalog
def planner_prompt(catalog: Catalog) -> str:
lines = []
for info in catalog.values():
args = ", ".join(f"{n}: {t}" for n, t in info.args.items() if t != "other")
lines.append(f"- {info.name} (tier T{info.tier}): {info.description[:160]} | args: {args}")
return (
"You turn a business owner's rule into a structured rule for an approval system. "
"Effects: require_approval = a human must approve matching calls; forbid = matching "
"calls are never allowed; permit = matching calls may run automatically (ONLY if the "
"owner explicitly says something may happen automatically / without approval). "
"Use only these tools and their listed arguments:\n"
+ "\n".join(lines)
+ "\nComparisons: gt, ge, lt, le, eq, ne. Amounts are whole numbers: 10k = 10000, "
"1 lakh = 100000. principal: agent (the AI), user (a human operator) or any. "
"If the rule is ambiguous or cannot be expressed with these tools and arguments, set "
"understood=false and ask one short question."
)
class RuleService:
def __init__(self, engine: PolicyEngine) -> None:
self.engine = engine
async def compile(
self,
s: AsyncSession,
tenant_id: uuid.UUID,
*,
text: str,
llm: LLM,
catalog: Catalog,
user_id: uuid.UUID | None = None,
rule_key: uuid.UUID | None = None,
samples: list[dict[str, Any]] | None = None,
) -> PolicyRule:
text = text.strip()
if not 3 <= len(text) <= MAX_TEXT:
raise RuleError(f"a rule is 3-{MAX_TEXT} characters")
draft = await llm.structured(RuleDraft, planner_prompt(catalog), text)
if not draft.understood or draft.rule is None:
raise RuleError(
"the rule could not be understood",
question=draft.question or "Which action and which condition do you mean?",
)
return await self.draft_from_ast(
s,
tenant_id,
rule=draft.rule,
text=text,
catalog=catalog,
user_id=user_id,
rule_key=rule_key,
samples=samples,
)
async def draft_from_ast(
self,
s: AsyncSession,
tenant_id: uuid.UUID,
*,
rule: RuleAST,
text: str,
catalog: Catalog,
user_id: uuid.UUID | None = None,
rule_key: uuid.UUID | None = None,
samples: list[dict[str, Any]] | None = None,
) -> PolicyRule:
errors = validate_rule(rule, catalog)
if errors:
raise RuleError("the rule does not fit the available tools", errors=errors)
key = rule_key or uuid.uuid4()
current = (
await s.execute(select(func.max(PolicyRule.version)).where(PolicyRule.rule_key == key))
).scalar_one_or_none()
if rule_key is not None and current is None:
raise RuleError("unknown rule")
version = (current or 0) + 1
cedar = render_cedar(rule, f"{key.hex[:12]}.v{version}")
try:
check_syntax(cedar)
check_syntax(self.engine.policy_text([cedar]))
except ValueError as exc: # rendering bug: never store unparseable Cedar
raise RuleError(f"internal: rendered Cedar does not parse: {exc}") from exc
tests = [
*sample_calls(rule),
*[x for x in (samples or []) if isinstance(x, dict) and x.get("tool") in catalog],
]
row = PolicyRule(
tenant_id=tenant_id,
rule_key=key,
version=version,
status="draft",
nl_text=text,
ast=rule.model_dump(mode="json"),
cedar=cedar,
plain=render_plain(rule),
preview={"tests": evaluate_samples(rule, cedar, tests)},
created_by=user_id,
)
s.add(row)
await s.flush()
return row
async def confirm(
self,
s: AsyncSession,
rule_id: uuid.UUID,
*,
user_id: uuid.UUID,
allow_permit: bool = False,
catalog: Catalog | None = None,
) -> PolicyRule:
row = await s.get(PolicyRule, rule_id)
if row is None:
raise LookupError(str(rule_id))
if row.status != "draft":
raise RuleError(f"rule version is {row.status}, not a draft")
rule = RuleAST.model_validate(row.ast)
if rule.effect == "permit" and not allow_permit:
raise RuleError("this rule lets calls run without approval; confirm with allow_permit")
if catalog is not None:
errors = validate_rule(rule, catalog)
if errors: # a tool changed since the draft was compiled
raise RuleError("the rule no longer fits the available tools", errors=errors)
await s.execute(
update(PolicyRule)
.where(PolicyRule.rule_key == row.rule_key, PolicyRule.status == "active")
.values(status="superseded")
)
row.status = "active"
row.confirmed_by = user_id
row.confirmed_at = datetime.now(UTC)
await s.flush()
await self.sync_settings(s, row.tenant_id)
return row
async def rollback(self, s: AsyncSession, rule_key: uuid.UUID) -> PolicyRule | None:
"""Deactivate the active version and re-activate the previous confirmed one."""
active = (
await s.execute(
select(PolicyRule).where(
PolicyRule.rule_key == rule_key, PolicyRule.status == "active"
)
)
).scalar_one_or_none()
if active is None:
raise RuleError("rule has no active version")
active.status = "rolled_back"
previous = (
await s.execute(
select(PolicyRule)
.where(
PolicyRule.rule_key == rule_key,
PolicyRule.status == "superseded",
PolicyRule.version < active.version,
)
.order_by(PolicyRule.version.desc())
.limit(1)
)
).scalar_one_or_none()
if previous is not None:
previous.status = "active"
await s.flush()
await self.sync_settings(s, active.tenant_id)
return previous
async def disable(self, s: AsyncSession, rule_key: uuid.UUID) -> None:
rows = (
await s.execute(
select(PolicyRule).where(
PolicyRule.rule_key == rule_key,
PolicyRule.status.in_(("active", "draft")),
)
)
).scalars()
tenant_id = None
for r in rows:
tenant_id = r.tenant_id
r.status = "disabled" if r.status == "active" else "discarded"
await s.flush()
if tenant_id is not None:
await self.sync_settings(s, tenant_id)
@staticmethod
async def sync_settings(s: AsyncSession, tenant_id: uuid.UUID) -> list[str]:
active = list(
(
await s.execute(
select(PolicyRule.cedar)
.where(PolicyRule.status == "active")
.order_by(PolicyRule.created_at, PolicyRule.rule_key)
)
).scalars()
)
settings = (
await s.execute(select(Tenant.settings).where(Tenant.id == tenant_id))
).scalar_one()
await s.execute(
update(Tenant)
.where(Tenant.id == tenant_id)
.values(settings={**(settings or {}), "rule_policies": active})
)
return active
def rule_out(r: PolicyRule) -> dict[str, Any]:
return {
"id": str(r.id),
"rule_key": str(r.rule_key),
"version": r.version,
"status": r.status,
"text": r.nl_text,
"plain": r.plain,
"cedar": r.cedar,
"ast": r.ast,
"tests": (r.preview or {}).get("tests", []),
"created_at": r.created_at,
"confirmed_at": r.confirmed_at,
}
|