Skip to content

Self-improving AI Employees for everyone

feat(approvals): always-allow rules (RFC-0007 AP.2b, 2 of 2)

trohitg6ec3522dc92a
diff --git a/RFC-0007-APPROVALS-ON-TEMPORAL.md b/RFC-0007-APPROVALS-ON-TEMPORAL.md
index 86be77fb..61732d5e 100644
--- a/RFC-0007-APPROVALS-ON-TEMPORAL.md
+++ b/RFC-0007-APPROVALS-ON-TEMPORAL.md
@@ -304,12 +304,15 @@ In a v1 generation, for every caller: agent tool calls, CLI calls and in-process
- **An operation-mapped node:** the operation, for example "Google Calendar: create events". twitterSend is mapped on `action`.
- **Otherwise the whole tool,** for example "Always allow Shell".
- **Offered** on the card only when it can name everything the rule covers (Claude Code's rule), and never on a money card. Money rules are switched on in the employee's list (D19).
+ - Only the card of a call its turn waits on offers one. No other row is known to be v1, and a rule made from a v0 card would do nothing.
+ - The label names the tool as its cards do: the spec's channel, else the tool's display name ("Google Calendar: create", "Web browser on shop.example", "HTTP Request: GET requests to api.example.com").
- **Storage:** a small `approval_allows` table with `id`, `workflow_id`, `node_type`, `operation`, `scope_kind`, `scope_value`, `label`, `created_at` and `created_by`.
- `tool_calls.check` reads it.
- It is a new table, so `create_all` makes it on both databases.
- **Applies** in v1 generations only, to waits and drafts alike.
- **Lifetime:** Reset keeps rules, because they are the owner's settings. Deleting the employee deletes them through the approvals `on_workflow_deleted` hook (`services/approvals/handlers.py:285-289`).
- **Revocation:** the Ask-first menu's "Allowed without asking…" (D19) lists the rules, each with Remove, plus a switch for each of the employee's money tools. A removed rule applies from the next call.
+ - The commands are `list_approval_allows {workflow_id}` (the rules, and the money switches of the employee's tools, each with the rule that allows it), `add_approval_allow {workflow_id, node_type, operation?}` (a money switch only) and `remove_approval_allow {workflow_id, allow_id}`.
- **Not adopted:** deny rules, session-scoped approvals, and rule files.
### 4.5 The card and the decisions
diff --git a/server/models/approvals.py b/server/models/approvals.py
index 5e95289f..8fbb4a8d 100644
--- a/server/models/approvals.py
+++ b/server/models/approvals.py
@@ -43,6 +43,9 @@ send: one row per workflow, seeded from an employee's ground rules, changed
from the chat's Ask first chip (``set_ask_first``). A workflow without a row
(the editor's own workflows) gates no tool calls. Its ``mode`` says what asks
in a v1 generation (RFC-0007 §4.2); NULL follows ``ask_first``.
+
+``ApprovalAllow`` is an always-allow rule: the owner's standing OK for one
+kind of call of one employee (services/approvals/allows.py, RFC-0007 §4.4).
"""
from __future__ import annotations
@@ -175,4 +178,28 @@ class WorkflowRule(SQLModel, table=True):
updated_at: datetime = Field(default_factory=_utcnow, sa_column=Column(DateTime(timezone=True), nullable=False))
-__all__ = ["ApprovalDecision", "ApprovalRequest", "WorkflowRule"]
+class ApprovalAllow(SQLModel, table=True):
+ """An always-allow rule (see the module docstring)."""
+
+ __tablename__ = "approval_allows"
+ __table_args__ = (
+ UniqueConstraint("workflow_id", "node_type", "operation", "scope_kind", "scope_value", name="uq_approval_allows_scope"),
+ )
+
+ id: str = Field(primary_key=True, max_length=64)
+ workflow_id: str = Field(index=True, max_length=255)
+ node_type: str = Field(max_length=100)
+ #: The value of the class table's field the call names; "" for every
+ #: operation.
+ operation: str = Field(default="", max_length=100)
+ #: ``host``, ``recipient``, ``operation`` or ``tool``.
+ scope_kind: str = Field(max_length=20)
+ #: The host or the recipient; "" for the other scopes.
+ scope_value: str = Field(default="", max_length=500)
+ #: How the owner reads it ("Google Calendar: create").
+ label: str = Field(default="", max_length=300)
+ created_at: datetime = Field(default_factory=_utcnow, sa_column=Column(DateTime(timezone=True), nullable=False))
+ created_by: str = Field(default="owner", max_length=255)
+
+
+__all__ = ["ApprovalAllow", "ApprovalDecision", "ApprovalRequest", "WorkflowRule"]
diff --git a/server/services/approvals/allows.py b/server/services/approvals/allows.py
new file mode 100644
index 00000000..be76bdef
--- /dev/null
+++ b/server/services/approvals/allows.py
@@ -0,0 +1,266 @@
+"""Always-allow rules (RFC-0007 §4.4): the owner's standing OK for one kind
+of call of one employee. In a v1 generation a call a rule matches runs
+without asking (services/approvals/tool_calls.py), recorded as
+``approved_by: auto`` when it answers the owner in the chat.
+
+A rule names the node type, the operation the call names (the class
+table's field, services/approvals/classes.py; "" for every operation) and
+one scope:
+
+- ``host``: a call that fetches a URL on that host. A URL request keeps its
+ method as the operation, so a GET rule never lets a DELETE through;
+- ``recipient``: a spec'd send to that recipient, as its card shows it;
+- ``operation``: every call with that operation;
+- ``tool``: every call of the tool.
+
+A card offers the rule its call would make only when the call's turn waits
+on it (no other row is known to be v1, where rules apply), when the rule
+can name all it covers, and never for money: the employee's list switches
+money on, per money tool or operation (D19). A binding whose own Ask first
+switch is off (an MCP tool's ``mcp_ask``) counts as a rule.
+
+Reset keeps rules, since they are the owner's settings; deleting the
+employee deletes them. Never imports ``nodes/``.
+"""
+
+from __future__ import annotations
+
+import uuid
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Any, Dict, List, Mapping, Optional
+from urllib.parse import urlsplit
+
+from sqlalchemy import delete
+from sqlalchemy.exc import IntegrityError
+from sqlmodel import select
+
+from models.approvals import ApprovalAllow
+
+#: A node whose binding carries its own Ask first switch: off counts as a
+#: rule.
+ASK_SWITCHES: Dict[str, str] = {"mcpConnector": "mcp_ask"}
+
+
+@dataclass(frozen=True)
+class Scope:
+ """What one rule covers, and how the owner reads it."""
+
+ node_type: str
+ operation: str
+ kind: str
+ value: str
+ label: str
+
+
+def _utcnow() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _host(url: str) -> str:
+ try:
+ return (urlsplit(url).hostname or "").lower()
+ except ValueError:
+ return ""
+
+
+def _name(node_cls: Any, spec: Any) -> str:
+ """The tool as its cards name it."""
+ if spec is not None:
+ return spec.channel
+ return str(getattr(node_cls, "display_name", None) or getattr(node_cls, "type", ""))
+
+
+def _recipient(spec: Any, data: Mapping[str, Any]) -> str:
+ """Who a spec'd send goes to, as its card shows it; "" for none."""
+ if spec is None or spec.restrict_while_asking or not spec.recipient or not spec.sends(data):
+ return ""
+ return " ".join(str(spec.preview(data).get("recipient") or "").lower().split())
+
+
+def scope_of(node_cls: Any, node_data: Mapping[str, Any], args: Any) -> Optional[Scope]:
+ """The rule an "Always allow" would make for this call, or None when it
+ cannot name all it covers (a URL with no host, an operation that is not
+ one value)."""
+ from services.approvals.classes import CLASSES_WHEN, call_data, fetched_url, operation_of
+ from services.plugin.approval import approval_spec
+
+ node_type = getattr(node_cls, "type", "")
+ spec = approval_spec(node_cls)
+ own = call_data(node_cls, node_data, args)
+ field = CLASSES_WHEN.get(node_type, ("",))[0]
+ operation = operation_of(node_cls, own, tool_call=True)
+ if field and operation is None:
+ return None
+ operation = operation or ""
+ name = _name(node_cls, spec)
+ url = fetched_url(node_cls, own)
+ if url:
+ host = _host(url)
+ if not host:
+ return None
+ if field == "method":
+ return Scope(node_type, operation, "host", host, f"{name}: {operation} requests to {host}")
+ return Scope(node_type, "", "host", host, f"{name} on {host}")
+ recipient = _recipient(spec, node_data)
+ if recipient:
+ action = f"{spec.action} ({operation})" if operation else spec.action
+ return Scope(node_type, operation, "recipient", recipient, f"{action} to {recipient}")
+ if operation:
+ return Scope(node_type, operation, "operation", "", f"{name}: {operation}")
+ return Scope(node_type, "", "tool", "", name)
+
+
+def offer(row: Any, approval_class: Optional[str]) -> Optional[Scope]:
+ """The rule a card offers for its call (see the module docstring)."""
+ from services.node_registry import get_node_class
+
+ if approval_class in (None, "read", "money") or row.status != "pending" or row.runtime != "turn":
+ return None
+ node_cls = get_node_class(row.node_type) if row.node_type else None
+ return scope_of(node_cls, row.node_data or {}, row.args) if node_cls is not None else None
+
+
+async def allowed(database: Any, workflow_id: Any, node_cls: Any, node_data: Mapping[str, Any], args: Any) -> bool:
+ """Whether a rule, or the binding's own switch, lets this call run
+ without asking."""
+ from services.approvals.classes import call_data, fetched_url, operation_of
+ from services.plugin.approval import approval_spec
+
+ node_type = getattr(node_cls, "type", "")
+ switch = ASK_SWITCHES.get(node_type)
+ if switch and node_data.get(switch) is False:
+ return True
+ async with database.get_session() as session:
+ result = await session.execute(
+ select(ApprovalAllow).where(ApprovalAllow.workflow_id == str(workflow_id or ""), ApprovalAllow.node_type == node_type)
+ )
+ found = list(result.scalars().all())
+ if not found:
+ return False
+ own = call_data(node_cls, node_data, args)
+ operation = operation_of(node_cls, own, tool_call=True) or ""
+ host = _host(fetched_url(node_cls, own))
+ recipient = _recipient(approval_spec(node_cls), node_data)
+ for rule in found:
+ if rule.operation and rule.operation != operation:
+ continue
+ if rule.scope_kind in ("tool", "operation"):
+ return True
+ if (rule.scope_kind, rule.scope_value) in (("host", host), ("recipient", recipient)):
+ return True
+ return False
+
+
+async def add(database: Any, workflow_id: str, scope: Scope, *, created_by: str = "owner") -> ApprovalAllow:
+ """Save a rule; the same rule again returns the one saved."""
+ row = ApprovalAllow(
+ id=uuid.uuid4().hex,
+ workflow_id=workflow_id,
+ node_type=scope.node_type,
+ operation=scope.operation,
+ scope_kind=scope.kind,
+ scope_value=scope.value,
+ label=scope.label,
+ created_at=_utcnow(),
+ created_by=created_by,
+ )
+ try:
+ async with database.get_session() as session:
+ session.add(row)
+ await session.commit()
+ return row
+ except IntegrityError:
+ async with database.get_session() as session:
+ result = await session.execute(
+ select(ApprovalAllow).where(
+ ApprovalAllow.workflow_id == workflow_id,
+ ApprovalAllow.node_type == scope.node_type,
+ ApprovalAllow.operation == scope.operation,
+ ApprovalAllow.scope_kind == scope.kind,
+ ApprovalAllow.scope_value == scope.value,
+ )
+ )
+ existing = result.scalars().first()
+ if existing is None:
+ raise
+ return existing
+
+
+async def list_for_workflow(database: Any, workflow_id: str) -> List[ApprovalAllow]:
+ async with database.get_session() as session:
+ result = await session.execute(
+ select(ApprovalAllow).where(ApprovalAllow.workflow_id == workflow_id).order_by(ApprovalAllow.created_at)
+ )
+ return list(result.scalars().all())
+
+
+async def remove(database: Any, workflow_id: str, allow_id: str) -> bool:
+ """Remove a rule; it no longer applies from the next call."""
+ async with database.get_session() as session:
+ result = await session.execute(delete(ApprovalAllow).where(ApprovalAllow.workflow_id == workflow_id, ApprovalAllow.id == allow_id))
+ await session.commit()
+ return bool(result.rowcount)
+
+
+async def delete_for_workflow(database: Any, workflow_id: str) -> int:
+ async with database.get_session() as session:
+ result = await session.execute(delete(ApprovalAllow).where(ApprovalAllow.workflow_id == workflow_id))
+ await session.commit()
+ return int(result.rowcount or 0)
+
+
+async def money_options(database: Any, workflow_id: str) -> List[Dict[str, str]]:
+ """The employee's money tools and operations, for its list's switches
+ (D19): ``{node_type, operation, label}``, operation "" for a tool that
+ is money whole."""
+ from services.approvals.classes import CLASSES, CLASSES_WHEN, MONEY
+ from services.node_registry import iter_tool_node_classes
+ from services.plugin.approval import approval_spec
+
+ tools = dict(iter_tool_node_classes())
+ workflow = await database.get_workflow(workflow_id)
+ graph = (workflow.data if workflow is not None else None) or {}
+ options: List[Dict[str, str]] = []
+ seen = set()
+ for node in graph.get("nodes") or []:
+ node_type = str(node.get("type") or "") if isinstance(node, Mapping) else ""
+ node_cls = tools.get(node_type)
+ if node_cls is None or node_type in seen:
+ continue
+ seen.add(node_type)
+ name = _name(node_cls, approval_spec(node_cls))
+ if CLASSES.get(node_type) == MONEY:
+ options.append({"node_type": node_type, "operation": "", "label": name})
+ for value, klass in CLASSES_WHEN.get(node_type, ("", {}))[1].items():
+ if klass == MONEY:
+ options.append({"node_type": node_type, "operation": value, "label": f"{name}: {value}"})
+ return options
+
+
+def serialize(row: ApprovalAllow) -> Dict[str, Any]:
+ created = row.created_at if row.created_at.tzinfo else row.created_at.replace(tzinfo=timezone.utc)
+ return {
+ "id": row.id,
+ "node_type": row.node_type,
+ "operation": row.operation,
+ "scope_kind": row.scope_kind,
+ "scope_value": row.scope_value,
+ "label": row.label,
+ "created_at": created.isoformat(),
+ }
+
+
+__all__ = [
+ "ASK_SWITCHES",
+ "Scope",
+ "add",
+ "allowed",
+ "delete_for_workflow",
+ "list_for_workflow",
+ "money_options",
+ "offer",
+ "remove",
+ "scope_of",
+ "serialize",
+]
diff --git a/server/services/approvals/classes.py b/server/services/approvals/classes.py
index 0fd00948..2dadeadf 100644
--- a/server/services/approvals/classes.py
+++ b/server/services/approvals/classes.py
@@ -22,7 +22,7 @@ question: whether a broken-off attempt may run again. Never imports
from __future__ import annotations
-from typing import Any, Dict, Mapping, Tuple
+from typing import Any, Dict, Mapping, Optional, Tuple
from services.approvals.repeats import _default
@@ -479,6 +479,19 @@ def call_data(node_cls: Any, node_data: Mapping[str, Any], tool_args: Any) -> Di
return dict(node_data or {})
+def operation_of(node_cls: Any, data: Mapping[str, Any], *, tool_call: bool = False) -> Optional[str]:
+ """The value of the node's class field this call names (its model's
+ default when unset). None for a node the table classes whole, and for a
+ value that is not one string."""
+ rule = CLASSES_WHEN.get(getattr(node_cls, "type", ""))
+ if rule is None:
+ return None
+ value = data.get(rule[0])
+ if value is None:
+ value = _default(node_cls, rule[0], tool_call)
+ return value if isinstance(value, str) else None
+
+
def fetched_url(node_cls: Any, data: Mapping[str, Any]) -> str:
"""The URL the call fetches, or "" when it fetches none."""
field = URL_FIELDS.get(getattr(node_cls, "type", ""))
@@ -544,4 +557,5 @@ __all__ = [
"call_data",
"class_of",
"fetched_url",
+ "operation_of",
]
diff --git a/server/services/approvals/decisions.py b/server/services/approvals/decisions.py
index 965c9aa7..7d30ec91 100644
--- a/server/services/approvals/decisions.py
+++ b/server/services/approvals/decisions.py
@@ -19,7 +19,9 @@
A discard may carry the owner's ``note`` for the employee. A held call its
agent's turn waits on (``runtime: turn``, RFC-0007 §4.6) gets no Undo grace
and no Restore: its turn runs it, or hears the decline, at once. A retry of
-one makes it a draft again, since that turn is over.
+one makes it a draft again, since that turn is over. A send with ``always``
+also saves the always-allow rule its card offers (services/approvals/
+allows.py), and is refused when the card offers none.
Each decision is a compare-and-swap on the row's revision, recorded with its
``decision_key`` in the same transaction (``approval_decisions``): the same
@@ -35,11 +37,14 @@ from __future__ import annotations
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Optional, Tuple
+from core.logging import get_logger
from models.approvals import ApprovalRequest
from services.approvals import store
from services.approvals.contract import DEFAULT_TIMEOUT_HOURS, RESTORE_SECONDS, UNDO_SECONDS
from services.approvals.listeners import change_of, notify_approval_changed
+logger = get_logger(__name__)
+
DECISIONS = ("send", "undo", "discard", "restore", "retry", "dismiss")
#: The longest note a discard keeps (the chat's message limit).
MAX_NOTE = 50000
@@ -134,6 +139,7 @@ async def decide(
subject: Any = None,
confirm: bool = False,
note: Any = None,
+ always: bool = False,
now: Optional[datetime] = None,
) -> Tuple[ApprovalRequest, bool]:
"""Apply a decision. Returns ``(row, idempotent)``; raises
@@ -156,7 +162,16 @@ async def decide(
values["decision_key"] = decision_key
if turn:
values["grace_until"] = None
+ scope = None
+ if always:
+ from services.approvals import allows
+
+ scope = allows.offer(row, store.approval_class(row))
+ if scope is None:
+ raise DecisionRefused("invalid_request", "This one cannot be always allowed.")
moved = await _move(database, row, ("pending",), "approved", values, record)
+ if scope is not None:
+ await _save_rule(database, moved, scope, actor)
elif decision == "undo":
grace = store.aware(row.grace_until)
if row.status != "approved" or row.consumed_at is not None or row.claim_token or grace is None or grace <= now:
@@ -204,6 +219,17 @@ async def decide(
return moved, False
+async def _save_rule(database: Any, row: ApprovalRequest, scope: Any, actor: str) -> None:
+ """Save the rule a send with ``always`` made. The send stands without
+ it: the next such call asks again."""
+ from services.approvals import allows
+
+ try:
+ await allows.add(database, row.workflow_id, scope, created_by=actor)
+ except Exception: # noqa: BLE001 - logged, and the next call asks
+ logger.warning("Could not save an always-allow rule", approval_id=row.id, exc_info=True)
+
+
async def _move(database: Any, row: ApprovalRequest, from_statuses, status: str, values: Dict[str, Any], record) -> ApprovalRequest:
try:
return await store.transition(
diff --git a/server/services/approvals/handlers.py b/server/services/approvals/handlers.py
index 5c9a8337..28054ae1 100644
--- a/server/services/approvals/handlers.py
+++ b/server/services/approvals/handlers.py
@@ -9,9 +9,10 @@ on its way) or ``recent`` (everything, newest first); default ``pending``.
``get_approvals {approval_ids: [...]}`` -> ``{approvals, server_time}``.
``decide_approval {approval_id, decision, decision_key, text?, subject?,
-confirm?, note?}`` -> ``{approval, idempotent?, will_send_on_resume}``.
-Decisions: ``send``, ``undo``, ``discard`` (with the owner's ``note``),
-``restore``, ``retry``, ``dismiss`` (services/approvals/decisions.py).
+confirm?, note?, always?}`` -> ``{approval, idempotent?, will_send_on_resume}``.
+Decisions: ``send`` (``always``: and save the card's always-allow rule),
+``undo``, ``discard`` (with the owner's ``note``), ``restore``, ``retry``,
+``dismiss`` (services/approvals/decisions.py).
Sending a held tool call starts its send (services/approvals/execution.py),
unless its agent's turn waits on it (``runtime: turn``) and runs it itself.
Errors: ``already_decided``,
@@ -26,6 +27,13 @@ needs_apply}``; ``rule_conflict`` when it moved. ``mode`` is ``outside``,
``everything`` or ``money_only`` (services/approvals/rules.py): setting it
keeps Ask first in step, and setting Ask first makes the mode follow it.
+Always-allow rules (services/approvals/allows.py): ``list_approval_allows
+{workflow_id}`` -> ``{allows, money}``, the rules and the money switches of
+the employee's tools (``{node_type, operation, label, allow_id}``, the rule
+that switches each on or null); ``add_approval_allow {workflow_id,
+node_type, operation?}`` -> ``{allow}``, a money switch only;
+``remove_approval_allow {workflow_id, allow_id}``.
+
Only the owner's own drafts and workflows are visible; any other id reads as
not found.
"""
@@ -38,7 +46,7 @@ from typing import Any, Dict, List
from fastapi import WebSocket
from core.logging import get_logger
-from services.approvals import decisions, execution, rules, store, waiter
+from services.approvals import allows, decisions, execution, rules, store, waiter
from services.approvals.contract import APPROVAL_KINDS
from services.approvals.listeners import change_of, notify_approval_changed
from services.approvals.reconcile import reconcile_once
@@ -189,6 +197,7 @@ async def handle_decide_approval(data: Dict[str, Any], websocket: WebSocket) ->
subject=data.get("subject"),
confirm=bool(data.get("confirm")),
note=data.get("note"),
+ always=data.get("always") is True,
)
except decisions.DecisionRefused as refused:
current = await store.get(database, approval_id) or row
@@ -298,9 +307,73 @@ async def handle_set_ask_first(data: Dict[str, Any], websocket: WebSocket) -> Di
}
+async def _authorized(data: Dict[str, Any], websocket: Any) -> Any:
+ """The workflow a rules command names, or None when the caller may not
+ see it."""
+ from core.container import container
+
+ workflow_id = str(data.get("workflow_id") or "").strip()
+ database = container.database()
+ if not workflow_id or not await _authorize_workflow(database, websocket, workflow_id):
+ return None
+ return workflow_id
+
+
+@ws_response
+async def handle_list_approval_allows(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ from core.container import container
+
+ workflow_id = await _authorized(data, websocket)
+ if workflow_id is None:
+ return {"success": False, "error": "not_found"}
+ database = container.database()
+ found = await allows.list_for_workflow(database, workflow_id)
+ switches = {(row.node_type, row.operation): row.id for row in found if row.scope_kind in ("tool", "operation")}
+ money = [
+ {**option, "allow_id": switches.get((option["node_type"], option["operation"]))}
+ for option in await allows.money_options(database, workflow_id)
+ ]
+ return {"success": True, "workflow_id": workflow_id, "allows": [allows.serialize(row) for row in found], "money": money}
+
+
+@ws_response
+async def handle_add_approval_allow(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ from core.container import container
+
+ workflow_id = await _authorized(data, websocket)
+ if workflow_id is None:
+ return {"success": False, "error": "not_found"}
+ database = container.database()
+ node_type, operation = data.get("node_type"), data.get("operation") or ""
+ option = next(
+ (item for item in await allows.money_options(database, workflow_id) if (item["node_type"], item["operation"]) == (node_type, operation)),
+ None,
+ )
+ if option is None:
+ return {"success": False, "error": "invalid_request"}
+ scope = allows.Scope(node_type, operation, "operation" if operation else "tool", "", option["label"])
+ row = await allows.add(database, workflow_id, scope, created_by=execution_principal(data, websocket))
+ logger.info("Always allowed", workflow_id=workflow_id, node_type=node_type, operation=operation)
+ return {"success": True, "allow": allows.serialize(row)}
+
+
+@ws_response
+async def handle_remove_approval_allow(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ from core.container import container
+
+ workflow_id = await _authorized(data, websocket)
+ if workflow_id is None:
+ return {"success": False, "error": "not_found"}
+ if not await allows.remove(container.database(), workflow_id, str(data.get("allow_id") or "")):
+ return {"success": False, "error": "not_found"}
+ logger.info("Removed an always-allow rule", workflow_id=workflow_id, allow_id=data.get("allow_id"))
+ return {"success": True}
+
+
async def on_workflow_deleted(database: Any, workflow_id: str) -> None:
removed = await store.delete_for_workflow(database, workflow_id)
await rules.delete_rule(database, workflow_id)
+ await allows.delete_for_workflow(database, workflow_id)
if removed:
logger.info("Removed a deleted workflow's drafts", workflow_id=workflow_id, count=removed)
@@ -311,15 +384,21 @@ WS_HANDLERS: Dict[str, Any] = {
"decide_approval": handle_decide_approval,
"get_ask_first": handle_get_ask_first,
"set_ask_first": handle_set_ask_first,
+ "list_approval_allows": handle_list_approval_allows,
+ "add_approval_allow": handle_add_approval_allow,
+ "remove_approval_allow": handle_remove_approval_allow,
}
__all__ = [
"WS_HANDLERS",
+ "handle_add_approval_allow",
"handle_decide_approval",
"handle_get_approvals",
"handle_get_ask_first",
+ "handle_list_approval_allows",
"handle_list_approvals",
+ "handle_remove_approval_allow",
"handle_set_ask_first",
"on_workflow_deleted",
]
diff --git a/server/services/approvals/store.py b/server/services/approvals/store.py
index 1c3ffea4..f7be300e 100644
--- a/server/services/approvals/store.py
+++ b/server/services/approvals/store.py
@@ -366,9 +366,9 @@ def _outcome_labels(row: ApprovalRequest) -> Tuple[str, str]:
return spec.outcome_labels if spec is not None else DONE_OUTCOME
-def _class_of(row: ApprovalRequest) -> Optional[str]:
- """What a held call may do (services/approvals/classes.py), for the
- card's pill."""
+def approval_class(row: ApprovalRequest) -> Optional[str]:
+ """What a held call may do (services/approvals/classes.py): the card's
+ pill, and whether it may offer an always-allow rule."""
from services.approvals.classes import call_data, class_of
from services.node_registry import get_node_class
@@ -405,11 +405,16 @@ def summary(row: ApprovalRequest, *, deployment_state: Optional[str] = None, now
sent, failed = _outcome_labels(row)
out["outcome_labels"] = {"sent": sent, "failed": failed}
if kind == "tool_call":
- out["approval_class"] = _class_of(row)
+ from services.approvals import allows
+
+ klass = approval_class(row)
+ out["approval_class"] = klass
# A tool with no spec: the card shows what it runs with, not a message.
out["generic"] = _spec_of(row) is None
# Its turn waits on it: no Undo, and the employee gets the real result.
out["waits"] = row.runtime == "turn"
+ scope = allows.offer(row, klass)
+ out["always"] = None if scope is None else {"label": scope.label, "scope": scope.kind}
if row.action:
out["action"] = row.action
subject = row.final_subject if decided and row.final_subject else row.subject
@@ -449,6 +454,7 @@ def summary(row: ApprovalRequest, *, deployment_state: Optional[str] = None, now
__all__ = [
"ApprovalConflict",
+ "approval_class",
"aware",
"cancel_open",
"cancel_pending",
diff --git a/server/services/approvals/tool_calls.py b/server/services/approvals/tool_calls.py
index 0894c434..faa8b08d 100644
--- a/server/services/approvals/tool_calls.py
+++ b/server/services/approvals/tool_calls.py
@@ -21,8 +21,9 @@ its row is the one being sent, and is never held again.
workflow's mode and the call's class (services/approvals/classes.py) decide,
for every tool an agent calls, spec or not:
-- A read runs. So does a call whose class the mode does not ask; one that
- reaches out (send, money) and answers the owner in the chat is recorded.
+- A read runs. So does a call whose class the mode does not ask, or that an
+ always-allow rule matches (services/approvals/allows.py); one that reaches
+ out (send, money) and answers the owner in the chat is recorded.
- An asked call is held, on a generic card when its tool has no spec, and
Stripe is held instead of refused. A restricted tool (the Browser) is held
only when it fetches a URL, and runs restricted otherwise.
@@ -216,6 +217,19 @@ async def _ask_mode(database: Any, workflow_id: Any) -> Optional[str]:
return "everything"
+async def _allowed(database: Any, context: Mapping[str, Any], node_cls: Any, node_data: Mapping[str, Any]) -> bool:
+ """Whether an always-allow rule, or the binding's own Ask first switch,
+ lets the call run (services/approvals/allows.py). When the rules cannot
+ be read, the call asks."""
+ from services.approvals import allows
+
+ try:
+ return await allows.allowed(database, context.get("workflow_id"), node_cls, node_data, context.get("tool_args"))
+ except Exception:
+ logger.warning("Could not read the always-allow rules; asking", workflow_id=context.get("workflow_id"), exc_info=True)
+ return False
+
+
def _restricted(spec: Any, node_data: Mapping[str, Any], context: Mapping[str, Any]) -> Checked:
"""Run with the spec's restrictions instead of holding (the Browser,
read-only); the model's arguments cannot lift them."""
@@ -288,7 +302,7 @@ async def _check_by_class(context: Mapping[str, Any], node_cls: Any, spec: Any)
mode = await _ask_mode(database, context.get("workflow_id"))
if mode is None:
return RUN
- if klass not in rules.ASKS[mode]:
+ if klass not in rules.ASKS[mode] or await _allowed(database, context, node_cls, node_data):
if klass in (SEND, MONEY) and isinstance(context.get("chat_stream"), Mapping):
return Checked(record=_auto_recorder(database, context, node_cls, spec, node_data))
return RUN
diff --git a/server/tests/services/approvals/test_allows.py b/server/tests/services/approvals/test_allows.py
new file mode 100644
index 00000000..15d036af
--- /dev/null
+++ b/server/tests/services/approvals/test_allows.py
@@ -0,0 +1,164 @@
+"""Always-allow rules (services/approvals/allows.py, RFC-0007 §4.4): a card
+its turn waits on offers the rule its call would make, scoped by host,
+recipient, operation or the whole tool, and never for money; Allow with
+``always`` saves it; in a v1 generation a call a rule matches runs unasked.
+The employee's list shows its rules and its money switches; removing a rule
+or deleting the employee ends it. An MCP tool whose own Ask first is off
+counts as a rule."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+import nodes # noqa: F401 -- populate plugin registry
+from services.approvals import allows, execution, handlers, rules, store, tool_calls
+from services.node_registry import get_node_class
+
+pytestmark = pytest.mark.asyncio
+
+SOCKET = SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(user_id="owner"))
+WHATSAPP = {"recipient_type": "phone", "phone": "447700900123", "message": "On my way."}
+POST = {"method": "POST", "url": "https://api.example/orders", "body": "{}"}
+
+
+def call(node_type, tool_args, node_data=None, *, call_id="call_1", waits=True, v1=True):
+ return {
+ "node_id": f"wf:{node_type}:1",
+ "workflow_id": "wf",
+ "execution_id": "wf:execution:1",
+ "user_id": "owner",
+ "parent_node_id": "wf:aiAgent:1",
+ "tool_call_id": call_id,
+ "node_data": {**(node_data or {}), **tool_args},
+ "tool_args": tool_args,
+ **({"approval_wait_version": 1} if v1 else {}),
+ **({"approval_wait": True} if waits else {}),
+ }
+
+
+async def check(node_type, tool_args, node_data=None, **options):
+ return await tool_calls.check(call(node_type, tool_args, node_data, **options), get_node_class(node_type))
+
+
+async def held(harness, node_type, tool_args, node_data=None, **options):
+ checked = await check(node_type, tool_args, node_data, **options)
+ return await store.get(harness.database, checked.result["approval_id"])
+
+
+async def decide(row, decision, key, **extra):
+ return await handlers.handle_decide_approval({"approval_id": row.id, "decision": decision, "decision_key": key, **extra}, SOCKET)
+
+
+async def asking(harness, monkeypatch):
+ async def start_send(row):
+ return None
+
+ monkeypatch.setattr(execution, "start_send", start_send)
+ monkeypatch.setattr(rules, "_LISTENERS", [])
+ await rules.set_mode(harness.database, "wf", "everything")
+ return harness
+
+
+ ("node_type", "args", "node_data", "offer"),
+ [
+ ("whatsappSend", WHATSAPP, {"message_type": "text"}, ("recipient", "Send a WhatsApp message to 447700900123")),
+ ("httpRequest", POST, None, ("host", "HTTP Request: POST requests to api.example")),
+ ("browser", {"operation": "navigate", "url": "https://Shop.Example/cart"}, None, ("host", "Web browser on shop.example")),
+ (
+ "googleCalendar",
+ {"operation": "create", "title": "Sync", "send_updates": "none"},
+ None,
+ ("operation", "Google Calendar: create"),
+ ),
+ ("shell", {"command": "ls"}, None, ("tool", "Shell")),
+ ("stripeAction", {"command": "customers list"}, None, None), # money: made in the list
+ ],
+)
+async def test_a_card_offers_the_rule_its_call_would_make(asking, node_type, args, node_data, offer):
+ row = await held(asking, node_type, args, node_data)
+ always = store.summary(row)["always"]
+ assert (None if always is None else (always["scope"], always["label"])) == offer
+
+
+async def test_a_draft_offers_no_rule(asking):
+ # Only a row its turn waits on is known to be v1, where rules apply.
+ row = await held(asking, "shell", {"command": "ls"}, waits=False)
+ assert store.summary(row)["always"] is None
+
+
+async def test_allow_always_saves_the_rule_and_the_next_call_runs(asking):
+ row = await held(asking, "whatsappSend", WHATSAPP, {"message_type": "text"})
+ answer = await decide(row, "send", "s1", always=True)
+ assert answer["success"] and answer["approval"]["status"] == "approved"
+ (rule,) = await allows.list_for_workflow(asking.database, "wf")
+ assert (rule.node_type, rule.scope_kind, rule.scope_value) == ("whatsappSend", "recipient", "447700900123")
+ # The same recipient again runs; anyone else still asks.
+ assert await check("whatsappSend", WHATSAPP, {"message_type": "text"}, call_id="call_2") is tool_calls.RUN
+ other = {**WHATSAPP, "phone": "447700900999"}
+ assert (await check("whatsappSend", other, {"message_type": "text"}, call_id="call_3")).result is not None
+ # Rules apply only in a v1 generation.
+ assert (await check("whatsappSend", WHATSAPP, {"message_type": "text"}, call_id="call_4", v1=False)).result is not None
+
+
+async def test_always_is_refused_on_money(asking):
+ row = await held(asking, "stripeAction", {"command": "refunds create --charge ch_1"})
+ assert (await decide(row, "send", "s1", always=True))["error"] == "invalid_request"
+ assert await allows.list_for_workflow(asking.database, "wf") == []
+
+
+async def test_a_host_rule_keeps_to_its_method(asking):
+ row = await held(asking, "httpRequest", {**POST, "method": "GET"})
+ await decide(row, "send", "s1", always=True)
+ assert await check("httpRequest", {**POST, "method": "GET", "url": "https://api.example/refunds"}, call_id="c2") is tool_calls.RUN
+ assert (await check("httpRequest", POST, call_id="c3")).result is not None
+ assert (await check("httpRequest", {**POST, "method": "DELETE"}, call_id="c4")).result is not None
+
+
+async def test_an_mcp_tool_whose_ask_first_is_off_runs(asking):
+ tool = {"mcp_connector": "docs", "mcp_tool": "search", "mcp_ask": False}
+ assert await check("mcpConnector", {"query": "pricing"}, tool) is tool_calls.RUN
+ assert (await check("mcpConnector", {"query": "pricing"}, {**tool, "mcp_ask": True}, call_id="c2")).result is not None
+
+
+async def test_the_list_shows_the_rules_and_the_money_switches(asking):
+ from services.approvals.handlers import handle_add_approval_allow, handle_list_approval_allows, handle_remove_approval_allow
+
+ graph = {
+ "nodes": [
+ {"id": "wf:stripeAction:1", "type": "stripeAction"},
+ {"id": "wf:googleCalendar:1", "type": "googleCalendar"},
+ {"id": "wf:shell:1", "type": "shell"},
+ ],
+ "edges": [],
+ }
+ await asking.database.save_workflow("wf", "Maya", "Maya_1", graph)
+ listed = await handle_list_approval_allows({"workflow_id": "wf"}, SOCKET)
+ assert listed["allows"] == []
+ money = {(item["node_type"], item["operation"]): item for item in listed["money"]}
+ assert set(money) == {("stripeAction", ""), ("googleCalendar", "delete")}
+ assert money[("stripeAction", "")]["allow_id"] is None
+
+ added = await handle_add_approval_allow({"workflow_id": "wf", "node_type": "stripeAction"}, SOCKET)
+ assert added["success"] and added["allow"]["label"] == "Stripe"
+ assert await check("stripeAction", {"command": "customers list"}) is tool_calls.RUN
+ # Only the employee's money switches are added this way.
+ refused = await handle_add_approval_allow({"workflow_id": "wf", "node_type": "shell"}, SOCKET)
+ assert refused["error"] == "invalid_request"
+
+ listed = await handle_list_approval_allows({"workflow_id": "wf"}, SOCKET)
+ (rule,) = listed["allows"]
+ assert {item["node_type"]: item["allow_id"] for item in listed["money"]}["stripeAction"] == rule["id"]
+ assert (await handle_remove_approval_allow({"workflow_id": "wf", "allow_id": rule["id"]}, SOCKET))["success"] is True
+ assert (await check("stripeAction", {"command": "customers list"}, call_id="c2")).result is not None
+
+
+async def test_deleting_the_employee_deletes_its_rules(asking):
+ row = await held(asking, "shell", {"command": "ls"})
+ await decide(row, "send", "s1", always=True)
+ assert len(await allows.list_for_workflow(asking.database, "wf")) == 1
+ await handlers.on_workflow_deleted(asking.database, "wf")
+ assert await allows.list_for_workflow(asking.database, "wf") == []