Spaces:
Running
Running
Download core/rules/service.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/rules/service.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/rules/service.py
-
curl -L -o service.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/rules/service.py
11.6 kB
| """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) | |
| 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, | |
| } | |