Skip to content

Commit d954a46

Browse files
committed
fix(agents): preserve prompt caches across tool discovery
1 parent 6f8a671 commit d954a46

28 files changed

Lines changed: 750 additions & 661 deletions

‎docs/tools/tool-search.md‎

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -58,12 +58,12 @@ run:
5858
2. List eligible OpenClaw and plugin tools.
5959
3. List eligible MCP tools through the session MCP runtime.
6060
4. Add eligible client tools supplied for the current run.
61-
5. Keep direct-only tools model-visible and index compact descriptors for the
62-
remaining catalog-eligible tools.
61+
5. Keep core coding primitives and direct-only tools model-visible and index
62+
compact descriptors for the remaining catalog-eligible tools.
6363
6. Add a deterministic, bounded, policy-filtered capability directory to the
6464
cache-stable system-prompt prefix.
6565
7. Expose the OpenClaw code bridge, the structured fallback tools, or the
66-
compact directory surface alongside those direct-only tools.
66+
compact directory surface alongside those stable, directly callable tools.
6767

6868
At execution time every real tool call returns to OpenClaw. The isolated Node
6969
runtime does not hold plugin implementations, MCP client objects, or secrets.
@@ -80,9 +80,9 @@ normal policy, approval, hook, logging, and result handling still apply.
8080
structured tools for providers that should not receive code, alongside the
8181
capability directory and direct-only tools.
8282
- `directory`: exposes `tool_search`, `tool_describe`, and `tool_call` plus a
83-
bounded prompt directory. Unlike the other modes, OpenClaw can also expose a
84-
small bounded set of likely or required tool schemas directly for the
85-
current turn. Direct-only tools remain visible in this mode too.
83+
bounded, cache-stable prompt directory. Core coding primitives, direct-only
84+
tools, and tools required by the run's delivery policy remain visible; other
85+
schemas stay deferred.
8686

8787
All modes use the same policy-filtered catalog and normal OpenClaw execution
8888
path. Tools marked `catalogMode: "direct-only"` stay outside that catalog and
@@ -114,8 +114,8 @@ Tool Search changes the shape:
114114
- Tool Search tools mode: the model sees three compact structured fallback
115115
tools, the same capability directory, and any direct-only tools
116116
- Tool Search directory mode: the model sees a bounded directory plus
117-
search/describe/call controls and a small bounded set of likely or required
118-
schemas, plus any direct-only tools
117+
search/describe/call controls, policy-required direct tools, and any
118+
direct-only tools
119119
- during the turn: the model can load remaining schemas as needed
120120

121121
Direct tool exposure is still the right default for small catalogs. Tool Search
@@ -220,12 +220,14 @@ Directory mode exposes:
220220
- `tool_describe`
221221
- `tool_call`
222222

223-
It also keeps client-provided tools and all direct-only tools directly visible,
224-
and may expose a small bounded set of likely or required catalog tool schemas
225-
directly for the current turn. If the bounded directory omits entries, use
226-
`tool_search` to find them. If the model requests an exact hidden directory
227-
tool name directly, OpenClaw hydrates it from the authorized catalog before
228-
normal execution.
223+
It also keeps core file and shell primitives, client-provided tools, direct-only
224+
tools, and policy-required delivery tools directly visible. Other authorized
225+
tool schemas stay deferred rather than changing with each user prompt. MCP tools
226+
cannot impersonate a directly visible core or policy-required delivery tool. If
227+
the bounded directory omits entries, use `tool_search` to find them and
228+
`tool_describe` to retrieve their full schemas. If the model requests an exact
229+
hidden directory tool name directly, OpenClaw resolves it from the authorized
230+
catalog before normal execution.
229231
Directory-mode client tool names must not collide with OpenClaw, plugin, or MCP
230232
tool names because exact deferred dispatch uses those names.
231233

‎extensions/google/transport-stream.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2218,6 +2218,39 @@ describe("google transport stream", () => {
22182218
});
22192219
});
22202220

