Skip to content

Commit 4a66667

Browse files
authored
fix(moonshot): rewrite duplicate native Kimi tool call ids
Preserve the first native Kimi tool-call ID while rewriting repeated replay occurrences to deterministic OpenAI-style IDs and keeping paired tool results aligned. Moonshot responses-family behavior and providers that do not opt in remain unchanged. Closes #51593 Co-authored-by: Pluviobyte <[email protected]>
1 parent 68222ba commit 4a66667

16 files changed

Lines changed: 156 additions & 16 deletions

File tree

‎docs/providers/moonshot.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -373,7 +373,7 @@ Config lives under `plugins.entries.moonshot.config.webSearch`:
373373
</Accordion>
374374

375375
<Accordion title="Tool call id sanitization">
376-
Moonshot Kimi serves tool_call ids shaped like `functions.<name>:<index>`. OpenClaw preserves them unchanged so multi-turn tool calls keep working.
376+
Moonshot Kimi serves native tool_call ids shaped like `functions.<name>:<index>`. For the OpenAI-completions transport, OpenClaw preserves the first occurrence of each native Kimi id and rewrites later duplicates to deterministic OpenAI-style `call_*` ids. Matching tool results are remapped with the same id so replay remains unique without stripping Kimi's first native id.
377377

378378
To force strict sanitization on a custom OpenAI-compatible provider, set `sanitizeToolCallIds: true`:
379379

‎extensions/moonshot/index.test.ts‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ describe("moonshot provider plugin", () => {
4444
});
4545
});
4646

