Skip to content

Self-improving AI Employees for everyone

feat(approvals): modes and the class-based check, v1 only (RFC-0007 AP.2a)

trohitgfc4b11f40834
diff --git a/RFC-0007-APPROVALS-ON-TEMPORAL.md b/RFC-0007-APPROVALS-ON-TEMPORAL.md
index ebcb2c52..86be77fb 100644
--- a/RFC-0007-APPROVALS-ON-TEMPORAL.md
+++ b/RFC-0007-APPROVALS-ON-TEMPORAL.md
@@ -330,6 +330,7 @@ In a v1 generation, for every caller: agent tool calls, CLI calls and in-process
- up to six argument lines, each cut at 300 characters;
- secret-named keys removed by `sanitize_runtime_payload`, which also drops `authorization`, `proxyauthorization` and `cookie`;
- no Edit.
+- **A call that fetches a URL** shows it on its card, as an "Address" line when its spec's lines lack it (the Browser's spec has none). The URL fields are a service table, `URL_FIELDS` in `classes.py`, which §4.4's host rules use too.
- **A class pill** on every request card: "Makes changes" (write), "Reaches out" (send), "Money or deletes" (money).
- **Keys:** the chat-wide Ctrl/Cmd+Enter never allows a money card, and the note box keeps Ctrl/Cmd+Enter to itself.
- **1b.1's outcome cards** are not requests and never offer Always:
diff --git a/server/core/database.py b/server/core/database.py
index ab41b573..dd7e13d5 100644
--- a/server/core/database.py
+++ b/server/core/database.py
@@ -655,7 +655,8 @@ class Database:
async def _migrate_approvals(self):
"""Give an older ``approval_requests`` table the columns approvals v2
- added (held tool calls, Undo and Restore, outcomes). A draft approved
+ added (held tool calls, Undo and Restore, outcomes), and an older
+ ``workflow_rules`` table its ``mode`` (RFC-0007). A draft approved
before them was handed on when it was decided, so it gets that as
``consumed_at`` and never reads as still undoable."""
columns_added = {
@@ -684,6 +685,10 @@ class Database:
}
try:
async with self.engine.begin() as conn:
+ result = await conn.execute(text("PRAGMA table_info(workflow_rules)"))
+ rule_columns = {row[1] for row in result.fetchall()}
+ if rule_columns and "mode" not in rule_columns:
+ await conn.execute(text("ALTER TABLE workflow_rules ADD COLUMN mode VARCHAR(20)"))
result = await conn.execute(text("PRAGMA table_info(approval_requests)"))
columns = {row[1] for row in result.fetchall()}
if not columns:
diff --git a/server/models/approvals.py b/server/models/approvals.py
index 5cb78e86..35845304 100644
--- a/server/models/approvals.py
+++ b/server/models/approvals.py
@@ -39,7 +39,8 @@ the owner's decisions; the same ``decision_key`` again is a no-op.
``WorkflowRule`` is a workflow's Ask first rule, read when something would
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.
+(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``.
"""
from __future__ import annotations
@@ -158,6 +159,9 @@ class WorkflowRule(SQLModel, table=True):
workflow_id: str = Field(primary_key=True, max_length=255)
ask_first: bool = Field(default=True)
+ #: ``outside`` | ``everything`` | ``money_only`` (services/approvals/
+ #: rules.py); NULL follows ``ask_first``.
+ mode: Optional[str] = Field(default=None, max_length=20)
revision: int = Field(default=0)
#: ``hire`` (seeded from the employee's ground rules) or ``owner``.
source: str = Field(default="owner", max_length=20)
diff --git a/server/services/approvals/classes.py b/server/services/approvals/classes.py
index b697de04..0fd00948 100644
--- a/server/services/approvals/classes.py
+++ b/server/services/approvals/classes.py
@@ -464,6 +464,28 @@ CLASSES_WHEN: Dict[str, Tuple[str, Dict[str, str]]] = {
}
+#: Where a call that fetches a URL names it: the scope of a host rule
+#: (RFC-0007 §4.4); the Browser is held only when it navigates (§4.3).
+URL_FIELDS: Dict[str, str] = {"browser": "url", "crawleeScraper": "url", "httpRequest": "url", "proxyRequest": "url"}
+
+
+def call_data(node_cls: Any, node_data: Mapping[str, Any], tool_args: Any) -> Dict[str, Any]:
+ """What :func:`class_of` judges for an LLM tool call: the tool's own
+ arguments when it has an input model of its own, else the call's
+ arguments over the node's settings."""
+ tool_input = getattr(node_cls, "tool_input_model", None)
+ if isinstance(tool_args, Mapping) and callable(tool_input) and tool_input() is not getattr(node_cls, "Params", None):
+ return dict(tool_args)
+ return dict(node_data or {})
+
+
+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", ""))
+ value = data.get(field) if field else None
+ return value.strip() if isinstance(value, str) else ""
+
+
def class_of(node_cls: Any, data: Mapping[str, Any], *, tool_call: bool = False) -> str:
"""The class of this call of ``node_cls`` with ``data``.
@@ -509,4 +531,17 @@ def _reaches_no_one(node_cls: Any, data: Mapping[str, Any]) -> bool:
return not spec.sends(data)
-__all__ = ["CLASSES", "CLASSES_WHEN", "DEFAULT", "LADDER", "MONEY", "READ", "SEND", "WRITE", "class_of"]
+__all__ = [
+ "CLASSES",
+ "CLASSES_WHEN",
+ "DEFAULT",
+ "LADDER",
+ "MONEY",
+ "READ",
+ "SEND",
+ "URL_FIELDS",
+ "WRITE",
+ "call_data",
+ "class_of",
+ "fetched_url",
+]
diff --git a/server/services/approvals/handlers.py b/server/services/approvals/handlers.py
index 4ad351f9..99a652e6 100644
--- a/server/services/approvals/handlers.py
+++ b/server/services/approvals/handlers.py
@@ -17,10 +17,12 @@ confirm?}`` -> ``{approval, idempotent?, will_send_on_resume}``. Decisions:
``approval_conflict``, ``send_unavailable``, ``not_found``,
``invalid_request``.
-``get_ask_first {workflow_id}`` -> ``{ask_first, revision}`` (``ask_first``
-is null for a workflow with no rule). ``set_ask_first {workflow_id,
-ask_first, expected_revision?}`` -> ``{ask_first, revision, replies_gated,
-needs_apply}``; ``rule_conflict`` when it moved.
+``get_ask_first {workflow_id}`` -> ``{ask_first, mode, revision}`` (both
+null for a workflow with no rule). ``set_ask_first {workflow_id, ask_first |
+mode, expected_revision?}`` -> ``{ask_first, mode, revision, replies_gated,
+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.
Only the owner's own drafts and workflows are visible; any other id reads as
not found.
@@ -243,6 +245,7 @@ async def handle_get_ask_first(data: Dict[str, Any], websocket: WebSocket) -> Di
"success": True,
"workflow_id": workflow_id,
"ask_first": None if rule is None else bool(rule.ask_first),
+ "mode": None if rule is None else rules.mode_of(rule),
"revision": 0 if rule is None else rule.revision,
}
@@ -253,7 +256,9 @@ async def handle_set_ask_first(data: Dict[str, Any], websocket: WebSocket) -> Di
workflow_id = str(data.get("workflow_id") or "").strip()
value = data.get("ask_first")
- if not workflow_id or not isinstance(value, bool):
+ mode = data.get("mode")
+ known_mode = isinstance(mode, str) and mode in rules.ASKS
+ if not workflow_id or (mode is None and not isinstance(value, bool)) or (mode is not None and not known_mode):
return {"success": False, "error": "invalid_request"}
expected = data.get("expected_revision")
if expected is not None and not isinstance(expected, int):
@@ -262,21 +267,26 @@ async def handle_set_ask_first(data: Dict[str, Any], websocket: WebSocket) -> Di
if not await _authorize_workflow(database, websocket, workflow_id):
return {"success": False, "error": "not_found"}
try:
- rule = await rules.set_ask_first(database, workflow_id, value, expected_revision=expected)
+ if mode is not None:
+ rule = await rules.set_mode(database, workflow_id, mode, expected_revision=expected)
+ else:
+ rule = await rules.set_ask_first(database, workflow_id, value, expected_revision=expected)
except rules.RuleConflict as conflict:
current = conflict.rule
return {
"success": False,
"error": "rule_conflict",
"ask_first": None if current is None else bool(current.ask_first),
+ "mode": None if current is None else rules.mode_of(current),
"revision": 0 if current is None else current.revision,
}
effects = await rules.notify_rule_changed(database, workflow_id, rule)
- logger.info("Ask first changed", workflow_id=workflow_id, ask_first=rule.ask_first)
+ logger.info("Ask first changed", workflow_id=workflow_id, ask_first=rule.ask_first, mode=rule.mode)
return {
"success": True,
"workflow_id": workflow_id,
"ask_first": bool(rule.ask_first),
+ "mode": rules.mode_of(rule),
"revision": rule.revision,
"replies_gated": bool(effects.get("replies_gated", False)),
"needs_apply": bool(effects.get("needs_apply", False)),
diff --git a/server/services/approvals/rules.py b/server/services/approvals/rules.py
index e86a74ed..34a342fb 100644
--- a/server/services/approvals/rules.py
+++ b/server/services/approvals/rules.py
@@ -10,13 +10,20 @@ restart: approval gates and held tool calls read it each time.
A workflow with no row and no seed (one built in the editor) has no rule:
its tool calls are never held, and its approval gates wait for the owner as
they always did.
+
+In a v1 generation the rule's mode says which classes of call ask
+(RFC-0007 §4.2; services/approvals/classes.py): ``outside`` asks before
+anything that reaches out (send, money), ``everything`` before any change
+(write too), ``money_only`` only before money and deletes. A rule without a
+mode follows Ask first: on is ``outside``, off is ``money_only``. Setting the
+mode keeps Ask first in step, which v0 generations read.
"""
from __future__ import annotations
import inspect
from datetime import datetime, timezone
-from typing import Any, Awaitable, Callable, Dict, List, Optional, Union
+from typing import Any, Awaitable, Callable, Dict, FrozenSet, List, Optional, Union
from sqlalchemy import update
from sqlalchemy.exc import IntegrityError
@@ -36,6 +43,13 @@ _SEEDERS: List[RuleSeeder] = []
RuleListener = Callable[[Any, str, Any], Union[Optional[Dict[str, Any]], Awaitable[Optional[Dict[str, Any]]]]]
_LISTENERS: List[RuleListener] = []
+#: The classes of call each mode asks for.
+ASKS: Dict[str, FrozenSet[str]] = {
+ "outside": frozenset({"send", "money"}),
+ "everything": frozenset({"write", "send", "money"}),
+ "money_only": frozenset({"money"}),
+}
+
class RuleConflict(ValueError):
"""The rule changed since the caller read it."""
@@ -105,8 +119,21 @@ async def ask_first(database: Any, workflow_id: Optional[str]) -> Optional[bool]
return None if rule is None else bool(rule.ask_first)
-async def _insert(database: Any, workflow_id: str, value: bool, *, source: str) -> WorkflowRule:
- row = WorkflowRule(workflow_id=workflow_id, ask_first=value, revision=0, source=source, updated_at=_utcnow())
+def mode_of(rule: WorkflowRule) -> str:
+ """The rule's mode: the owner's choice, else what Ask first means."""
+ if rule.mode in ASKS:
+ return rule.mode
+ return "outside" if rule.ask_first else "money_only"
+
+
+async def ask_mode(database: Any, workflow_id: Optional[str]) -> Optional[str]:
+ """Which mode the workflow asks in, or None when it has no rule."""
+ rule = await get_rule(database, workflow_id or "")
+ return None if rule is None else mode_of(rule)
+
+
+async def _insert(database: Any, workflow_id: str, value: bool, *, source: str, mode: Optional[str] = None) -> WorkflowRule:
+ row = WorkflowRule(workflow_id=workflow_id, ask_first=value, mode=mode, revision=0, source=source, updated_at=_utcnow())
try:
async with database.get_session() as session:
session.add(row)
@@ -121,20 +148,34 @@ async def _insert(database: Any, workflow_id: str, value: bool, *, source: str)
async def set_ask_first(database: Any, workflow_id: str, value: bool, *, expected_revision: Optional[int] = None) -> WorkflowRule:
- """Change the rule. ``expected_revision`` (the revision the caller read)
- makes it a compare-and-swap; :class:`RuleConflict` when it moved."""
+ """Change the rule; the mode follows it again. ``expected_revision``
+ (the revision the caller read) makes it a compare-and-swap;
+ :class:`RuleConflict` when it moved."""
+ return await _set(database, workflow_id, bool(value), None, expected_revision)
+
+
+async def set_mode(database: Any, workflow_id: str, mode: str, *, expected_revision: Optional[int] = None) -> WorkflowRule:
+ """Change the mode, with Ask first in step (off only for money and
+ deletes), as :func:`set_ask_first` does. ``ValueError`` for a mode that
+ is not one of :data:`ASKS`."""
+ if mode not in ASKS:
+ raise ValueError(f"unknown mode: {mode!r}")
+ return await _set(database, workflow_id, mode != "money_only", mode, expected_revision)
+
+
+async def _set(database: Any, workflow_id: str, value: bool, mode: Optional[str], expected_revision: Optional[int]) -> WorkflowRule:
current = await get_rule(database, workflow_id)
if current is None:
if expected_revision not in (None, 0):
raise RuleConflict(None)
- return await _insert(database, workflow_id, bool(value), source="owner")
+ return await _insert(database, workflow_id, value, source="owner", mode=mode)
if expected_revision is not None and current.revision != expected_revision:
raise RuleConflict(current)
async with database.get_session() as session:
result = await session.execute(
update(WorkflowRule)
.where(WorkflowRule.workflow_id == workflow_id, WorkflowRule.revision == current.revision)
- .values(ask_first=bool(value), revision=current.revision + 1, source="owner", updated_at=_utcnow())
+ .values(ask_first=value, mode=mode, revision=current.revision + 1, source="owner", updated_at=_utcnow())
)
await session.commit()
if not result.rowcount:
@@ -155,12 +196,16 @@ async def delete_rule(database: Any, workflow_id: str) -> None:
__all__ = [
+ "ASKS",
"RuleConflict",
"ask_first",
+ "ask_mode",
"delete_rule",
"get_rule",
+ "mode_of",
"notify_rule_changed",
"register_rule_listener",
"register_rule_seeder",
"set_ask_first",
+ "set_mode",
]
diff --git a/server/services/approvals/store.py b/server/services/approvals/store.py
index eef34f7f..ecfb4368 100644
--- a/server/services/approvals/store.py
+++ b/server/services/approvals/store.py
@@ -343,15 +343,39 @@ def _iso(moment: Optional[datetime]) -> Optional[str]:
return moment.isoformat() if moment is not None else None
+#: What the card of a tool with no spec says once it ran, and when it did not.
+DONE_OUTCOME = ("Done", "Not done")
+
+
+def _spec_of(row: ApprovalRequest) -> Any:
+ from services.node_registry import get_node_class
+ from services.plugin.approval import approval_spec
+
+ return approval_spec(get_node_class(row.node_type)) if row.node_type else None
+
+
def _outcome_labels(row: ApprovalRequest) -> Tuple[str, str]:
"""What the card says once it went, and when it did not: a held tool
call's plugin words it (its ``approval`` spec); a gate's draft is a
- message."""
+ message; a tool with no spec did something."""
+ from services.plugin.approval import MESSAGE_OUTCOME
+
+ if row.kind != "tool_call":
+ return MESSAGE_OUTCOME
+ spec = _spec_of(row)
+ 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."""
+ from services.approvals.classes import call_data, class_of
from services.node_registry import get_node_class
- from services.plugin.approval import MESSAGE_OUTCOME, approval_spec
- spec = approval_spec(get_node_class(row.node_type)) if row.kind == "tool_call" and row.node_type else None
- return spec.outcome_labels if spec is not None else MESSAGE_OUTCOME
+ node_cls = get_node_class(row.node_type) if row.node_type else None
+ if node_cls is None:
+ return None
+ return class_of(node_cls, call_data(node_cls, row.node_data or {}, row.args), tool_call=bool(row.tool_call_id))
def summary(row: ApprovalRequest, *, deployment_state: Optional[str] = None, now: Optional[datetime] = None) -> Dict[str, Any]:
@@ -380,6 +404,12 @@ 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)
+ # 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"
if row.action:
out["action"] = row.action
subject = row.final_subject if decided and row.final_subject else row.subject
diff --git a/server/services/approvals/tool_calls.py b/server/services/approvals/tool_calls.py
index 33097d10..0894c434 100644
--- a/server/services/approvals/tool_calls.py
+++ b/server/services/approvals/tool_calls.py
@@ -17,6 +17,19 @@ A call that comes back to run because the owner pressed Send carries
``approval_execution`` (services/approvals/execution.py): it runs only when
its row is the one being sent, and is never held again.
+**In a v1 generation** (``approval_wait_version`` 1, RFC-0007 §4.3) the
+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.
+- 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.
+- A call its turn waits on (``approval_wait``) is a turn row (``runtime:
+ turn``); any other is a draft.
+- A rule that cannot be read asks before everything.
+
**Agents outside AgentWorkflow** (rlm, claude_code, or every agent
with AgentWorkflow off) reach plugins through ``services/handlers/tools.py``,
which calls :func:`check_in_process`. Such a call cannot wait as a draft, so
@@ -67,6 +80,11 @@ HELD_MESSAGE = (
"Not sent yet: it waits for the owner's OK on a card in the chat. It goes out only if they press Send, "
"so do not call this again for it. Tell them it is ready for them to check."
)
+#: The same in a v1 generation, where the card's button is Allow.
+WAITING_MESSAGE = (
+ "Not done yet: it waits for the owner's OK on a card in the chat, and runs only if they allow it. "
+ "Do not call this again for it; tell them it is ready for them to check."
+)
REFUSED_MESSAGE = (
"Not run: {channel} cannot wait for the owner's OK, and they ask to approve everything first. "
"Tell them what you would do; they can turn Ask first off to let you."
@@ -150,7 +168,7 @@ def _clean_node_data(node_cls: Any, node_data: Mapping[str, Any], args: Mapping[
return {key: value for key, value in dict(node_data or {}).items() if not (key in locked and key in (args or {}))}
-def _held(row: Any, node_cls: Any, context: Mapping[str, Any]) -> Dict[str, Any]:
+def _held(row: Any, node_cls: Any, context: Mapping[str, Any], message: str = HELD_MESSAGE) -> Dict[str, Any]:
from datetime import datetime as _dt
return {
@@ -162,7 +180,7 @@ def _held(row: Any, node_cls: Any, context: Mapping[str, Any]) -> Dict[str, Any]
"approval_id": row.id,
"channel": row.channel,
"to": row.recipient_label or row.recipient,
- "message": HELD_MESSAGE,
+ "message": message,
},
"approval_id": row.id,
"execution_id": context.get("execution_id"),
@@ -188,6 +206,24 @@ async def _asks_first(database: Any, workflow_id: Any) -> Optional[bool]:
return True
+async def _ask_mode(database: Any, workflow_id: Any) -> Optional[str]:
+ """The workflow's mode (None: no rule). The strictest when it cannot be
+ read: hold the call rather than run it unasked."""
+ try:
+ return await rules.ask_mode(database, workflow_id)
+ except Exception:
+ logger.warning("Could not read the Ask first mode; asking before everything", workflow_id=workflow_id, exc_info=True)
+ return "everything"
+
+
+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."""
+ restricted = {**node_data, **dict(spec.restrict_while_asking)}
+ tool_args = {k: v for k, v in dict(context.get("tool_args") or {}).items() if k not in spec.restrict_while_asking}
+ return Checked(node_data=restricted, tool_args=tool_args)
+
+
async def check(context: Mapping[str, Any], node_cls: Any) -> Checked:
"""What to do with a tool call before it runs (see the module docstring)."""
from services.plugin.approval import approval_spec
@@ -206,6 +242,8 @@ async def check(context: Mapping[str, Any], node_cls: Any) -> Checked:
"error_type": "ApprovalNotClaimed",
}
)
+ if context.get("approval_wait_version") == 1:
+ return await _check_by_class(context, node_cls, spec)
if spec is None or not is_agent_tool_call(context):
return RUN
node_data = await as_it_runs(context, node_cls)
@@ -230,13 +268,36 @@ async def check(context: Mapping[str, Any], node_cls: Any) -> Checked:
}
)
if spec.restrict_while_asking:
- restricted = {**node_data, **dict(spec.restrict_while_asking)}
- tool_args = {k: v for k, v in dict(context.get("tool_args") or {}).items() if k not in spec.restrict_while_asking}
- return Checked(node_data=restricted, tool_args=tool_args)
+ return _restricted(spec, node_data, context)
row = await hold(database, context, node_cls, spec, node_data)
return Checked(result=_held(row, node_cls, context))
+async def _check_by_class(context: Mapping[str, Any], node_cls: Any, spec: Any) -> Checked:
+ """:func:`check` in a v1 generation (see the module docstring)."""
+ from services.approvals.classes import MONEY, READ, SEND, call_data, class_of, fetched_url
+
+ if not is_agent_tool_call(context):
+ return RUN
+ node_data = await as_it_runs(context, node_cls)
+ judged = call_data(node_cls, node_data, context.get("tool_args"))
+ klass = class_of(node_cls, judged, tool_call=True)
+ if klass == READ:
+ return RUN
+ database = _database()
+ mode = await _ask_mode(database, context.get("workflow_id"))
+ if mode is None:
+ return RUN
+ if klass not in rules.ASKS[mode]:
+ 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
+ if spec is not None and spec.restrict_while_asking and not fetched_url(node_cls, judged):
+ return _restricted(spec, node_data, context)
+ row = await hold(database, context, node_cls, spec, node_data)
+ return Checked(result=_held(row, node_cls, context, WAITING_MESSAGE))
+
+
async def check_in_process(
context: Mapping[str, Any],
node_cls: Any,
@@ -264,10 +325,44 @@ async def check_in_process(
return Checked(result={"status": "not_run", "message": REFUSED_MESSAGE.format(channel=spec.channel)})
+def _preview(node_cls: Any, spec: Any, data: Mapping[str, Any], args: Mapping[str, Any]) -> Dict[str, Any]:
+ """What the card shows: the spec's view of the call, or, for a tool with
+ no spec, its name and up to six of what it runs with, the call's own
+ arguments first. A call that fetches a URL shows it."""
+ from services.approvals.classes import call_data, fetched_url
+
+ own = call_data(node_cls, data, args)
+ if spec is not None:
+ preview = spec.preview(data)
+ url = fetched_url(node_cls, own)[:300]
+ if url and all(line.get("value") != url for line in preview["details"]):
+ preview["details"] = [{"label": "Address", "value": url}, *preview["details"]]
+ return preview
+ node_type = getattr(node_cls, "type", "")
+ name = _tool_name(node_cls, node_type)
+ values = {**args, **{key: value for key, value in data.items() if key not in args}}
+ return {"channel": name, "action": _action(name, node_type, own), "details": _argument_lines(node_cls, values)}
+
+
+def _tool_name(node_cls: Any, node_type: str) -> str:
+ return str(getattr(node_cls, "display_name", None) or node_type or "a tool")
+
+
+def _action(name: str, node_type: str, data: Mapping[str, Any]) -> str:
+ """"Use {tool}", with the operation the call names, as the class and
+ repeat tables name each node's operation field."""
+ from services.approvals.classes import CLASSES_WHEN
+ from services.approvals.repeats import REPEATABLE_WHEN
+
+ field = (CLASSES_WHEN.get(node_type) or REPEATABLE_WHEN.get(node_type) or ("",))[0]
+ operation = data.get(field) if field else None
+ return f"Use {name} ({operation})" if isinstance(operation, str) and operation else f"Use {name}"
+
+
def _row_fields(context: Mapping[str, Any], node_cls: Any, spec: Any, node_data: Mapping[str, Any]) -> Dict[str, Any]:
args = _clean_args(node_cls, context.get("tool_args") or {})
data = _clean_node_data(node_cls, node_data, context.get("tool_args") or {})
- preview = spec.preview(data)
+ preview = _preview(node_cls, spec, data, args)
stream = context.get("chat_stream") if isinstance(context.get("chat_stream"), Mapping) else {}
run_id = context.get("chat_run_id") or (stream or {}).get("run_id")
return {
@@ -300,8 +395,12 @@ def _row_fields(context: Mapping[str, Any], node_cls: Any, spec: Any, node_data:
async def hold(database: Any, context: Mapping[str, Any], node_cls: Any, spec: Any, node_data: Mapping[str, Any]) -> Any:
- """The held call's row: created once, found again on a retry."""
+ """The held call's row: created once, found again on a retry. ``spec``
+ is None for a tool with no spec (a v1 generation's generic card)."""
fields = _row_fields(context, node_cls, spec, node_data)
+ if context.get("approval_wait"):
+ # Its turn waits on it (RFC-0007 §4.6): a turn row, not a draft.
+ fields["runtime"] = "turn"
fields["expires_at"] = _utcnow() + timedelta(hours=DEFAULT_TIMEOUT_HOURS)
fields["ui_part_id"] = await _ui_part(database, fields.get("run_id"))
row, created = await store.get_or_create(database, idempotency_key=call_key(context), fields=fields)
@@ -539,12 +638,8 @@ async def _graph_send(context: Mapping[str, Any], node_cls: Any, node_data: Mapp
def _effect_fields(context: Mapping[str, Any], node_cls: Any, node_data: Mapping[str, Any]) -> Dict[str, Any]:
"""An ``effect`` row: what was tried and what it ran with (no secrets),
for a card the owner checks and dismisses."""
- from services.approvals.repeats import REPEATABLE_WHEN
-
node_type = getattr(node_cls, "type", None) or str(context.get("node_type") or "")
- name = str(getattr(node_cls, "display_name", None) or node_type or "a tool")
- field = REPEATABLE_WHEN.get(node_type, ("", frozenset()))[0]
- operation = node_data.get(field) if field else None
+ name = _tool_name(node_cls, node_type)
tool_args = context.get("tool_args")
stream = context.get("chat_stream") if isinstance(context.get("chat_stream"), Mapping) else {}
run_id = context.get("chat_run_id") or (stream or {}).get("run_id")
@@ -557,7 +652,7 @@ def _effect_fields(context: Mapping[str, Any], node_cls: Any, node_data: Mapping
"runtime": "temporal",
"kind": "effect",
"channel": name[:60],
- "action": (f"Use {name} ({operation})" if isinstance(operation, str) and operation else f"Use {name}")[:200],
+ "action": _action(name, node_type, node_data)[:200],
"details": _argument_lines(node_cls, tool_args if isinstance(tool_args, Mapping) else node_data),
"node_type": node_type or None,
"tool_node_id": str(context.get("node_id") or ""),
@@ -595,6 +690,7 @@ __all__ = [
"REDO_MESSAGE",
"RESEND_MESSAGE",
"RUN",
+ "WAITING_MESSAGE",
"as_it_runs",
"call_key",
"check",
diff --git a/server/tests/services/approvals/test_modes.py b/server/tests/services/approvals/test_modes.py
new file mode 100644
index 00000000..8b901452
--- /dev/null
+++ b/server/tests/services/approvals/test_modes.py
@@ -0,0 +1,195 @@
+"""What asks in a v1 generation (RFC-0007 §4.2, §4.3): the workflow's mode
+and the call's class decide, for every tool an agent calls. A read never
+asks; a call the mode does not ask runs, and leaves a record in the chat
+when it reaches out; an asked call is held, on a generic card when its tool
+has no spec and as a turn row when its turn waits on it; the Browser is held
+only when it navigates, and browses read-only otherwise. A v0 generation
+keeps Ask first and the plugins' specs."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+from sqlalchemy import text
+
+import nodes # noqa: F401 -- populate plugin registry
+from services.approvals import rules, store, tool_calls
+from services.node_registry import get_node_class
+
+pytestmark = pytest.mark.asyncio
+
+WHATSAPP = {"recipient_type": "phone", "phone": "447700900123", "message": "On my way."}
+WRITE_FILE = {"operation": "write", "path": "notes.md", "content": "Plan"}
+SOCKET = SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(user_id="owner"))
+
+
+def call(node_type, tool_args, node_data=None, *, v1=True, **extra):
+ return {
+ "node_id": f"wf:{node_type}:1",
+ "node_type": node_type,
+ "workflow_id": "wf",
+ "execution_id": "wf:execution:1",
+ "user_id": "owner",
+ "parent_node_id": "wf:aiAgent:1",
+ "tool_call_id": f"call_{node_type}",
+ "node_data": {**(node_data or {}), **tool_args},
+ "tool_args": tool_args,
+ **({"approval_wait_version": 1} if v1 else {}),
+ **extra,
+ }
+
+
+async def check(node_type, tool_args, node_data=None, **extra):
+ return await tool_calls.check(call(node_type, tool_args, node_data, **extra), get_node_class(node_type))
+
+
+async def test_the_mode_follows_ask_first_until_the_owner_sets_one(harness):
+ assert await rules.ask_mode(harness.database, "wf") is None
+ await rules.set_ask_first(harness.database, "wf", False)
+ assert await rules.ask_mode(harness.database, "wf") == "money_only"
+ rule = await rules.set_mode(harness.database, "wf", "everything", expected_revision=0)
+ assert (rule.mode, rule.ask_first, rule.revision) == ("everything", True, 1)
+ # A v0 generation reads Ask first: off only for money and deletes.
+ rule = await rules.set_mode(harness.database, "wf", "money_only")
+ assert (rule.mode, rule.ask_first) == ("money_only", False)
+ with pytest.raises(rules.RuleConflict):
+ await rules.set_mode(harness.database, "wf", "outside", expected_revision=0)
+ with pytest.raises(ValueError):
+ await rules.set_mode(harness.database, "wf", "never")
+ # The Ask first switch makes the mode follow it again.
+ rule = await rules.set_ask_first(harness.database, "wf", True)
+ assert rule.mode is None and await rules.ask_mode(harness.database, "wf") == "outside"
+ # A workflow without a rule gets one.
+ assert (await rules.set_mode(harness.database, "other", "outside")).ask_first is True
+
+
+async def test_an_older_rules_table_gets_the_mode_column(harness):
+ async with harness.database.engine.begin() as conn:
+ await conn.execute(text("DROP TABLE workflow_rules"))
+ await conn.execute(
+ text(
+ "CREATE TABLE workflow_rules (workflow_id VARCHAR(255) PRIMARY KEY, ask_first BOOLEAN NOT NULL,"
+ " revision INTEGER NOT NULL, source VARCHAR(20) NOT NULL, updated_at DATETIME NOT NULL)"
+ )
+ )
+ await conn.execute(text("INSERT INTO workflow_rules VALUES ('wf', 0, 3, 'owner', '2026-01-01 10:00:00')"))
+ await harness.database._migrate_approvals()
+ await harness.database._migrate_approvals() # runs again at every startup; changes nothing
+ assert await rules.ask_mode(harness.database, "wf") == "money_only"
+ assert (await rules.set_mode(harness.database, "wf", "everything", expected_revision=3)).mode == "everything"
+
+
+async def test_a_v0_generation_keeps_ask_first_and_the_specs(harness):
+ await rules.set_ask_first(harness.database, "wf", True)
+ assert await check("shell", {"command": "ls"}, v1=False) is tool_calls.RUN
+ refused = await check("stripeAction", {"command": "customers list"}, v1=False)
+ assert refused.result["result"]["status"] == "not_run"
+
+
+ ("mode", "node_type", "args", "held"),
+ [
+ ("outside", "whatsappSend", WHATSAPP, True),
+ ("outside", "googleGmail", {"operation": "search", "query": "invoice"}, False),
+ ("outside", "fileModify", WRITE_FILE, False),
+ ("outside", "shell", {"command": "ls"}, True),
+ ("outside", "stripeAction", {"command": "customers list"}, True), # held, not refused (D8)
+ ("everything", "fileModify", WRITE_FILE, True),
+ ("everything", "googleGmail", {"operation": "search", "query": "invoice"}, False),
+ ("money_only", "whatsappSend", WHATSAPP, False),
+ ("money_only", "stripeAction", {"command": "customers list"}, True),
+ ("money_only", "googleCalendar", {"operation": "delete", "event_id": "e1", "send_updates": "none"}, True),
+ ],
+)
+async def test_the_mode_says_which_classes_ask(harness, mode, node_type, args, held):
+ await rules.set_mode(harness.database, "wf", mode)
+ checked = await check(node_type, args)
+ assert (checked.result is not None) is held
+ if held:
+ assert checked.result["result"]["status"] == "waiting_for_owner"
+ assert "allow" in checked.result["result"]["message"]
+
+
+async def test_a_tool_without_a_spec_is_held_on_a_generic_card(harness):
+ await rules.set_mode(harness.database, "wf", "outside")
+ args = {"method": "POST", "headers": {"Authorization": "Bearer s", "Accept": "application/json"}, "body": "{}"}
+ await check("httpRequest", args, {"url": "https://api.example/orders", "timeout": 30})
+ (row,) = await store.list_approvals(harness.database, status="pending")
+ summary = store.summary(row)
+ assert (row.channel, row.action, row.draft_text, summary["editable"]) == ("HTTP Request", "Use HTTP Request (POST)", "", False)
+ assert (summary["generic"], summary["approval_class"], summary["waits"]) == (True, "send", False)
+ assert summary["outcome_labels"] == {"sent": "Done", "failed": "Not done"}
+ # The call's own arguments first, then what it runs with; no header secret.
+ lines = {line["label"]: line["value"] for line in row.details}
+ assert list(lines)[:3] == ["method", "headers", "body"] and lines["url"] == "https://api.example/orders"
+ assert "Authorization" not in lines["headers"]
+
+
+async def test_a_call_its_turn_waits_on_is_a_turn_row(harness):
+ await rules.set_mode(harness.database, "wf", "outside")
+ await check("shell", {"command": "ls"}, approval_wait=True)
+ await check("shell", {"command": "pwd"}, tool_call_id="call_2")
+ rows = {row.tool_call_id: row for row in await store.list_approvals(harness.database, status="pending")}
+ assert rows["call_shell"].runtime == "turn" and store.summary(rows["call_shell"])["waits"] is True
+ assert rows["call_2"].runtime == "temporal" and store.summary(rows["call_2"])["waits"] is False
+
+
+async def test_the_browser_is_held_only_when_it_navigates(harness):
+ await rules.set_mode(harness.database, "wf", "outside")
+ navigating = await check("browser", {"operation": "navigate", "url": "https://shop.example"})
+ assert navigating.result["result"]["status"] == "waiting_for_owner"
+ # The card says where it goes.
+ (row,) = await store.list_approvals(harness.database, status="pending")
+ assert row.details[0] == {"label": "Address", "value": "https://shop.example"}
+ clicking = await check(
+ "browser", {"operation": "click", "ref": "e3", "interaction": "full"}, {"interaction": "full"}, tool_call_id="c2"
+ )
+ assert clicking.result is None
+ assert clicking.node_data["interaction"] == "read_only" and "interaction" not in clicking.tool_args
+ # Judged on the call itself: without an operation it takes a snapshot,
+ # whatever the node's settings say.
+ assert await check("browser", {}, {"operation": "navigate"}, tool_call_id="c3") is tool_calls.RUN
+
+
+async def test_an_unreadable_rule_asks_before_everything(harness, monkeypatch):
+ async def broken(*_args, **_kwargs):
+ raise RuntimeError("database is locked")
+
+ monkeypatch.setattr(rules, "ask_mode", broken)
+ assert (await check("fileModify", WRITE_FILE)).result["result"]["status"] == "waiting_for_owner"
+
+
+async def test_in_the_chat_a_call_that_reaches_out_is_recorded(harness, monkeypatch):
+ from services.chat import parts
+
+ async def show_approval(*_args, **_kwargs):
+ return None
+
+ monkeypatch.setattr(parts, "show_approval", show_approval)
+ stream = {"run_id": "r_1", "session_id": "wf", "workflow_id": "wf"}
+ await rules.set_mode(harness.database, "wf", "money_only")
+ sent = await check("whatsappSend", WHATSAPP, chat_stream=stream)
+ assert sent.result is None and sent.record is not None
+ # A write is the employee's own work, not something it sent.
+ await rules.set_mode(harness.database, "wf", "outside")
+ assert await check("fileModify", WRITE_FILE, chat_stream=stream) is tool_calls.RUN
+
+
+async def test_a_graph_node_is_never_held(harness):
+ await rules.set_mode(harness.database, "wf", "everything")
+ assert await check("whatsappSend", WHATSAPP, parent_node_id=None) is tool_calls.RUN
+
+
+async def test_the_ask_first_commands_read_and_set_the_mode(harness, monkeypatch):
+ from services.approvals.handlers import handle_get_ask_first, handle_set_ask_first
+
+ monkeypatch.setattr(rules, "_LISTENERS", [])
+ await harness.database.save_workflow("7", "Maya", "Maya_1", {"nodes": [], "edges": []})
+ assert (await handle_get_ask_first({"workflow_id": "7"}, SOCKET))["mode"] is None
+ answer = await handle_set_ask_first({"workflow_id": "7", "mode": "everything"}, SOCKET)
+ assert answer == {**answer, "success": True, "mode": "everything", "ask_first": True, "revision": 0}
+ assert (await handle_get_ask_first({"workflow_id": "7"}, SOCKET))["mode"] == "everything"
+ stale = await handle_set_ask_first({"workflow_id": "7", "mode": "outside", "expected_revision": 5}, SOCKET)
+ assert stale == {**stale, "success": False, "error": "rule_conflict", "mode": "everything"}
+ assert (await handle_set_ask_first({"workflow_id": "7", "mode": "never"}, SOCKET))["error"] == "invalid_request"