Skip to content

Commit 278f624

Browse files
author
Peter Steinberger
committed
fix(mistral): reject incomplete streamed tool terminals
1 parent a1b41d5 commit 278f624

3 files changed

Lines changed: 219 additions & 7 deletions

File tree

‎packages/ai/src/providers/mistral.bounded-stream.test.ts‎

Lines changed: 195 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
import http from "node:http";
33
import type { AddressInfo } from "node:net";
44
import { describe, expect, it } from "vitest";
5-
import { createBoundedMistralFetcher } from "./mistral.js";
5+
import type { Context, Model } from "../types.js";
6+
import { createBoundedMistralFetcher, streamMistral } from "./mistral.js";
67

78
const MAX = 16 * 1024 * 1024;
89
const TOTAL = 18 * 1024 * 1024;
@@ -166,3 +167,196 @@ describe("Mistral bounded-stream-read direct (synthetic ReadableStream)", () =>
166167
expect(got).toBe(16777216 + CHUNK);
167168
});
168169
});
170+
171+
type MistralTerminalFixture = {
172+
finishReason: "stop" | "length" | "error" | "tool_calls" | null;
173+
done: boolean;
174+
abort?: boolean;
175+
toolArguments?: string[];
176+
text?: string;
177+
};
178+
179+
async function streamMistralTerminalFixture(fixture: MistralTerminalFixture) {
180+
const server = http.createServer((request, response) => {
181+
request.resume();
182+
response.writeHead(200, { "content-type": "text/event-stream" });
183+
const toolCalls = fixture.toolArguments?.map((args, index) => ({
184+
index,
185+
id: `call_${index}`,
186+
type: "function",
187+
function: { name: `tool_${index}`, arguments: args },
188+
}));
189+
response.write(
190+
`data: ${JSON.stringify({
191+
id: "mistral-terminal-owner-proof",
192+
object: "chat.completion.chunk",
193+
created: 1,
194+
model: "mistral-large-latest",
195+
choices: [
196+
{
197+
index: 0,
198+
delta: {
199+
content: fixture.text ?? null,
200+
...(toolCalls ? { tool_calls: toolCalls } : {}),
201+
},
202+
finish_reason: fixture.finishReason,
203+
},
204+
],
205+
usage: { prompt_tokens: 5, completion_tokens: 3, total_tokens: 8 },
206+
})}\n\n`,
207+
);
208+
if (fixture.abort) {
209+
request.once("close", () => response.end());
210+
return;
211+
}
212+
response.end(fixture.done ? "data: [DONE]\n\n" : "");
213+
});
214+
await new Promise<void>((resolve, reject) => {
215+
server.once("error", reject);
216+
server.listen(0, "127.0.0.1", resolve);
217+
});
218+
const { port } = server.address() as AddressInfo;
219+
const model = {
220+
id: "mistral-large-latest",
221+
name: "Mistral terminal owner",
222+
api: "mistral-conversations",
223+
provider: "mistral",
224+
baseUrl: `http://127.0.0.1:${port}`,
225+
reasoning: false,
226+
input: ["text"],
227+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
228+
contextWindow: 128_000,
229+
maxTokens: 8192,
230+
} satisfies Model<"mistral-conversations">;
231+
const context = {
232+
messages: [{ role: "user", content: "Inspect only", timestamp: 1 }],
233+
} satisfies Context;
234+
try {
235+
const abort = new AbortController();
236+
const stream = streamMistral(model, context, {
237+
apiKey: "redacted-fixture-token",
238+
...(fixture.abort ? { signal: abort.signal } : {}),
239+
});
240+
const events: string[] = [];
241+
for await (const event of stream) {
242+
events.push(event.type);
243+
if (fixture.abort && event.type === "toolcall_delta") {
244+
abort.abort(new Error("Operator canceled the incomplete tool"));
245+
}
246+
}
247+
return { result: await stream.result(), events };
248+
} finally {
249+
await new Promise<void>((resolve, reject) => {
250+
server.close((error) => (error ? reject(error) : resolve()));
251+
});
252+
}
253+
}
254+
255+
describe("Mistral terminal ownership through the installed SDK and real HTTP/SSE", () => {
256+
it("discards unfinished tool arguments when the operator cancels generation", async () => {
257+
const { result, events } = await streamMistralTerminalFixture({
258+
finishReason: null,
259+
done: false,
260+
abort: true,
261+
toolArguments: ['{"action":"delete_all"'],
262+
});
263+
expect(result.stopReason).toBe("aborted");
264+
expect(events).not.toContain("toolcall_end");
265+
expect(result.content).not.toContainEqual(expect.objectContaining({ type: "toolCall" }));
266+
});
267+
268+
it.each([
269+
{ name: "EOF without a provider terminal", finishReason: null, done: false },
270+
{ name: "DONE without a provider terminal", finishReason: null, done: true },
271+
{ name: "a provider error terminal", finishReason: "error", done: true },
272+
{ name: "malformed arguments on a tool terminal", finishReason: "tool_calls", done: true },
273+
] as const)("rejects $name without executable calls", async (fixture) => {
274+
const { result, events } = await streamMistralTerminalFixture({
275+
...fixture,
276+
toolArguments: ['{"action":"delete_all"'],
277+
text: "Safe partial answer",
278+
});
279+
expect(result.stopReason).toBe("error");
280+
expect(result.errorMessage).toBeTruthy();
281+
expect(events).not.toContain("toolcall_end");
282+
expect(result.content).not.toContainEqual(expect.objectContaining({ type: "toolCall" }));
283+
expect(result.content).toContainEqual({ type: "text", text: "Safe partial answer" });
284+
});
285+
286+
it.each(["length", "stop"] as const)(
287+
"preserves a %s terminal and visible text without finalizing partial tools",
288+
async (finishReason) => {
289+
const { result, events } = await streamMistralTerminalFixture({
290+
finishReason,
291+
done: true,
292+
toolArguments: ['{"action":"delete_all"'],
293+
text: "Safe partial answer",
294+
});
295+
expect(result.stopReason).toBe(finishReason);
296+
expect(result.content).toEqual([{ type: "text", text: "Safe partial answer" }]);
297+
expect(events).not.toContain("toolcall_end");
298+
expect(events).toContain("done");
299+
},
300+
);
301+
302+
it("drops every pending parallel tool when a later call is truncated", async () => {
303+
const { result, events } = await streamMistralTerminalFixture({
304+
finishReason: "length",
305+
done: true,
306+
toolArguments: ['{"action":"inspect"}', '{"action":"delete_all"'],
307+
});
308+
expect(result.stopReason).toBe("length");
309+
expect(result.content).toEqual([]);
310+
expect(events).not.toContain("toolcall_end");
311+
});
312+
313+
it("keeps a complete provider-confirmed tool executable", async () => {
314+
const { result, events } = await streamMistralTerminalFixture({
315+
finishReason: "tool_calls",
316+
done: true,
317+
toolArguments: ['{"action":"inspect"}'],
318+
});
319+
expect(result.stopReason).toBe("toolUse");
320+
expect(result.content).toContainEqual(
321+
expect.objectContaining({ type: "toolCall", arguments: { action: "inspect" } }),
322+
);
323+
expect(events).toContain("toolcall_end");
324+
});
325+
326+
it.each(["null", "[]", "42", '"dangerous"'] as const)(
327+
"rejects a provider-confirmed non-object JSON argument: %s",
328+
async (argumentsJson) => {
329+
const { result, events } = await streamMistralTerminalFixture({
330+
finishReason: "tool_calls",
331+
done: true,
332+
toolArguments: [argumentsJson],
333+
});
334+
expect(result.stopReason).toBe("error");
335+
expect(result.errorMessage).toContain("invalid JSON arguments");
336+
expect(events).not.toContain("toolcall_end");
337+
expect(result.content).not.toContainEqual(expect.objectContaining({ type: "toolCall" }));
338+
},
339+
);
340+
341+
it("preserves a legitimate empty tool-argument object", async () => {
342+
const { result, events } = await streamMistralTerminalFixture({
343+
finishReason: "tool_calls",
344+
done: true,
345+
toolArguments: ["{}"],
346+
});
347+
expect(result.stopReason).toBe("toolUse");
348+
expect(result.content).toContainEqual(expect.objectContaining({ arguments: {} }));
349+
expect(events).toContain("toolcall_end");
350+
});
351+
352+
it("keeps a completed stop response without tools unchanged", async () => {
353+
const { result, events } = await streamMistralTerminalFixture({
354+
finishReason: "stop",
355+
done: true,
356+
text: "Visible answer",
357+
});
358+
expect(result.stopReason).toBe("stop");
359+
expect(result.content).toEqual([{ type: "text", text: "Visible answer" }]);
360+
expect(events).toContain("done");
361+
});
362+
});

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -630,8 +630,7 @@ describe("Mistral provider", () => {
630630
}).result();
631631
const toolCalls = result.content.filter((block) => block.type === "toolCall");
632632