47-
it("owns replay policy for OpenAI-compatible Moonshot transports without mangling native Kimi tool_call IDs", async () => {
47+
it("rewrites duplicate tool-call ids with OpenAI-style ids for Moonshot replay", async () => {
4848
const provider = await registerSingleProviderPlugin(plugin);
4949

5050
const policy = provider.buildReplayPolicy?.({
@@ -57,10 +57,28 @@ describe("moonshot provider plugin", () => {
5757
applyAssistantFirstOrderingFix: true,
5858
validateGeminiTurns: true,
5959
validateAnthropicTurns: true,
60+
sanitizeToolCallIds: true,
61+
toolCallIdMode: "strict",
62+
duplicateToolCallIdStyle: "openai",
6063
});
6164
expect(policy).not.toHaveProperty("dropReasoningFromHistory");
62-
expect(policy).not.toHaveProperty("sanitizeToolCallIds");
63-
expect(policy).not.toHaveProperty("toolCallIdMode");
65+
});
66+
67+
it("preserves responses-family replay behavior", async () => {
68+
const provider = await registerSingleProviderPlugin(plugin);
69+
70+
const policy = provider.buildReplayPolicy?.({
71+
provider: "moonshot",
72+
modelApi: "openai-responses",
73+
modelId: "kimi-k2.6",
74+
} as never);
75+
76+
expect(policy).toEqual({
77+
applyAssistantFirstOrderingFix: false,
78+
validateGeminiTurns: false,
79+
validateAnthropicTurns: false,
80+
allowSyntheticToolResults: true,
81+
});
6482
});
6583

6684
it("wires moonshot-thinking stream hooks", async () => {

‎extensions/moonshot/index.ts‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Moonshot plugin entrypoint registers its OpenClaw integration.
22
import { defineSingleProviderPluginEntry } from "openclaw/plugin-sdk/provider-entry";
3-
import { buildProviderReplayFamilyHooks } from "openclaw/plugin-sdk/provider-model-shared";
3+
import { buildOpenAICompatibleReplayPolicy } from "openclaw/plugin-sdk/provider-model-shared";
44
import { MOONSHOT_THINKING_STREAM_HOOKS } from "openclaw/plugin-sdk/provider-stream-family";
55
import { applyMoonshotNativeStreamingUsageCompat } from "./api.js";
66
import { moonshotMediaUnderstandingProvider } from "./media-understanding-provider.js";
@@ -61,14 +61,13 @@ export default defineSingleProviderPluginEntry({
6161
},
6262
applyNativeStreamingUsageCompat: ({ providerConfig }) =>
6363
applyMoonshotNativeStreamingUsageCompat(providerConfig),
64-
// Kimi K2+ returns native tool_call IDs shaped like `functions.<name>:<index>`.
65-
// Sanitizing them to alphanumeric-only breaks Kimi's serving-layer matching in
66-
// multi-turn replay. See openclaw/openclaw#62319.
67-
...buildProviderReplayFamilyHooks({
68-
family: "openai-compatible",
69-
sanitizeToolCallIds: false,
70-
dropReasoningFromHistory: false,
71-
}),
64+
buildReplayPolicy: ({ modelApi, modelId }) =>
65+
buildOpenAICompatibleReplayPolicy(modelApi, {
66+
modelId,
67+
sanitizeToolCallIds: modelApi === "openai-completions",
68+
duplicateToolCallIdStyle: "openai",
69+
dropReasoningFromHistory: false,
70+
}),
7271
...moonshotThinkingStreamHooks,
7372
wrapSimpleCompletionStreamFn: (ctx) =>
7473
ctx.modelId.trim().toLowerCase() === KIMI_K2_7_CODE_MODEL_ID

‎src/agents/embedded-agent-helpers/images.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ export async function sanitizeSessionMessagesImages(
6262
sanitizeMode?: "full" | "images-only";
6363
sanitizeToolCallIds?: boolean;
6464
preserveNativeAnthropicToolUseIds?: boolean;
65+
duplicateToolCallIdStyle?: "openai";
6566
/**
6667
* Mode for tool call ID sanitization:
6768
* - "strict" (alphanumeric only)
@@ -87,6 +88,7 @@ export async function sanitizeSessionMessagesImages(
8788
const sanitizedIds = shouldSanitizeToolCallIds
8889
? sanitizeToolCallIdsForCloudCodeAssist(messages, options.toolCallIdMode, {
8990
preserveNativeAnthropicToolUseIds: options?.preserveNativeAnthropicToolUseIds,
91+
duplicateToolCallIdStyle: options?.duplicateToolCallIdStyle,
9092
})
9193
: messages;
9294
const out: AgentMessage[] = [];

‎src/agents/embedded-agent-runner/replay-history.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -705,6 +705,7 @@ export async function sanitizeSessionHistory(params: {
705705
sanitizeToolCallIds:
706706
policy.sanitizeToolCallIds && !allowProviderOwnedThinkingReplay && !isOpenAIResponsesApi,
707707
toolCallIdMode: policy.toolCallIdMode,
708+
duplicateToolCallIdStyle: policy.duplicateToolCallIdStyle,
708709
preserveNativeAnthropicToolUseIds: policy.preserveNativeAnthropicToolUseIds,
709710
preserveSignatures: policy.preserveSignatures,
710711
sanitizeThoughtSignatures: policy.sanitizeThoughtSignatures,
@@ -769,6 +770,7 @@ export async function sanitizeSessionHistory(params: {
769770
policy.sanitizeToolCallIds && policy.toolCallIdMode
770771
? sanitizeToolCallIdsForCloudCodeAssist(openAISafeToolCalls, policy.toolCallIdMode, {
771772
preserveNativeAnthropicToolUseIds: policy.preserveNativeAnthropicToolUseIds,
773+
duplicateToolCallIdStyle: policy.duplicateToolCallIdStyle,
772774
preserveReplaySafeThinkingToolCallIds: allowProviderOwnedThinkingReplay,
773775
allowedToolNames: params.allowedToolNames,
774776
})

‎src/agents/embedded-agent-runner/run/attempt.tool-call-normalization.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1159,11 +1159,13 @@ export function sanitizeReplayToolCallIdsForStream(params: {
11591159
mode: ToolCallIdMode;
11601160
allowedToolNames?: Set<string>;
11611161
preserveNativeAnthropicToolUseIds?: boolean;
1162+
duplicateToolCallIdStyle?: "openai";
11621163
preserveReplaySafeThinkingToolCallIds?: boolean;
11631164
repairToolUseResultPairing?: boolean;
11641165
}): AgentMessage[] {
11651166
const sanitized = sanitizeToolCallIdsForCloudCodeAssist(params.messages, params.mode, {
11661167
preserveNativeAnthropicToolUseIds: params.preserveNativeAnthropicToolUseIds,
1168+
duplicateToolCallIdStyle: params.duplicateToolCallIdStyle,
11671169
preserveReplaySafeThinkingToolCallIds: params.preserveReplaySafeThinkingToolCallIds,
11681170
allowedToolNames: params.allowedToolNames,
11691171
});

‎src/agents/embedded-agent-runner/run/attempt.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2794,6 +2794,7 @@ export async function runEmbeddedAttempt(
27942794
mode,
27952795
allowedToolNames: replayAllowedToolNames,
27962796
preserveNativeAnthropicToolUseIds: transcriptPolicy.preserveNativeAnthropicToolUseIds,
2797+
duplicateToolCallIdStyle: transcriptPolicy.duplicateToolCallIdStyle,
27972798
preserveReplaySafeThinkingToolCallIds: shouldAllowProviderOwnedThinkingReplay({
27982799
modelApi: (model as { api?: unknown })?.api as string | null | undefined,
27992800
provider: params.provider,

‎src/agents/runtime-plan/types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,7 @@ export type AgentRuntimeTranscriptPolicy = {
299299
sanitizeMode: "full" | "images-only";
300300
sanitizeToolCallIds: boolean;
301301
toolCallIdMode?: AgentRuntimeToolCallIdMode;
302+
duplicateToolCallIdStyle?: "openai";
302303
preserveNativeAnthropicToolUseIds: boolean;
303304
repairToolUseResultPairing: boolean;
304305
preserveSignatures: boolean;

‎src/agents/tool-call-id.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -536,6 +536,36 @@ describe("sanitizeToolCallIdsForCloudCodeAssist", () => {
536536
expect((out[3] as Extract<AgentMessage, { role: "toolResult" }>).toolCallId).toBe(second.id);
537537
});
538538

539+
it("uses OpenAI-style ids for repeated native Kimi ids when requested", () => {
540+
const input = castAgentMessages([
541+
{
542+
role: "assistant",
543+
content: [{ type: "toolCall", id: "functions.read:0", name: "read", arguments: {} }],
544+
},
545+
buildToolResult({ toolCallId: "functions.read:0", text: "one" }),
546+
{
547+
role: "assistant",
548+
content: [{ type: "toolCall", id: "functions.read:0", name: "read", arguments: {} }],
549+
},
550+
buildToolResult({ toolCallId: "functions.read:0", text: "two" }),
551+
]);
552+
const options = { duplicateToolCallIdStyle: "openai" as const };
553+
554+
const out = sanitizeToolCallIdsForCloudCodeAssist(input, "strict", options);
555+
const firstContent = (out[0] as Extract<AgentMessage, { role: "assistant" }>).content;
556+
const secondContent = (out[2] as Extract<AgentMessage, { role: "assistant" }>).content;
557+
if (!Array.isArray(firstContent) || !Array.isArray(secondContent)) {
558+
throw new Error("Expected assistant tool-call content");
559+
}
560+
const firstId = (firstContent[0] as { id?: string }).id;
561+
const secondId = (secondContent[0] as { id?: string }).id;
562+
expect(firstId).toBe("functions.read:0");
563+
expect(secondId).toMatch(/^call_[a-f0-9]{24}$/);
564+
expect((out[1] as Extract<AgentMessage, { role: "toolResult" }>).toolCallId).toBe(firstId);
565+
expect((out[3] as Extract<AgentMessage, { role: "toolResult" }>).toolCallId).toBe(secondId);
566+
expect(sanitizeToolCallIdsForCloudCodeAssist(out, "strict", options)).toBe(out);
567+
});
568+
539569
it("does not preserve malformed Kimi-like ids", () => {
540570
for (const bad of [
541571
"functions.read",

‎src/agents/tool-call-id.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { isAllowedToolCallName, normalizeAllowedToolNames } from "./tool-call-sh
1010
export type ToolCallIdMode = "strict" | "strict9";
1111
const NATIVE_ANTHROPIC_TOOL_USE_ID_RE = /^toolu_[A-Za-z0-9_]+$/;
1212
const NATIVE_KIMI_TOOL_CALL_ID_RE = /^functions\.[A-Za-z0-9_-]+:\d+$/;
13+
const OPENAI_TOOL_CALL_ID_RE = /^call_[A-Za-z0-9_-]+$/;
1314

1415
const STRICT9_LEN = 9;
1516
const TOOL_CALL_TYPES = new Set(["toolCall", "toolUse", "functionCall"]);
@@ -286,6 +287,7 @@ function createOccurrenceAwareResolver(
286287
mode: ToolCallIdMode,
287288
options?: {
288289
preserveNativeAnthropicToolUseIds?: boolean;
290+
duplicateToolCallIdStyle?: "openai";
289291
reservedIds?: Iterable<string>;
290292
},
291293
): {
@@ -298,14 +300,34 @@ function createOccurrenceAwareResolver(
298300
const orphanToolResultOccurrences = new Map<string, number>();
299301
const pendingByRawId = new Map<string, string[]>();
300302
const preserveNativeAnthropicToolUseIds = options?.preserveNativeAnthropicToolUseIds === true;
303+
const duplicateToolCallIdStyle = options?.duplicateToolCallIdStyle;
301304

302305
const allocate = (seed: string): string => {
303306
const next = makeUniqueToolId({ id: seed, used, mode });
304307
used.add(next);
305308
return next;
306309
};
307310

311+
const allocateOpenAIStyleId = (id: string, occurrence: number): string => {
312+
for (let attempt = 0; ; attempt += 1) {
313+
const candidate = `call_${shortHash(`${id}:${occurrence}:${attempt}`, 24)}`;
314+
if (!used.has(candidate)) {
315+
used.add(candidate);
316+
return candidate;
317+
}
318+
}
319+
};
320+
308321
const allocatePreservingNativeAnthropicId = (id: string, occurrence: number): string => {
322+
if (
323+
duplicateToolCallIdStyle === "openai" &&
324+
occurrence === 1 &&
325+
OPENAI_TOOL_CALL_ID_RE.test(id) &&
326+
!used.has(id)
327+
) {
328+
used.add(id);
329+
return id;
330+
}
309331
if (
310332
preserveNativeAnthropicToolUseIds &&
311333
isNativeAnthropicToolUseId(id) &&
@@ -321,7 +343,10 @@ function createOccurrenceAwareResolver(
321343
const resolveAssistantId = (id: string): string => {
322344
const occurrence = (assistantOccurrences.get(id) ?? 0) + 1;
323345
assistantOccurrences.set(id, occurrence);
324-
const next = allocatePreservingNativeAnthropicId(id, occurrence);
346+
const next =
347+
duplicateToolCallIdStyle === "openai" && occurrence > 1
348+
? allocateOpenAIStyleId(id, occurrence)
349+
: allocatePreservingNativeAnthropicId(id, occurrence);
325350
const pending = pendingByRawId.get(id);
326351
if (pending) {
327352
pending.push(next);
@@ -442,12 +467,14 @@ function rewriteToolResultIds(params: {
442467
*
443468
* @param messages - The messages to sanitize
444469
* @param mode - "strict" (alphanumeric only) or "strict9" (alphanumeric length 9)
470+
* @param options.duplicateToolCallIdStyle - Optional provider-safe style for repeated IDs
445471
*/
446472
export function sanitizeToolCallIdsForCloudCodeAssist(
447473
messages: AgentMessage[],
448474
mode: ToolCallIdMode = "strict",
449475
options?: {
450476
preserveNativeAnthropicToolUseIds?: boolean;
477+
duplicateToolCallIdStyle?: "openai";
451478
preserveReplaySafeThinkingToolCallIds?: boolean;
452479
allowedToolNames?: Iterable<string>;
453480
},

0 commit comments

Comments
 (0)