Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix(stream): normalize textual passthrough tool calls

OpenClaw5901a272240a
diff --git a/open-sse/utils/stream.ts b/open-sse/utils/stream.ts
index 062cb808bb..ceb9fe560f 100644
--- a/open-sse/utils/stream.ts
+++ b/open-sse/utils/stream.ts
@@ -181,6 +181,60 @@ function appendBoundedText(current: string, next: string): string {
return combined.slice(-STREAM_SUMMARY_TEXT_LIMIT);
}
+function stripZeroWidth(value: unknown): unknown {
+ if (typeof value === "string") {
+ return value.replace(/[\u200B-\u200D\uFEFF]/g, "");
+ }
+ if (Array.isArray(value)) {
+ return value.map((item) => stripZeroWidth(item));
+ }
+ if (value && typeof value === "object") {
+ return Object.fromEntries(
+ Object.entries(value as Record<string, unknown>).map(([key, item]) => [
+ key,
+ stripZeroWidth(item),
+ ])
+ );
+ }
+ return value;
+}
+
+function parseTextualToolCallFromContent(text: unknown): { name: string; args: unknown } | null {
+ if (typeof text !== "string") return null;
+ const normalized = text.replace(/[\u200B-\u200D\uFEFF]/g, "");
+ const match = normalized.match(
+ /^[\s\S]*?\[Tool call:\s*([^\]\n]+)\]\s*\nArguments:\s*([\s\S]+?)\s*$/
+ );
+ if (!match) return null;
+ const name = match[1]?.trim();
+ const rawArgs = match[2]?.trim();
+ if (!name || !rawArgs) return null;
+ try {
+ return { name, args: stripZeroWidth(JSON.parse(rawArgs)) };
+ } catch {
+ return null;
+ }
+}
+
+function collectPassthroughTextualToolCall(
+ text: string,
+ toolCalls: Map<string, ToolCall>
+): boolean {
+ const parsed = parseTextualToolCallFromContent(text);
+ if (!parsed) return false;
+ const key = `textual:${toolCalls.size}`;
+ toolCalls.set(key, {
+ id: `call_${Date.now()}_${toolCalls.size}`,
+ index: toolCalls.size,
+ type: "function",
+ function: {
+ name: parsed.name,
+ arguments: JSON.stringify(parsed.args || {}),
+ },
+ });
+ return true;
+}
+
function toStreamFailureStatus(value: unknown): number | null {
if (typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599) {
return value;
@@ -1211,6 +1265,7 @@ export function createSSEStream(options: StreamOptions = {}) {
}
const delta = parsed.choices?.[0]?.delta;
+ let textualToolCallConverted = false;
// Extract <think> tags from streaming content
if (delta?.content && typeof delta.content === "string") {
@@ -1288,11 +1343,18 @@ export function createSSEStream(options: StreamOptions = {}) {
if (content && typeof content === "string") {
totalContentLength += content.length;
}
- if (typeof delta?.content === "string")
- passthroughAccumulatedContent = appendBoundedText(
- passthroughAccumulatedContent,
- delta.content
- );
+ if (typeof delta?.content === "string") {
+ if (collectPassthroughTextualToolCall(delta.content, passthroughToolCalls)) {
+ passthroughHasToolCalls = true;
+ textualToolCallConverted = true;
+ delta.content = "";
+ } else {
+ passthroughAccumulatedContent = appendBoundedText(
+ passthroughAccumulatedContent,
+ delta.content
+ );
+ }
+ }
if (typeof delta?.reasoning_content === "string")
passthroughAccumulatedReasoning = appendBoundedText(
passthroughAccumulatedReasoning,
@@ -1330,6 +1392,9 @@ export function createSSEStream(options: StreamOptions = {}) {
parsed.usage = filterUsageForFormat(buffered, FORMATS.OPENAI);
output = `data: ${JSON.stringify(parsed)}\n`;
injectedUsage = true;
+ } else if (textualToolCallConverted) {
+ output = `data: ${JSON.stringify(parsed)}\n`;
+ injectedUsage = true;
} else if (idFixed || needsReserialization) {
output = `data: ${JSON.stringify(parsed)}\n`;
injectedUsage = true;
diff --git a/tests/unit/stream-utils.test.ts b/tests/unit/stream-utils.test.ts
index 4c3d902115..418668fab9 100644
--- a/tests/unit/stream-utils.test.ts
+++ b/tests/unit/stream-utils.test.ts
@@ -124,6 +124,55 @@ test("createSSEStream passthrough normalizes tool-call finishes and reports the
assert.equal(onCompletePayload.clientPayload._streamed, true);
});
+test("createSSEStream passthrough converts textual tool-call content into structured call log tool_calls", async () => {
+ let onCompletePayload = null;
+ const toolArgs = JSON.stringify({
+ command: 'sqlite3 /root/.o\u200dmniroute/omniroute.db ".tables"',
+ });
+ const toolText = `[Tool call: terminal]\nArguments: ${toolArgs}`;
+
+ const text = await readTransformed(
+ [
+ `data: ${JSON.stringify({
+ id: "chatcmpl_textual_tool",
+ object: "chat.completion.chunk",
+ created: 1,
+ model: "antigravity/gemini-3.5-flash-low",
+ choices: [{ index: 0, delta: { role: "assistant", content: toolText } }],
+ })}\n\n`,
+ `data: ${JSON.stringify({
+ id: "chatcmpl_textual_tool",
+ object: "chat.completion.chunk",
+ created: 1,
+ model: "antigravity/gemini-3.5-flash-low",
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
+ })}\n\n`,
+ ],
+ {
+ mode: "passthrough",
+ sourceFormat: FORMATS.OPENAI,
+ provider: "antigravity",
+ model: "antigravity/gemini-3.5-flash-low",
+ body: {
+ messages: [{ role: "user", content: "inspect db" }],
+ },
+ onComplete(payload) {
+ onCompletePayload = payload;
+ },
+ }
+ );
+
+ assert.equal(onCompletePayload.status, 200);
+ const choice = onCompletePayload.responseBody.choices[0];
+ assert.equal(choice.finish_reason, "tool_calls");
+ assert.equal(choice.message.content, null);
+ assert.equal(choice.message.tool_calls[0].function.name, "terminal");
+ assert.deepEqual(JSON.parse(choice.message.tool_calls[0].function.arguments), {
+ command: 'sqlite3 /root/.omniroute/omniroute.db ".tables"',
+ });
+ assert.doesNotMatch(text, /\[Tool call: terminal\]/);
+});
+
test("createSSEStream passthrough flushes a buffered final line without a trailing newline", async () => {
const text = await readTransformed(
[