633-
expect(toolCalls).toHaveLength(2);
634-
expect(new Set(toolCalls.map((toolCall) => toolCall.id)).size).toBe(2);
633+
expect(toolCalls).toHaveLength(0);
635634
expect(result.stopReason).toBe("error");
636635
expect(result.errorMessage).toContain("tool-call continuation is ambiguous");
637636
});

‎packages/ai/src/providers/mistral.ts‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import type {
88
ContentChunk,
99
FunctionTool,
1010
} from "@mistralai/mistralai/models/components";
11+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
1112
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
1213
import { getEnvApiKey } from "../env-api-keys.js";
1314
import { getAiTransportHost } from "../host.js";
@@ -191,10 +192,8 @@ export const streamMistral: StreamFunction<"mistral-conversations", MistralOptio
191192
stream.push({ type: "done", reason: output.stopReason, message: output });
192193
stream.end();
193194
} catch (error) {
194-
for (const block of output.content) {
195-
// partialArgs is only a streaming scratch buffer; never persist it.
196-
delete (block as { partialArgs?: string }).partialArgs;
197-
}
195+
// Failed or canceled generations must never retain partially repaired tool calls.
196+
output.content = output.content.filter((block) => block.type !== "toolCall");
198197
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
199198
output.errorMessage = formatMistralError(error);
200199
stream.push({ type: "error", reason: output.stopReason, error: output });
@@ -415,6 +414,7 @@ async function consumeChatStream(
415414
mistralStream: AsyncIterable<CompletionEvent>,
416415
): Promise<void> {
417416
let currentBlock: TextContent | ThinkingContent | null = null;
417+
let terminalFinishReason: string | undefined;
418418
const blocks = output.content;
419419
const blockIndex = () => blocks.length - 1;
420420
type ToolBlockIdentity = {
@@ -621,6 +621,7 @@ async function consumeChatStream(
621621
}
622622

623623
if (choice.finishReason) {
624+
terminalFinishReason = choice.finishReason;
624625
output.stopReason = mapChatStopReason(choice.finishReason);
625626
}
626627

@@ -780,6 +781,24 @@ async function consumeChatStream(
780781
}
781782

782783
finishCurrentBlock(currentBlock);
784+
// Only an authoritative tool terminal can make strictly parsed arguments executable.
785+
if (!terminalFinishReason || output.stopReason !== "toolUse") {
786+
blocks.splice(0, blocks.length, ...blocks.filter((block) => block.type !== "toolCall"));
787+
if (!terminalFinishReason) {
788+
throw new Error("Mistral stream ended without a terminal finish reason");
789+
}
790+
return;
791+
}
792+
try {
793+
for (const index of toolBlockIdentities.keys()) {
794+
const rawArguments = (blocks[index] as ToolCall & { partialArgs?: string }).partialArgs ?? "";
795+
if (!isRecord(JSON.parse(rawArguments))) {
796+
throw new Error("Mistral tool-call arguments must be a JSON object");
797+
}
798+
}
799+
} catch {
800+
throw new Error("Mistral completed tool call has invalid JSON arguments");
801+
}
783802
for (const index of toolBlockIdentities.keys()) {
784803
const block = output.content.at(index);
785804
if (block?.type !== "toolCall") {

0 commit comments

Comments
 (0)