2221+
it("keeps Gemini function declaration bytes stable across discovery orders", () => {
2222+
const tools = [
2223+
{
2224+
name: "zeta_lookup",
2225+
description: "Look up the last value",
2226+
parameters: { type: "object", properties: { value: { type: "string" } } },
2227+
},
2228+
{
2229+
name: "alpha_lookup",
2230+
description: "Look up the first value",
2231+
parameters: { type: "object", properties: { query: { type: "string" } } },
2232+
},
2233+
];
2234+
const buildParams = (orderedTools: typeof tools) =>
2235+
buildGoogleGenerativeAiParams(buildGeminiModel(), {
2236+
messages: [{ role: "user", content: "hello", timestamp: 0 }],
2237+
tools: orderedTools,
2238+
} as never);
2239+
2240+
const first = buildParams(tools);
2241+
const reversed = buildParams(tools.toReversed());
2242+
2243+
expect(reversed.tools).toEqual(first.tools);
2244+
expect(first.tools).toEqual([
2245+
{
2246+
functionDeclarations: [
2247+
expect.objectContaining({ name: "alpha_lookup" }),
2248+
expect.objectContaining({ name: "zeta_lookup" }),
2249+
],
2250+
},
2251+
]);
2252+
});
2253+
22212254
it("includes cachedContent in direct Gemini payloads when requested", () => {
22222255
const params = buildGoogleGenerativeAiParams(
22232256
buildGeminiModel(),

‎extensions/google/transport-stream.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import {
2929
finalizeTransportStream,
3030
mergeTransportHeaders,
3131
sanitizeTransportPayloadText,
32+
sortPromptCacheToolsByName,
3233
stripSystemPromptCacheBoundary,
3334
transformTransportMessages,
3435
type WritableTransportStream,
@@ -709,7 +710,7 @@ function convertGoogleTools(tools: NonNullable<Context["tools"]>) {
709710
}
710711
return [
711712
{
712-
functionDeclarations: tools.map((tool) => ({
713+
functionDeclarations: sortPromptCacheToolsByName(tools).map((tool) => ({
713714
name: tool.name,
714715
description: tool.description,
715716
parametersJsonSchema: tool.parameters,

‎packages/ai/src/providers/anthropic-tool-projection.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,28 @@ import { describe, expect, it } from "vitest";
22
import { projectAnthropicTools } from "./anthropic-tool-projection.js";
33

44
describe("projectAnthropicTools", () => {
5+
it("keeps projected wire tools identical across discovery orders", () => {
6+
const tools = [
7+
{
8+
name: "ZuluLookup",
9+
description: "Look up the last value",
10+
parameters: { type: "object", properties: { value: { type: "string" } } },
11+
},
12+
{
13+
name: "AlphaLookup",
14+
description: "Look up the first value",
15+
parameters: { type: "object", properties: { query: { type: "string" } } },
16+
},
17+
];
18+
const toWireName = (name: string) => name.toLowerCase();
19+
20+
const first = projectAnthropicTools(tools, toWireName);
21+
const reversed = projectAnthropicTools(tools.toReversed(), toWireName);
22+
23+
expect(first.tools.map((tool) => tool.wireName)).toEqual(["alphalookup", "zululookup"]);
24+
expect(reversed.tools).toEqual(first.tools);
25+
});
26+
527
it("converts draft-07 tuple items to draft 2020-12 prefixItems for Anthropic", () => {
628
const projection = projectAnthropicTools(
729
[

‎packages/ai/src/providers/anthropic-tool-projection.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { isRecord } from "@openclaw/normalization-core/record-coerce";
2+
import { sortPromptCacheToolsByName } from "../utils/prompt-cache-stability.js";
23
import { projectRuntimeToolInputSchema } from "./tool-schema-json-projection.js";
34

45
type AnthropicToolDescriptor = {
@@ -187,7 +188,9 @@ export function projectAnthropicTools(
187188
return {
188189
inputToolCount: tools.length,
189190
unavailableOriginalNames,
190-
tools: projectedTools,
191+
// Anthropic caches through the last wire tool, so discovery order must not
192+
// move the cache breakpoint or change otherwise identical request bytes.
193+
tools: sortPromptCacheToolsByName(projectedTools),
191194
};
192195
}
193196

‎packages/ai/src/providers/anthropic.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2367,6 +2367,54 @@ describe("Anthropic provider", () => {
23672367
expect(onPayload).not.toHaveBeenCalled();
23682368
});
23692369

2370+
it("keeps Anthropic wire tool bytes and their cache breakpoint stable across discovery orders", async () => {
2371+
const tools = [
2372+
{
2373+
name: "zeta_lookup",
2374+
description: "Look up the last value",
2375+
parameters: { type: "object", properties: { value: { type: "string" } } },
2376+
},
2377+
{
2378+
name: "alpha_lookup",
2379+
description: "Look up the first value",
2380+
parameters: { type: "object", properties: { query: { type: "string" } } },
2381+
},
2382+
] as Tool[];
2383+
const captureTools = async (orderedTools: Tool[]) => {
2384+
let capturedPayload: unknown;
2385+
const stream = streamSimpleAnthropic(
2386+
makeAnthropicModel(),
2387+
{
2388+
systemPrompt: "stable system",
2389+
messages: [{ role: "user", content: "hello", timestamp: 0 }],
2390+
tools: orderedTools,
2391+
},
2392+
{
2393+
apiKey: "sk-ant-provider",
2394+
onPayload: (payload) => {
2395+
capturedPayload = payload;
2396+
throw new Error("stop before network");
2397+
},
2398+
},
2399+
);
2400+
await stream.result();
2401+
return (capturedPayload as { tools: unknown[] }).tools;
2402+
};
2403+
2404+
const first = await captureTools(tools);
2405+
const reversed = await captureTools(tools.toReversed());
2406+
2407+
expect(reversed).toEqual(first);
2408+
expect(first).toEqual([
2409+
expect.objectContaining({ name: "alpha_lookup" }),
2410+
expect.objectContaining({
2411+
name: "zeta_lookup",
2412+
cache_control: { type: "ephemeral" },
2413+
}),
2414+
]);
2415+
expect(first[0]).not.toHaveProperty("cache_control");
2416+
});
2417+
23702418
it("splits the system prompt cache boundary into cached and uncached Anthropic blocks", async () => {
23712419
let capturedPayload: unknown;
23722420
const stream = streamSimpleAnthropic(

‎packages/ai/src/providers/openai-responses-tools.ts‎

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
33
import type { Tool as OpenAITool } from "openai/resources/responses/responses.js";
44
import { getAiTransportHost } from "../host.js";
55
import type { Model, Tool } from "../types.js";
6+
import { sortPromptCacheToolsByName } from "../utils/prompt-cache-stability.js";
67
import { projectOpenAITools, type OpenAIToolProjection } from "./openai-tool-projection.js";
78
import {
89
findOpenAIStrictToolProjectionDiagnostics,
@@ -45,7 +46,7 @@ export function convertResponsesToolPayload(
4546
const strictSetting = resolveResponsesStrictToolSetting(options);
4647
const strict = resolveResponsesStrictToolFlag(projection, strictSetting, options?.model);
4748
// Sort tools before request construction so prompt-cache bytes stay deterministic.
48-
const convertedTools = sortResponsesToolsByName(projection.tools).map((tool) => {
49+
const convertedTools = sortPromptCacheToolsByName(projection.tools).map((tool) => {
4950
const result: ResponsesFunctionTool = {
5051
type: "function",
5152
name: tool.name,
@@ -139,25 +140,3 @@ function shouldLogStrictToolDowngradeDiagnostic(
139140
loggedStrictToolDowngradeDiagnosticKeys.add(key);
140141
return true;
141142
}
142-
143-
function compareToolText(left: string | undefined, right: string | undefined): number {
144-
const leftText = left ?? "";
145-
const rightText = right ?? "";
146-
if (leftText < rightText) {
147-
return -1;
148-
}
149-
if (leftText > rightText) {
150-
return 1;
151-
}
152-
return 0;
153-
}
154-
155-
function sortResponsesToolsByName<T extends { name?: string; description?: string }>(
156-
tools: readonly T[],
157-
): T[] {
158-
return tools.toSorted(
159-
(left, right) =>
160-
compareToolText(left.name, right.name) ||
161-
compareToolText(left.description, right.description),
162-
);
163-
}

‎packages/ai/src/transports/openai-transport-shared.ts‎

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import {
88
} from "../internal/openai.js";
99
import { transportAbortError } from "./transport-stream-shared.js";
1010

11+
export { sortPromptCacheToolsByName as sortTransportToolsByName } from "../utils/prompt-cache-stability.js";
12+
1113
const MODEL_STREAM_COOPERATIVE_YIELD_INTERVAL_MS = 12;
1214
const MODEL_STREAM_COOPERATIVE_YIELD_MAX_EVENTS = 64;
1315

@@ -146,25 +148,3 @@ export function resolvePromptCacheKey(
146148
}
147149
return clampOpenAIPromptCacheKey(options?.promptCacheKey ?? options?.sessionId);
148150
}
149-
150-
function compareTransportToolText(left: string | undefined, right: string | undefined): number {
151-
const leftText = left ?? "";
152-
const rightText = right ?? "";
153-
if (leftText < rightText) {
154-
return -1;
155-
}
156-
if (leftText > rightText) {
157-
return 1;
158-
}
159-
return 0;
160-
}
161-
162-
export function sortTransportToolsByName<T extends { name?: string; description?: string }>(
163-
tools: readonly T[],
164-
): T[] {
165-
return tools.toSorted(
166-
(left, right) =>
167-
compareTransportToolText(left.name, right.name) ||
168-
compareTransportToolText(left.description, right.description),
169-
);
170-
}

‎packages/ai/src/utils/prompt-cache-stability.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,26 @@
66
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
77
import { sanitizeSurrogates } from "./sanitize-unicode.js";
88

9+
/** Canonicalizes provider tool order without relying on host locale settings. */
10+
export function sortPromptCacheToolsByName<
11+
T extends {
12+
readonly name?: string;
13+
readonly wireName?: string;
14+
readonly description?: string;
15+
},
16+
>(tools: readonly T[]): T[] {
17+
const compareText = (left: string | undefined, right: string | undefined): number => {
18+
const leftText = left ?? "";
19+
const rightText = right ?? "";
20+
return leftText < rightText ? -1 : leftText > rightText ? 1 : 0;
21+
};
22+
return tools.toSorted(
23+
(left, right) =>
24+
compareText(left.wireName ?? left.name, right.wireName ?? right.name) ||
25+
compareText(left.description, right.description),
26+
);
27+
}
28+
929
/** Normalize structured prompt text before hashing or snapshot comparison. */
1030
export function normalizeStructuredPromptSection(text: string): string {
1131
return sanitizeSurrogates(text)

‎src/agents/embedded-agent-runner/google-prompt-cache.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,56 @@ describe("google prompt cache", () => {
357357
]);
358358
});
359359

360+
it("reuses managed cached content when tool discovery order changes", async () => {
361+
const now = 1_000_000;
362+
const entries: SessionCustomEntry[] = [];
363+
const sessionManager = makeSessionManager(entries);
364+
const fetchMock = createCacheFetchMock({
365+
name: "cachedContents/stable-tool-order",
366+
expireTime: new Date(now + 3_600_000).toISOString(),
367+
});
368+
const { streamFn, getCapturedPayload } = createCapturingStreamFn();
369+
const wrapped = await preparePromptCacheStream({
370+
fetchMock,
371+
now,
372+
sessionManager,
373+
streamFn,
374+
});
375+
const tools = [
376+
{
377+
name: "zeta_lookup",
378+
description: "Look up the last value",
379+
parameters: { type: "object", properties: { value: { type: "string" } } },
380+
},
381+
{
382+
name: "alpha_lookup",
383+
description: "Look up the first value",
384+
parameters: { type: "object", properties: { query: { type: "string" } } },
385+
},
386+
];
387+
388+
for (const orderedTools of [tools, tools.toReversed()]) {
389+
await Promise.resolve(
390+
wrapped?.(
391+
makeGoogleModel(),
392+
{ systemPrompt: "Follow policy.", messages: [], tools: orderedTools } as never,
393+
{ toolChoice: "auto" } as never,
394+
),
395+
);
396+
expect(getCapturedPayload()?.cachedContent).toBe("cachedContents/stable-tool-order");
397+
}
398+
399+
expect(fetchMock).toHaveBeenCalledTimes(1);
400+
expect(entries).toHaveLength(1);
401+
const createBody = JSON.parse(fetchInit(fetchMock).body as string) as {
402+
tools: Array<{ functionDeclarations: Array<{ name: string }> }>;
403+
};
404+
expect(createBody.tools[0]?.functionDeclarations.map((tool) => tool.name)).toEqual([
405+
"alpha_lookup",
406+
"zeta_lookup",
407+
]);
408+
});
409+
360410
it("cancels failed cache creation response bodies", async () => {
361411
const now = 1_500_000;
362412
const response = new Response("permission denied", { status: 403 });

0 commit comments

Comments
 (0)