Skip to content

Commit 4249df3

Browse files
authored
improve(code-mode): call tools as global functions (#126262)
* feat(code-mode): expose tools as global functions * fix(code-mode): harden callable tool composition * fix(code-mode): reserve private guest globals * fix(cron): migrate legacy code-mode triggers * fix(code-mode): align final tool result contracts
1 parent 15f33d9 commit 4249df3

75 files changed

Lines changed: 3322 additions & 1264 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/automation/cron-jobs.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,13 +141,15 @@ An event trigger adds a headless condition script to an `every`, `cron`, or `str
141141
schedule: { kind: "every", everyMs: 30000 },
142142
trigger: {
143143
// Fires only when the observed status differs from the last evaluation.
144-
script: "const res = await tools.call('exec', { command: 'gh pr checks 123 --json state -q \\'.[].state\\' | sort -u' }); const status = String(res?.result?.details?.aggregated ?? '').trim(); json({ fire: status !== trigger.state?.status, message: `PR 123 CI: ${trigger.state?.status ?? 'unknown'} -> ${status}`, state: { status } });",
144+
script: "const res = await exec({ command: 'gh pr checks 123 --json state -q \\'.[].state\\' | sort -u' }); const status = String(res?.aggregated ?? '').trim(); json({ fire: status !== trigger.state?.status, message: `PR 123 CI: ${trigger.state?.status ?? 'unknown'} -> ${status}`, state: { status } });",
145145
once: false,
146146
},
147147
payload: { kind: "agentTurn", message: "Investigate the CI status change." },
148148
}
149149
```
150150

151+
When upgrading, run `openclaw doctor --fix` to migrate persisted trigger scripts that call `tools.call('exec', args)` and read the legacy `.result.details` envelope. Doctor leaves custom or ambiguous legacy scripts unchanged and identifies each affected job for manual conversion; standalone script payloads are not migrated.
152+
151153
The script must return `{ fire, message?, state? }`. The previous JSON state is available as the deeply frozen `trigger.state`; stream gates also receive the current batch as `trigger.streamBatch`. Return a new `state` value to persist it. State is capped at 16 KB. When a firing result includes `message`, the scheduler appends it to the system-event text or agent-turn message before execution. `once: true` disables the job after its first successful fired payload.
152154

153155
`fire: false` persists evaluation state and counters, then reschedules without creating run history. If a fired payload run fails, the returned `state` is **not** persisted — the next evaluation sees the previous state and can fire again, so write scripts as read-only checks and keep actions in the payload. Trigger schedules have a built-in minimum interval of 30 seconds. Each evaluation has a 30-second wall-clock budget and up to 5 tool calls.

‎docs/plugins/tool-plugins.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,8 @@ or sensitive values in schema descriptions because trusted output metadata can
235235
become model-visible.
236236
Use `{ additionalProperties: false }` on object layers when you want a complete
237237
compact output hint; open or truncated schemas remain available through
238-
`tools.describe(...)` but are not advertised as complete quick-index contracts.
238+
the callable catalog handle's `describe()` but are not advertised as complete
239+
quick-index contracts.
239240

240241
Factory tools declare `outputSchema` on the concrete `AnyAgentTool` they
241242
return. The static `tool({ factory })` declaration does not accept a separate

‎docs/tools/code-mode.md‎

Lines changed: 150 additions & 114 deletions
Large diffs are not rendered by default.

‎extensions/qa-lab/src/providers/mock-openai/server.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6893,7 +6893,9 @@ Update and merge these partial structured summaries.`,
68936893
const readAgent = readToolUse(await request());
68946894
expect(readAgent.name).toBe("exec");
68956895
const readAgentCode = String(requireRecord(readAgent.input, "exec input").code);
6896-
expect(readAgentCode).toContain("tools.callValue(target.id, targetArgs)");
6896+
expect(readAgentCode).toContain("await catalog.search(targetName)");
6897+
expect(readAgentCode).toContain("await target(targetArgs)");
6898+
expect(readAgentCode).not.toContain("ALL_TOOLS");
68976899
expect(readAgentCode).toContain("value.content.slice(0, 2048)");
68986900
await expectPlan("read", { path: "AGENT.md" }, String(readAgent.id));
68996901

@@ -7182,6 +7184,8 @@ Update and merge these partial structured summaries.`,
71827184
const execArgs = outputToolArgsFromItem(execCall);
71837185
expect(execArgs).toMatchObject({ language: "javascript", restartSafe: true });
71847186
expect(execArgs.code).toContain("qa_restart_wait");
7187+
expect(execArgs.code).toContain('catalog.search("qa_restart_wait")');
7188+
expect(execArgs.code).toContain("await target({})");
71857189
expect(execArgs.code).toContain(`CHECKPOINT-${checkpoint}`);
71867190

71877191
const runId = `restart-checkpoint-${checkpoint}`;

‎extensions/qa-lab/src/providers/mock-openai/server.ts‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -663,9 +663,9 @@ function buildScenarioToolCallEvents(
663663
`// ${QA_CODE_MODE_TARGET_MARKER}${encodedTarget}`,
664664
`const targetName = ${JSON.stringify(name)};`,
665665
`const targetArgs = ${JSON.stringify(args)};`,
666-
"const target = ALL_TOOLS.find((entry) => entry.name === targetName);",
666+
"const target = (await catalog.search(targetName)).find((entry) => entry.toolName === targetName);",
667667
"if (!target) throw new Error(`QA mock target tool unavailable: ${targetName}`);",
668-
"const value = await tools.callValue(target.id, targetArgs);",
668+
"const value = await target(targetArgs);",
669669
'if (targetName === "read" && value?.kind === "text" && typeof value.content === "string") {',
670670
" return { ...value, content: value.content.slice(0, 2048) };",
671671
"}",
@@ -960,9 +960,9 @@ async function buildResponsesPayload(
960960
restartSafe: true,
961961
code: [
962962
`// ${QA_CODE_MODE_TARGET_MARKER}${encodedTarget}`,
963-
'const target = ALL_TOOLS.find((tool) => tool.name === "qa_restart_wait");',
963+
'const target = (await catalog.search("qa_restart_wait")).find((tool) => tool.toolName === "qa_restart_wait");',
964964
'if (!target) throw new Error("qa_restart_wait unavailable");',
965-
"await tools.call(target.id, {});",
965+
"await target({});",
966966
`return "CHECKPOINT-${nextCheckpoint}";`,
967967
].join("\n"),
968968
});
@@ -1155,17 +1155,24 @@ async function buildResponsesPayload(
11551155
language: "javascript",
11561156
code: useApiFiles
11571157
? [
1158-
'const files = await API.list("mcp");',
1159-
'const root = await API.read("mcp/index.d.ts");',
1160-
'const api = await API.read("mcp/fixture.d.ts");',
1161-
'const result = await MCP.fixture.lookupNote({ id: "alpha" });',
1158+
"const [files, root, api, result, failure, resources, resource, prompts, prompt] = await Promise.all([",
1159+
' API.list("mcp"), API.read("mcp/index.d.ts"), API.read("mcp/fixture.d.ts"),',
1160+
' MCP.fixture.lookupNote({ id: "alpha" }), MCP.fixture.lookupNote({ id: "missing" }),',
1161+
' MCP.fixture.resources.list(), MCP.fixture.resources.read({ uri: "memo://fixture/alpha" }),',
1162+
' MCP.fixture.prompts.list(), MCP.fixture.prompts.get({ name: "fixture_brief", arguments: { id: "alpha" } }),',
1163+
"]);",
1164+
'if (result.structuredContent?.note !== "fixture-note-alpha" || result.isError !== false) throw new Error("MCP success lost its top-level result shape");',
1165+
'if (failure.structuredContent?.note !== "missing-note" || failure.isError !== true) throw new Error("MCP resolved failure lost its top-level result shape");',
1166+
'if (result._meta !== undefined || result.content?.[0]?._meta?.proof !== "fixture-content-metadata") throw new Error("MCP result metadata crossed the wrong boundary");',
1167+
'if (!resources.resources?.some((entry) => entry.uri === "memo://fixture/alpha") || resource.contents?.[0]?.text !== "fixture-note-alpha") throw new Error("MCP resources lost their native result shape");',
1168+
'if (!prompts.prompts?.some((entry) => entry.name === "fixture_brief") || prompt.messages?.[0]?.content?.text !== "fixture-note-alpha") throw new Error("MCP prompts lost their native result shape");',
11621169
"return {",
11631170
' marker: "MCP_CODE_MODE_FILE_TOOL_RESULT",',
11641171
" files: files.files.map((file) => file.path),",
11651172
" rootHasFixture: root.content.includes('fixture'),",
11661173
" headerHasLookup: api.content.includes('function lookupNote'),",
11671174
" resultText: result.content?.[0]?.text,",
1168-
" allHasMcp: ALL_TOOLS.some((tool) => tool.source === 'mcp'),",
1175+
" allHasMcp: catalog.all().some((tool) => tool.source === 'mcp'),",
11691176
"};",
11701177
].join("\n")
11711178
: [
@@ -1178,7 +1185,7 @@ async function buildResponsesPayload(
11781185
" headerHasLookup: api.header.includes('function lookupNote'),",
11791186
" schemaKeys: Object.keys(api.schemas),",
11801187
" resultText: result.content?.[0]?.text,",
1181-
" allHasMcp: ALL_TOOLS.some((tool) => tool.source === 'mcp'),",
1188+
" allHasMcp: catalog.all().some((tool) => tool.source === 'mcp'),",
11821189
"};",
11831190
].join("\n"),
11841191
});

‎scripts/e2e/lib/mcp-code-mode-probe-server.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,37 @@ server.tool(
2929
{
3030
id: z.string().describe("Fixture note id to look up."),
3131
},
32+
async ({ id }) => {
33+
const note = notes.get(id);
34+
return {
35+
content: [{
36+
type: "text",
37+
text: note ?? "missing-note",
38+
annotations: { audience: ["assistant"] },
39+
_meta: { proof: "fixture-content-metadata" },
40+
}],
41+
structuredContent: { id, note: note ?? "missing-note" },
42+
isError: note === undefined,
43+
_meta: { private: "fixture-private-metadata" },
44+
};
45+
},
46+
);
47+
48+
server.registerResource(
49+
"fixture_note",
50+
"memo://fixture/alpha",
51+
{ description: "Fixture alpha note", mimeType: "text/plain" },
52+
async (uri) => ({
53+
contents: [{ uri: uri.href, mimeType: "text/plain", text: notes.get("alpha") }],
54+
}),
55+
);
56+
57+
server.registerPrompt(
58+
"fixture_brief",
59+
{ description: "A fixture note briefing", argsSchema: { id: z.string() } },
3260
async ({ id }) => ({
33-
content: [{ type: "text", text: notes.get(id) ?? "missing-note" }],
61+
description: "A fixture note briefing",
62+
messages: [{ role: "user", content: { type: "text", text: notes.get(id) ?? "missing-note" } }],
3463
}),
3564
);
3665

‎scripts/e2e/lib/mcp-code-mode-validation.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,6 @@ export function validateMcpCodeModeResult(
8383
assert(mentions.mcpNamespace > 0, "session log lacks MCP.fixture usage");
8484
assert(mentions.mcpTool > 0, "session log lacks MCP.fixture.lookupNote call");
8585
assert(mentions.apiCall === 0, "agent should not call MCP.$api when API files are available");
86-
assert(mentions.toolSearchPollution === 0, "agent should not use tools.search for MCP lookup");
86+
assert(mentions.toolSearchPollution === 0, "agent should not use catalog.search for MCP lookup");
8787
return finalText;
8888
}

‎scripts/e2e/mcp-code-mode-gateway-client.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ async function readSessionLogMentions(stateDir: string): Promise<Record<string,
111111
apiFileRead: "API.read",
112112
mcpNamespace: "MCP.fixture",
113113
mcpTool: "MCP.fixture.lookupNote",
114-
toolSearchPollution: 'tools.search("lookup note"',
114+
toolSearchPollution: 'catalog.search("lookup note"',
115115
},
116116
});
117117
}
@@ -152,7 +152,7 @@ async function main() {
152152
'const api = await API.read("mcp/fixture.d.ts");',
153153
'const result = await MCP.fixture.lookupNote({ id: "alpha" });',
154154
'return { marker: "MCP_CODE_MODE_FILE_TOOL_RESULT", files: files.files.map((file) => file.path), rootHasFixture: root.content.includes("fixture"), headerHasLookup: api.content.includes("function lookupNote"), note: result.content?.[0]?.text };',
155-
"Do not use tools.search for MCP and do not call the inline MCP API helper.",
155+
"Do not use catalog.search for MCP and do not call the inline MCP API helper.",
156156
"After exec finishes, send a normal assistant reply; do not stop after only the tool call.",
157157
"Reply with MCP_CODE_MODE_FILE_OK note=fixture-note-alpha unclear=none only after the MCP call returns fixture-note-alpha.",
158158
].join(" "),

‎scripts/e2e/mock-openai-server.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -499,7 +499,7 @@ function mcpCodeModeApiFileEvents(body, bodyText) {
499499
" rootHasFixture: root.content.includes('fixture'),",
500500
" headerHasLookup: api.content.includes('function lookupNote'),",
501501
" resultText: result.content?.[0]?.text,",
502-
" allHasMcp: ALL_TOOLS.some((tool) => tool.source === 'mcp'),",
502+
" allHasMcp: catalog.all().some((tool) => tool.source === 'mcp'),",
503503
"};",
504504
].join("\n"),
505505
});

‎scripts/mcp-code-mode-gateway-e2e.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,8 @@ async function readSessionLogMentions(stateDir: string): Promise<Record<string,
8585
apiFileList: "API.list",
8686
apiFileRead: "API.read",
8787
mcpNamespace: "MCP.fixture",
88-
mcpTool: "fixture__lookup_note",
89-
toolSearchPollution: 'tools.search("lookup note"',
88+
mcpTool: "MCP.fixture.lookupNote",
89+
toolSearchPollution: 'catalog.search("lookup note"',
9090
},
9191
});
9292
}

0 commit comments

Comments
 (0)