Skip to content

Self-improving AI Employees for everyone

feat(approvals): CLI and in-process drafts (RFC-0007 AP.2c, 1 of 2)

trohitgaf9c060740b7
diff --git a/server/services/approvals/tool_calls.py b/server/services/approvals/tool_calls.py
index faa8b08d..33d9e5f8 100644
--- a/server/services/approvals/tool_calls.py
+++ b/server/services/approvals/tool_calls.py
@@ -33,9 +33,12 @@ for every tool an agent calls, spec or not:
**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
-while the workflow asks first a call that sends is refused (a restricted
-tool runs restricted); no row is written.
+which calls :func:`check_in_process`. In a v0 generation such a call cannot
+wait as a draft, so while the workflow asks first a call that sends is
+refused (a restricted tool runs restricted); no row is written. In a v1
+generation it asks as :func:`check` decides, and a held call is a draft
+keyed by its call id (an MCP call's request digest); a call with no id is
+refused.
**At most once.** Temporal runs an activity again only when an attempt
broke off (the worker stopped, a timeout): a failure the node reports comes
@@ -325,6 +328,8 @@ async def check_in_process(
from services.plugin.base import restore_locked_fields
spec = approval_spec(node_cls)
+ if context.get("approval_wait_version") == 1:
+ return await _check_in_process_by_class(context, node_cls, spec, params, tool_args)
if spec is None or not context.get("parent_node_id"):
return RUN
# Judged on what runs: a locked field comes from the node's settings.
@@ -339,6 +344,38 @@ async def check_in_process(
return Checked(result={"status": "not_run", "message": REFUSED_MESSAGE.format(channel=spec.channel)})
+async def _check_in_process_by_class(
+ context: Mapping[str, Any], node_cls: Any, spec: Any, params: Mapping[str, Any], tool_args: Mapping[str, Any]
+) -> Checked:
+ """:func:`check_in_process` in a v1 generation (RFC-0007 §4.9): the order
+ of :func:`check`, and a held call is a draft keyed by its call id, which
+ the owner's Send runs through the node's own activity. A call with no
+ id is refused: a retry could not find its draft."""
+ from services.approvals.classes import READ, call_data, class_of, fetched_url
+ from services.plugin.base import restore_locked_fields
+
+ if not context.get("parent_node_id"):
+ return RUN
+ # Judged on what runs: a locked field comes from the node's settings.
+ node_data = restore_locked_fields(node_cls, {**dict(params or {}), **dict(tool_args or {})}, tool_args, params or {})
+ judged = call_data(node_cls, node_data, 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"))
+ held = {**context, "node_data": node_data, "tool_args": dict(tool_args or {})}
+ if mode is None or klass not in rules.ASKS[mode] or await _allowed(database, held, node_cls, node_data):
+ return RUN
+ if spec is not None and spec.restrict_while_asking and not fetched_url(node_cls, judged):
+ return _restricted(spec, params or {}, held)
+ if not context.get("tool_call_id"):
+ channel = spec.channel if spec is not None else _tool_name(node_cls, getattr(node_cls, "type", ""))
+ return Checked(result={"status": "not_run", "message": REFUSED_MESSAGE.format(channel=channel)})
+ row = await hold(database, held, node_cls, spec, node_data)
+ return Checked(result=_held(row, node_cls, held, WAITING_MESSAGE)["result"])
+
+
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
@@ -373,12 +410,21 @@ def _action(name: str, node_type: str, data: Mapping[str, Any]) -> str:
return f"Use {name} ({operation})" if isinstance(operation, str) and operation else f"Use {name}"
+def _run_id(context: Mapping[str, Any]) -> Optional[str]:
+ """The chat run the call was made in: its stream's, else its run scope's
+ (a CLI or in-process agent's call has no stream)."""
+ from services.chat.stream import chat_run_id_of
+
+ 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") or chat_run_id_of(context)
+ return run_id if isinstance(run_id, str) and run_id else None
+
+
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 = _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")
+ run_id = _run_id(context)
return {
"owner_id": str(context.get("user_id") or "owner"),
"workflow_id": str(context.get("workflow_id") or ""),
@@ -399,7 +445,7 @@ def _row_fields(context: Mapping[str, Any], node_cls: Any, spec: Any, node_data:
"tool_node_id": str(context.get("node_id") or ""),
"tool_call_id": str(context.get("tool_call_id") or ""),
"agent_node_id": str(context.get("parent_node_id") or ""),
- "run_id": run_id if isinstance(run_id, str) and run_id else None,
+ "run_id": run_id,
"node_data": data,
"args": args,
"original_args": dict(context.get("tool_args") or {}),
@@ -655,8 +701,6 @@ def _effect_fields(context: Mapping[str, Any], node_cls: Any, node_data: Mapping
node_type = getattr(node_cls, "type", None) or str(context.get("node_type") or "")
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")
return {
"owner_id": str(context.get("user_id") or "owner"),
"workflow_id": str(context.get("workflow_id") or ""),
@@ -672,7 +716,7 @@ def _effect_fields(context: Mapping[str, Any], node_cls: Any, node_data: Mapping
"tool_node_id": str(context.get("node_id") or ""),
"tool_call_id": str(context.get("tool_call_id") or ""),
"agent_node_id": str(context.get("parent_node_id") or ""),
- "run_id": run_id if isinstance(run_id, str) and run_id else None,
+ "run_id": _run_id(context),
}
diff --git a/server/services/cli_agent/workflow_tools.py b/server/services/cli_agent/workflow_tools.py
index 5a8e8cc0..12d2cd4c 100644
--- a/server/services/cli_agent/workflow_tools.py
+++ b/server/services/cli_agent/workflow_tools.py
@@ -334,23 +334,25 @@ def _build_handler(
"parameters": dict(entry.get("parameters") or {}),
**({"pi_harness_version": 1} if entry.get("pi_harness_version") == 1 else {}),
}
+ # Every call gets the request's identity: a stateful tool's idempotency
+ # key, and a held call's draft key (services/approvals/tool_calls.py).
+ # Request IDs are local to one client. The stateful HTTP transport
+ # validates its server-issued session ID before calling this tool, so
+ # parallel CLI sessions need that namespace as well.
+ mcp = _get_mcp()
+ if mcp is not None:
+ try:
+ request_context = mcp.get_context().request_context
+ request = request_context.request
+ session_id = request.headers.get("mcp-session-id") if request is not None else None
+ if session_id:
+ from services.temporal.pi_protocol import canonical_digest
+ config["tool_call_id"] = "mcp:" + canonical_digest({
+ "session": session_id, "request": request_context.request_id,
+ })
+ except ValueError:
+ pass # The admission guard, or the draft, reports the missing identity.
if config.get("node_type") in {"coding_agent", "taskManager", "_builtin_check_delegated_tasks"} and config.get("pi_harness_version") == 1:
- # Request IDs are local to one client. The stateful HTTP transport
- # validates its server-issued session ID before calling this tool,
- # so parallel CLI sessions need that namespace as well.
- mcp = _get_mcp()
- if mcp is not None:
- try:
- request_context = mcp.get_context().request_context
- request = request_context.request
- session_id = request.headers.get("mcp-session-id") if request is not None else None
- if session_id:
- from services.temporal.pi_protocol import canonical_digest
- config["tool_call_id"] = "mcp:" + canonical_digest({
- "session": session_id, "request": request_context.request_id,
- })
- except ValueError:
- pass # The admission guard reports the missing identity.
from services.plugin.deps import get_ai_service, get_database
config["ai_service"] = get_ai_service()
config["database"] = get_database()
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index 5a3bcbd5..46e09e76 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -197,7 +197,7 @@ async def _dispatch_tool(tool_name: str, tool_args: Dict[str, Any], config: Dict
for key in ("run_scope", "generation", "parameter_snapshot", "employee_job_id", "team_task_id",
"root_execution_id", "team_id", "team_execution_id", "data_scope_id", "context_execution_id",
"context_session_id", "session_id", "graphVersion", "outputs", "credential_customer_id",
- "ai_service", "database"):
+ "ai_service", "database", "approval_wait_version"):
if key in config:
context[key] = config[key]
if config.get("pi_harness_version") == 1:
@@ -248,10 +248,11 @@ async def _dispatch_tool(tool_name: str, tool_args: Dict[str, Any], config: Dict
database = config.get("database") or container.database()
node_params = restore_dropped(node_params, await database.get_node_parameters(config["node_id"]) or {})
- # Ask first: a call that sends is refused while the workflow asks
- # first (it cannot wait as a draft here); a restricted tool runs
- # restricted. Temporal tool calls are checked in BaseNode.as_activity.
- checked = await check_in_process(context, plugin_cls, node_params, tool_args)
+ # Ask first: in a v0 generation a call that sends is refused while
+ # the workflow asks first; in v1 a held call is a draft its node's
+ # own activity sends later. A restricted tool runs restricted.
+ # Temporal tool calls are checked in BaseNode.as_activity.
+ checked = await check_in_process({**context, "node_id": config.get("node_id")}, plugin_cls, node_params, tool_args)
if checked.result is not None:
return checked.result
if checked.node_data is not None:
diff --git a/server/services/temporal/pi_inline_delegation.py b/server/services/temporal/pi_inline_delegation.py
index 02fae15b..b863d205 100644
--- a/server/services/temporal/pi_inline_delegation.py
+++ b/server/services/temporal/pi_inline_delegation.py
@@ -35,6 +35,8 @@ INLINE_SCOPE_KEYS = (
"execution_control_version", "controller_workflow_id", "execution_control_state",
"execution_control_revision", "execution_control_producers_held",
"execution_control_root_run_id", "execution_control_released_revision",
+ # What asks, for a CLI or in-process agent's tool calls (RFC-0007 §4.9).
+ "approval_wait_version",
)
diff --git a/server/tests/services/approvals/test_tool_calls.py b/server/tests/services/approvals/test_tool_calls.py
index e449aee6..818fadfe 100644
--- a/server/tests/services/approvals/test_tool_calls.py
+++ b/server/tests/services/approvals/test_tool_calls.py
@@ -241,6 +241,41 @@ async def test_an_unreadable_rule_refuses_rather_than_sends(harness, nodes_loade
assert refused["status"] == "not_run" and ran.calls == []
+async def test_in_a_v1_generation_an_agent_outside_agentworkflow_leaves_a_draft(harness, nodes_loaded, monkeypatch):
+ # RFC-0007 §4.9: the draft carries the call's id, its node and its chat
+ # run, so Send can run it through the node's own activity.
+ whatsapp, gmail = get_node_class("whatsappSend"), get_node_class("googleGmail")
+ ran = Ran()
+ monkeypatch.setattr(whatsapp, "execute_as_tool", ran)
+ monkeypatch.setattr(gmail, "execute_as_tool", ran)
+ await rules.set_mode(harness.database, "wf", "outside")
+ args = {"recipient_type": "phone", "phone": "447700900123", "message": "On my way."}
+ v1 = {"approval_wait_version": 1, "run_scope": {"run_id": "r_1"}}
+ answer = await dispatch("whatsappSend", args, {"message_type": "text"}, tool_call_id="mcp:abc", **v1)
+ assert answer["status"] == "waiting_for_owner" and "allow" in answer["message"] and ran.calls == []
+ (row,) = await store.list_approvals(harness.database, status="pending")
+ assert (row.tool_node_id, row.tool_call_id, row.run_id, row.runtime) == ("wf:whatsappSend:1", "mcp:abc", "r_1", "temporal")
+ # The same request again finds its draft; a call with no id cannot have one.
+ again = await dispatch("whatsappSend", args, {"message_type": "text"}, tool_call_id="mcp:abc", **v1)
+ assert again["approval_id"] == answer["approval_id"]
+ assert (await dispatch("whatsappSend", args, {"message_type": "text"}, **v1))["status"] == "not_run"
+ # A read runs.
+ assert await dispatch("googleGmail", {"operation": "search", "query": "invoice"}, tool_call_id="mcp:def", **v1) == {"sent": True}
+
+
+async def test_in_a_v1_generation_the_browser_outside_agentworkflow_is_held_only_when_it_navigates(harness, nodes_loaded, monkeypatch):
+ browser = get_node_class("browser")
+ ran = Ran()
+ monkeypatch.setattr(browser, "execute_as_tool", ran)
+ await rules.set_mode(harness.database, "wf", "outside")
+ v1 = {"approval_wait_version": 1, "tool_call_id": "mcp:abc"}
+ await dispatch("browser", {"operation": "click", "ref": "e3", "interaction": "full"}, {"interaction": "full"}, **v1)
+ [(args, params)] = ran.calls
+ assert params["interaction"] == "read_only" and "interaction" not in args
+ held = await dispatch("browser", {"operation": "navigate", "url": "https://shop.example"}, **{**v1, "tool_call_id": "mcp:def"})
+ assert held["status"] == "waiting_for_owner" and len(ran.calls) == 1
+
+
async def test_send_starts_the_send_and_puts_it_back_when_nothing_can(harness, nodes_loaded, monkeypatch):
await rules.set_ask_first(harness.database, "wf", True)
await tool_calls.check(call(), get_node_class("whatsappSend"))
diff --git a/server/tests/services/cli_agent/test_workflow_tool_context.py b/server/tests/services/cli_agent/test_workflow_tool_context.py
index dd4428ca..e1fc89a3 100644
--- a/server/tests/services/cli_agent/test_workflow_tool_context.py
+++ b/server/tests/services/cli_agent/test_workflow_tool_context.py
@@ -67,6 +67,39 @@ async def test_handler_forwards_execution_workspace_and_parent_identity():
assert started.kwargs["execution_id"] == "execution-1"
+async def test_every_call_carries_its_request_identity(monkeypatch):
+ # A held call's draft is keyed by it (RFC-0007 §4.9), not only a delegation.
+ from services.temporal.pi_protocol import canonical_digest
+
+ request_context = SimpleNamespace(request_id=7, request=SimpleNamespace(headers={"mcp-session-id": "session-1"}))
+ monkeypatch.setattr(workflow_tools, "_get_mcp", lambda: SimpleNamespace(get_context=lambda: SimpleNamespace(request_context=request_context)))
+ context = BatchContext(
+ workflow_id="workflow-3",
+ node_id="cli-parent-3",
+ execution_id="execution-3",
+ workspace_dir=Path("workspace-3").resolve(),
+ broadcaster=SimpleNamespace(update_node_status=AsyncMock(), broadcast_agent_capability=AsyncMock()),
+ connected_tools=[
+ {
+ "node_id": "tool-3",
+ "node_type": "contextTestTool",
+ "_agent_tool_name": "contextTestTool",
+ "_agent_tool_input_model": _Params,
+ "parameters": {},
+ }
+ ],
+ )
+ context_token = mcp_server._current_batch.set(context)
+ execute = AsyncMock(return_value={"ok": True})
+ try:
+ with patch("services.handlers.tools.execute_tool", new=execute):
+ await workflow_tools._build_handler("contextTestTool", _Params)(value="hello")
+ finally:
+ mcp_server._current_batch.reset(context_token)
+
+ assert execute.await_args.args[2]["tool_call_id"] == "mcp:" + canonical_digest({"session": "session-1", "request": 7})
+
+
async def test_handler_validates_the_authenticated_batch_schema():
context = BatchContext(
workflow_id="workflow-2",