Skip to content

Commit 23a681e

Browse files
fix(system-agent): tell messaging users a delegated approval can't be applied from chat (#116519) (#117432)
* fix(system-agent): surface operator-only approval handoff on all delegated routes (#116519) Delegated OpenClaw writes from messaging channels told the user to approve conversationally ("Say yes to apply"), but delegated sessions intentionally ignore chat approvals — only an operator in the OpenClaw UI can resolve them. - Default agent-loop route: thread operatorApprovalOnly from the engine through the turn runner into the ring-zero tool options; the tool registers the delegated proposal for the operator registry and instructs the model to surface the OpenClaw operator UI / `openclaw` CLI path instead of a dead-end conversational prompt (the needs-approval marker is kept so out-of-process CLI hosts still mirror the refusal). - Planner-fallback route: the delegated reply preserves refusal evidence (what was requested, that it was not applied) alongside the operator handoff. - Gateway: the closed SystemAgentChatResult schema is unchanged — the openclaw.chat response carries only needsApproval/proposalId; no approvalHint field. - Coverage: real agent-loop turn through the real ring-zero tool, tool-boundary delegated refusal + marker transition, engine default-route passthrough, and direct-session "Say yes to apply" preserved. - Plugin SDK: regenerate plugin-sdk-api-baseline.jsonl — the new optional operatorApprovalOnly field on SystemAgentToolOptions flows into the createOpenClawCodingTools options closure, changing its closureHash; the export declaration is unchanged. * fix(system-agent): preserve validation in delegated approval handoffs Keep executor preapproval validation before staging delegated proposals, share actionable operator handoff text, and align the system prompt. Cover real tool and transport behavior while retaining direct approvals. Co-authored-by: SunnyShu0925 <[email protected]> * test(system-agent): restore scoped CLI fixture and reuse suites Keep delegated approval coverage inside existing suites without increasing shard or file-size limits. Restore the CLI backend fixture dropped when chat-engine tests were split, avoiding real plugin setup loading in routing and continuity tests. --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 60dc020 commit 23a681e

14 files changed

Lines changed: 309 additions & 14 deletions

‎docs/cli/openclaw.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,11 @@ Starting a guided setup flow also runs immediately: channel setup (`connect tele
110110

111111
Persistent operations require conversational approval (or `--yes` for a direct command): write config, `config set`, `config set-ref`, setup/onboarding bootstrap, change the default model, start/stop/restart the Gateway, create agents, and install plugins.
112112

113+
Changes delegated by a regular agent, including requests from messaging channels,
114+
require approval in the OpenClaw operator UI. Replying "yes" in that chat cannot
115+
approve the change. Run `openclaw dashboard` on the Gateway host to review the
116+
pending approval, or run the change directly with `openclaw setup` there.
117+
113118
Configured agents can ask OpenClaw to create another agent through their
114119
`openclaw` tool. The request enters the same typed create-agent operation and
115120
operator approval flow used by Ask OpenClaw; the approval summary names the

‎src/agents/cli-runner/bundle-mcp.resume.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,14 @@ describe("prepareCliBundleMcpConfig resume hash", () => {
108108
expect(first.mcpConfigHash).not.toBe(approval.mcpConfigHash);
109109
expect(first.mcpResumeHash).toBe(approval.mcpResumeHash);
110110
expect(approval.mcpResumeHash).not.toBe(otherSurface.mcpResumeHash);
111+
const delegated = await prepare({
112+
surface: "cli",
113+
operatorApprovalOnly: true,
114+
approvalArmed: true,
115+
proposalRef: { current: proposed },
116+
});
117+
expect(delegated.mcpConfigHash).not.toBe(approval.mcpConfigHash);
118+
expect(delegated.mcpResumeHash).toBe(approval.mcpResumeHash);
111119
const binding = {
112120
sessionId: "native-cli-session",
113121
authProfileId: "claude-cli:ops",
@@ -142,5 +150,6 @@ describe("prepareCliBundleMcpConfig resume hash", () => {
142150
await first.cleanup?.();
143151
await approval.cleanup?.();
144152
await otherSurface.cleanup?.();
153+
await delegated.cleanup?.();
145154
});
146155
});

‎src/agents/tools/system-agent-tool.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,46 @@ describe("openclaw tool", () => {
102102
expect(mocks.executeSystemAgentOperation).not.toHaveBeenCalled();
103103
});
104104

105+
it("registers delegated proposals but never instructs a chat 'yes'", async () => {
106+
const proposalRef: { current?: string } = {};
107+
const args = {
108+
action: "config_set" as const,
109+
path: "agents.defaults.subagents.thinking",
110+
value: "high",
111+
approved: true,
112+
};
113+
const tool = createSystemAgentTool({
114+
surface: "gateway",
115+
operatorApprovalOnly: true,
116+
proposalRef,
117+
});
118+
119+
const result = await tool.execute("t-delegated", args);
120+
const text = toolText(result);
121+
122+
expect(text).toContain("needs-approval:");
123+
expect(text).toContain("OpenClaw operator UI");
124+
expect(text).toContain("cannot be applied from this chat");
125+
expect(text).not.toContain("ask the user to reply yes");
126+
expect(proposalRef.current).toBe(
127+
hashSystemAgentOperation({
128+
kind: "config-set",
129+
path: "agents.defaults.subagents.thinking",
130+
value: "high",
131+
}),
132+
);
133+
expect(mocks.executeSystemAgentOperation).not.toHaveBeenCalled();
134+
// Out-of-process CLI hosts still mirror the refusal from the marker line.
135+
expect(resolveSystemAgentProposalTransition({ args, resultText: text })).toEqual({
136+
proposal: proposalRef.current,
137+
operation: {
138+
kind: "config-set",
139+
path: "agents.defaults.subagents.thinking",
140+
value: "high",
141+
},
142+
});
143+
});
144+
105145
it("rejects arbitrary plugin installs before creating an approval proposal", async () => {
106146
const proposalRef: { current?: string } = {};
107147
const tool = createSystemAgentTool({ surface: "cli", proposalRef });

‎src/agents/tools/system-agent-tool.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import type { RuntimeEnv } from "../../runtime.js";
1111
import {
1212
executeSystemAgentOperation,
1313
isPersistentSystemAgentOperation,
14+
SYSTEM_AGENT_OPERATOR_APPROVAL_HANDOFF,
1415
type SystemAgentOperation,
1516
} from "../../system-agent/operations.js";
1617
import { validateSystemAgentPluginInstallSpec } from "../../system-agent/plugin-install-spec.js";
@@ -20,6 +21,8 @@ import { textResult, ToolInputError, readToolStringParam, type AnyAgentTool } fr
2021
export type SystemAgentToolOptions = {
2122
/** Where setup side effects run; the gateway surface never manages its own daemon. */
2223
surface: "cli" | "gateway";
24+
/** Delegated proposals require operator UI approval, never a chat reply. */
25+
operatorApprovalOnly?: boolean;
2326
/**
2427
* Host-verified consent for THIS turn: true only when the host judged the
2528
* user's actual message to be an explicit approval. The model-supplied
@@ -487,8 +490,11 @@ export function createSystemAgentTool(options: SystemAgentToolOptions): AnyAgent
487490
options.proposalRef.current = operationHash;
488491
options.proposalRef.operation = operation;
489492
}
493+
const approvalHint = options.operatorApprovalOnly
494+
? `The proposal is registered for operator approval. Do not request conversational approval. ${SYSTEM_AGENT_OPERATOR_APPROVAL_HANDOFF}`
495+
: "The proposal is registered; describe this exact change and ask the user to reply yes (their approval unlocks THIS action only — then retry the exact registered operation with approved=true).";
490496
return textResult(
491-
`${SYSTEM_AGENT_NEEDS_APPROVAL_PREFIX}${operationHash}\nThis action changes state. The proposal is registered; describe this exact change and ask the user to reply yes (their approval unlocks THIS action only — then retry the exact registered operation with approved=true).`,
497+
`${SYSTEM_AGENT_NEEDS_APPROVAL_PREFIX}${operationHash}\nThis action changes state. ${approvalHint}`,
492498
{ needsApproval: true },
493499
);
494500
}

‎src/mcp/openclaw-tools-serve-config.ts‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ export const OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_APPROVAL_ARMED_ENV =
1818
"OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_APPROVAL_ARMED";
1919
export const OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_PROPOSAL_ENV =
2020
"OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_PROPOSAL";
21+
// Delegation and chat consent are mutually exclusive. Keep both in the existing
22+
// per-turn transport value so native transcript resume identity stays stable.
23+
const APPROVAL_ARMED_OPERATOR_ONLY_VALUE = "operator-only";
2124

2225
const OPENCLAW_TOOLS_MCP_TOOL_IDS = ["cron", "openclaw"] as const;
2326
export type OpenClawToolsMcpToolId = (typeof OPENCLAW_TOOLS_MCP_TOOL_IDS)[number];
@@ -65,16 +68,19 @@ export function resolveOpenClawToolsMcpSystemAgentSurface(
6568
* Reconstruct per-turn approval state for the served openclaw tool. The
6669
* stdio server runs out of process, so the host passes the armed bit and the
6770
* pending proposal hash through env; the host mirrors transitions back from
68-
* tool events (see mirrorSystemAgentProposalFromToolEvents in agent-turn.ts).
71+
* tool events (see mirrorSystemAgentToolStateFromEvents in agent-turn.ts).
6972
*/
7073
export function resolveOpenClawToolsMcpSystemAgentApproval(env: NodeJS.ProcessEnv = process.env): {
7174
approvalArmed: boolean;
7275
proposalRef: { current?: string };
76+
operatorApprovalOnly?: boolean;
7377
} {
7478
const pendingProposal = env[OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_PROPOSAL_ENV]?.trim();
79+
const armedValue = env[OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_APPROVAL_ARMED_ENV]?.trim();
7580
return {
76-
approvalArmed: env[OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_APPROVAL_ARMED_ENV]?.trim() === "1",
81+
approvalArmed: armedValue === "1",
7782
proposalRef: pendingProposal ? { current: pendingProposal } : {},
83+
...(armedValue === APPROVAL_ARMED_OPERATOR_ONLY_VALUE ? { operatorApprovalOnly: true } : {}),
7884
};
7985
}
8086

@@ -134,9 +140,14 @@ export function buildSystemAgentToolsMcpServerConfig(
134140
[OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_SURFACE_ENV]: options.surface,
135141
// Per-turn approval state travels with the per-run MCP config; the
136142
// host mirrors proposal transitions back from tool events.
137-
...(options.approvalArmed === true
138-
? { [OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_APPROVAL_ARMED_ENV]: "1" }
139-
: {}),
143+
...(options.operatorApprovalOnly === true
144+
? {
145+
[OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_APPROVAL_ARMED_ENV]:
146+
APPROVAL_ARMED_OPERATOR_ONLY_VALUE,
147+
}
148+
: options.approvalArmed === true
149+
? { [OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_APPROVAL_ARMED_ENV]: "1" }
150+
: {}),
140151
...(pendingProposal
141152
? { [OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_PROPOSAL_ENV]: pendingProposal }
142153
: {}),

‎src/mcp/openclaw-tools-serve.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,4 +138,54 @@ describe("OpenClaw tools MCP server", () => {
138138
[OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_SURFACE_ENV]: "gateway",
139139
});
140140
});
141+
142+
it("serializes operator-approval-only through the native CLI MCP config", () => {
143+
const config = buildSystemAgentToolsMcpServerConfig({
144+
surface: "cli",
145+
operatorApprovalOnly: true,
146+
proposalRef: { current: "deadbeef" },
147+
});
148+
const server = config.mcpServers.openclaw as { env?: Record<string, string> };
149+
expect(server.env?.[OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_APPROVAL_ARMED_ENV]).toBe("operator-only");
150+
151+
// Non-delegated configs must not arm approval (direct sessions keep the
152+
// interactive "reply yes" approval flow until the host arms a turn).
153+
const direct = buildSystemAgentToolsMcpServerConfig({ surface: "cli" });
154+
const directServer = direct.mcpServers.openclaw as { env?: Record<string, string> };
155+
expect(directServer.env).not.toHaveProperty(OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_APPROVAL_ARMED_ENV);
156+
157+
// A host-armed direct turn uses "1", distinct from the delegated value.
158+
const armed = buildSystemAgentToolsMcpServerConfig({ surface: "cli", approvalArmed: true });
159+
const armedServer = armed.mcpServers.openclaw as { env?: Record<string, string> };
160+
expect(armedServer.env?.[OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_APPROVAL_ARMED_ENV]).toBe("1");
161+
});
162+
163+
it("reconstructs the delegated refusal from env on the native CLI MCP tool", async () => {
164+
const operation = {
165+
kind: "config-set",
166+
path: "agents.defaults.subagents.thinking",
167+
value: "high",
168+
} as const;
169+
vi.stubEnv(OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_APPROVAL_ARMED_ENV, "operator-only");
170+
vi.stubEnv(OPENCLAW_TOOLS_MCP_SYSTEM_AGENT_PROPOSAL_ENV, hashSystemAgentOperation(operation));
171+
const handlers = createPluginToolsMcpHandlers(
172+
resolveOpenClawToolsForMcp({ tools: ["openclaw"], systemAgentSurface: "cli" }),
173+
);
174+
175+
const result = await handlers.callTool({
176+
name: "openclaw",
177+
arguments: {
178+
action: "config_set",
179+
path: "agents.defaults.subagents.thinking",
180+
value: "high",
181+
approved: true,
182+
},
183+
});
184+
185+
const text = JSON.stringify(result);
186+
expect(text).toContain("needs-approval:");
187+
expect(text).toContain("OpenClaw operator UI");
188+
expect(text).toContain("cannot be applied from this chat");
189+
expect(text).not.toContain("ask the user to reply yes");
190+
});
141191
});

‎src/system-agent/agent-turn.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
55
import { listAgentEntries } from "../agents/agent-scope-config.js";
66
import { testing as cliBackendsTesting } from "../agents/cli-backends.test-support.js";
77
import { fingerprintResolvedProviderAuth } from "../agents/execution-auth-binding.js";
8+
import { createSystemAgentTool } from "../agents/tools/system-agent-tool.js";
89
import type { OpenClawConfig } from "../config/types.js";
910
import {
1011
cleanupSystemAgentSession,
@@ -831,6 +832,59 @@ describe("runSystemAgentTurn", () => {
831832
);
832833
});
833834

835+
it("threads operator-approval-only into the real ring-zero tool and returns the delegated refusal", async () => {
836+
useTempStateDir();
837+
const config = {
838+
agents: { defaults: { model: "openai/gpt-5.5" } },
839+
} satisfies OpenClawConfig;
840+
const { session, deps } = await createVerifiedSession(config);
841+
const runEmbeddedAgent = vi.fn(async (params: RunEmbeddedAgentParams) => {
842+
const options = params.systemAgentTool;
843+
if (!options) {
844+
throw new Error("missing system agent tool options");
845+
}
846+
const tool = createSystemAgentTool(options);
847+
const result = await tool.execute("delegated-turn", {
848+
action: "config_set",
849+
path: "agents.defaults.subagents.thinking",
850+
value: "high",
851+
approved: true,
852+
});
853+
const text = (result as { content: Array<{ type: string; text?: string }> }).content
854+
.map((block) => block.text ?? "")
855+
.filter(Boolean)
856+
.join("\n");
857+
return { meta: { finalAssistantVisibleText: text } };
858+
});
859+
860+
const reply = await runSystemAgentTurnWithDeps(
861+
{
862+
input: "switch the thinking level",
863+
overview: { defaultModel: "openai/gpt-5.5" } as never,
864+
surface: "gateway",
865+
approvalArmed: false,
866+
operatorApprovalOnly: true,
867+
session,
868+
},
869+
{
870+
...deps,
871+
runEmbeddedAgent: runEmbeddedAgent as never,
872+
readConfigFileSnapshot: vi.fn(async () => configSnapshot(config)) as never,
873+
},
874+
);
875+
876+
expect(runEmbeddedAgent).toHaveBeenCalledWith(
877+
expect.objectContaining({
878+
systemAgentTool: expect.objectContaining({ operatorApprovalOnly: true }),
879+
}),
880+
);
881+
expect(reply?.text).toContain("OpenClaw operator UI");
882+
expect(reply?.text).toContain("cannot be applied from this chat");
883+
expect(reply?.text).not.toContain("ask the user to reply yes");
884+
// The refusal still registers the exact proposal for the operator registry.
885+
expect(session.proposalRef.current).toBeDefined();
886+
});
887+
834888
it("rejects a low-level session without verified inference before lookup or run", async () => {
835889
useTempStateDir();
836890
const runCliAgent = vi.fn();

‎src/system-agent/agent-turn.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ export type SystemAgentTurnRunner = (params: {
5454
surface: "cli" | "gateway";
5555
/** Host-verified: the user's current message is an explicit approval. */
5656
approvalArmed: boolean;
57+
/** Delegated sessions can only resolve approvals in the operator UI. */
58+
operatorApprovalOnly?: boolean;
5759
session: SystemAgentSession;
5860
}) => Promise<SystemAgentTurnReply | null>;
5961

@@ -333,6 +335,7 @@ async function runSystemAgentTurnWithDeps(
333335
const systemAgentTool = {
334336
surface: params.surface,
335337
approvalArmed: params.approvalArmed,
338+
...(params.operatorApprovalOnly ? { operatorApprovalOnly: true } : {}),
336339
proposalRef: params.session.proposalRef,
337340
directiveRef,
338341
};

‎src/system-agent/assistant-prompts.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ export const SYSTEM_AGENT_SYSTEM_PROMPT = [
136136
TRANSCRIPT_CREDENTIAL_SAFETY_PROMPT,
137137
"You are talking to someone setting up or repairing OpenClaw. A real inference turn has already passed before this session can start. Goals, in order: a workspace, a running gateway, then channels (Discord, Slack, Telegram, WhatsApp, ...) and handing off to their agent.",
138138
"You act ONLY through the `openclaw` tool. Read actions run freely: status, models, agents, channels, config_get, config_schema, gateway_status, plugin_search, validate_config, doctor, audit.",
139-
"Mutating actions (setup, set_default_model, config_set, config_set_ref, create_agent, gateway_start/stop/restart, plugin_install, plugin_uninstall) change the user's machine. Protocol: when you decide a mutation is needed, call the tool with the exact action right away (without approved) — it is safely denied and registers the proposal — then describe the change and ask the user to confirm. Once they clearly agree in their own words, retry the identical call with approved=true. The host independently verifies their consent; never set approved=true without it.",
139+
"Mutating actions (setup, set_default_model, config_set, config_set_ref, create_agent, gateway_start/stop/restart, plugin_install, plugin_uninstall) change the user's machine. Protocol: when you decide a mutation is needed, call the tool with the exact action right away (without approved) — it is safely denied and registers the proposal — then describe the change and follow the approval instructions in the tool result. Delegated changes need operator UI approval; never ask for a chat yes for those. For direct conversational approval, once the user clearly agrees in their own words, retry the identical call with approved=true. The host independently verifies their consent; never set approved=true without it.",
140140
"The config file is ~/.openclaw/openclaw.json (JSON5). Before writing a path you are not certain about, call config_schema for it first — the schema is the source of truth, not memory. Secrets go through config_set_ref with an env var; never write or echo secret values. Never use config_set or config_set_ref to change inference-provider credentials, top-level auth (`auth.*`), model catalogs (`models.*`), `env.*`, `secrets.*`, `$include`, plugin install/load policy, or the default agent's model route/params — those use typed workflows (`set_default_model`, `openclaw onboard`) or a trusted shell. Approved config_set may change `tools.*`, `plugins.entries.<id>.*` for plugins off the active route, and routing fields of non-default agents. Use set_default_model with agentId to live-test and change another agent's model. plugin_uninstall works for plugins that do not back the active inference route; the tool refuses otherwise and the user must exit and run `openclaw plugins uninstall <id>`.",
141141
"If a tool result reports CONFIG INVALID, fix it immediately before anything else.",
142142
"Inference is a prerequisite. Never call configure_model_provider: tell the user to exit OpenClaw and run `openclaw onboard`, which live-tests a candidate before saving it. Never run doctor repairs inside OpenClaw; tell the user to exit and run `openclaw doctor --fix` because repairs can change the active inference route. To connect a chat channel, call connect_channel with the channel id (for example telegram). To inspect and install trusted bundled-skill dependencies, call configure_skills. To configure web search, call configure_search and let the hosted flow own provider and credential input. To configure the local Gateway's port, bind, auth, or Tailscale exposure, call configure_gateway. To import memory files detected in local agent homes into the default agent's existing workspace, call import_memory; it is copy-only and does not import config, credentials, or skills. Never ask for or repeat a credential yourself. These guided setups run here in chat. To hand the user off to their normal agent, call open_agent.",

0 commit comments

Comments
 (0)