Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

A local model's tool calls work even when they arrive as text, and it can't loop forever (#4180)

Milind Soni637161105062
diff --git a/server/drivers/agents-bridge-chat.test.ts b/server/drivers/agents-bridge-chat.test.ts
index 2c206163ec..b771c364aa 100644
--- a/server/drivers/agents-bridge-chat.test.ts
+++ b/server/drivers/agents-bridge-chat.test.ts
@@ -95,10 +95,9 @@ it("a bridged turn on the chat-completions runtime carries on after use_tool nam
expect(tools).toEqual([false, true]);
expect(recorder.events.some((event) => event.type === "item.completed" && event.itemType === "assistant_text" && event.text === "The tool for that is create_trigger.")).toBe(true);
- // It ends the way any turn with a failed tool call ends on this runtime,
- // not as a transport that broke under it.
+ // This fixture is on this machine, so the model counts as local: having searched and answered, it is not failed for
+ // its first guess, and nothing reads as a transport that broke under it.
const errors = recorder.events.flatMap((event) => event.type === "runtime.error" ? [event.message] : []);
- expect(errors.join("\n")).not.toMatch(/MCP request failed|MCP session closed|execution outcome may be uncertain/);
- expect(completed).toMatchObject({ ok: false });
- expect(errors).toEqual([expect.stringMatching(/^Stopped because the tool call “[^”]+” failed\./)]);
+ expect(completed).toMatchObject({ ok: true });
+ expect(errors).toEqual([]);
}, 30_000);
diff --git a/server/drivers/chat-repeat-guard.test.ts b/server/drivers/chat-repeat-guard.test.ts
new file mode 100644
index 0000000000..4f8e723e68
--- /dev/null
+++ b/server/drivers/chat-repeat-guard.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from "vitest";
+import { ChatRepeatGuard } from "./chat-repeat-guard.ts";
+
+const failed = { ok: false, text: "ENOENT" };
+
+describe("ChatRepeatGuard", () => {
+ it("refuses a call after three identical failures, then stops at the second refusal", () => {
+ const guard = new ChatRepeatGuard();
+ expect(guard.noteAfter("read", "{}", failed)).toBeUndefined();
+ expect(guard.refuses("read", "{}")).toBeNull();
+ expect(guard.noteAfter("read", "{}", failed)).toBeUndefined();
+ expect(guard.noteAfter("read", "{}", failed)).toContain("will not run again");
+ expect(guard.refuses("read", "{}")).toContain("was not run");
+ expect(guard.stopped).toBeNull();
+ expect(guard.refuses("read", "{}")).toContain("was not run");
+ expect(guard.stopped).toContain("read");
+ });
+
+ it("treats other inputs and other failures as progress", () => {
+ const guard = new ChatRepeatGuard();
+ for (const text of ["a", "b", "c", "d"]) guard.noteAfter("read", "{}", { ok: false, text });
+ expect(guard.refuses("read", "{}")).toBeNull();
+ for (let i = 0; i < 3; i++) guard.noteAfter("read", '{"p":1}', failed);
+ expect(guard.refuses("read", '{"p":2}')).toBeNull();
+ expect(guard.refuses("read", '{"p":1}')).not.toBeNull();
+ });
+
+ it("starts the count over when the call works", () => {
+ const guard = new ChatRepeatGuard();
+ guard.noteAfter("read", "{}", failed);
+ guard.noteAfter("read", "{}", failed);
+ guard.noteAfter("read", "{}", { ok: true, text: "fine" });
+ guard.noteAfter("read", "{}", failed);
+ expect(guard.refuses("read", "{}")).toBeNull();
+ });
+
+ it("sees the same call in another key order", () => {
+ const guard = new ChatRepeatGuard();
+ for (let i = 0; i < 3; i++) guard.noteAfter("read", '{"a":1,"b":2}', failed);
+ expect(guard.refuses("read", '{"b":2,"a":1}')).not.toBeNull();
+ });
+
+ it("notes a repeated answer at three and stops at ten, even taking turns with another call", () => {
+ const guard = new ChatRepeatGuard();
+ const same = { ok: true, text: "still running" };
+ const notes: Array<string | undefined> = [];
+ for (let i = 0; i < 9; i++) {
+ notes.push(guard.noteAfter("status", "{}", same));
+ guard.noteAfter("other", `{"i":${i}}`, { ok: true, text: String(i) });
+ }
+ expect(notes[1]).toBeUndefined();
+ expect(notes[2]).toContain("3 times");
+ expect(guard.stopped).toBeNull();
+ guard.noteAfter("status", "{}", same);
+ expect(guard.stopped).toContain("status");
+ });
+
+ it("never counts a screenshot as the same answer", () => {
+ const guard = new ChatRepeatGuard();
+ for (let i = 0; i < 20; i++) expect(guard.noteAfter("shot", "{}", { ok: true, text: "ok", images: [{}] })).toBeUndefined();
+ expect(guard.stopped).toBeNull();
+ });
+
+ it("a changed answer starts over", () => {
+ const guard = new ChatRepeatGuard();
+ guard.noteAfter("status", "{}", { ok: true, text: "a" });
+ guard.noteAfter("status", "{}", { ok: true, text: "a" });
+ guard.noteAfter("status", "{}", { ok: true, text: "b" });
+ expect(guard.noteAfter("status", "{}", { ok: true, text: "b" })).toBeUndefined();
+ });
+});
diff --git a/server/drivers/chat-repeat-guard.ts b/server/drivers/chat-repeat-guard.ts
new file mode 100644
index 0000000000..af19ec3995
--- /dev/null
+++ b/server/drivers/chat-repeat-guard.ts
@@ -0,0 +1,71 @@
+// A local model that is stuck says so by repeating itself: the same call, the same answer, until the round limit. Counted
+// per call rather than back to back, so taking turns between two stuck calls is still stuck. A different answer starts the
+// count over, because that is progress. Each round on a laptop costs tens of seconds, so this stops long before the limit.
+import { createHash } from "node:crypto";
+
+const REFUSE_AFTER_FAILURES = 3;
+const REFUSALS_BEFORE_STOP = 2;
+const SAME_ANSWER_NOTE_AT = 3;
+const SAME_ANSWER_STOP_AT = 10;
+
+interface Seen {
+ ok: boolean;
+ answer: string;
+ streak: number;
+}
+
+/** The same arguments in another key order are the same call. */
+function canonical(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(canonical);
+ if (value === null || typeof value !== "object") return value;
+ const source = value as Record<string, unknown>;
+ return Object.fromEntries(Object.keys(source).sort().map((key) => [key, canonical(source[key])]));
+}
+
+function callKey(name: string, args: string): string {
+ try { return `${name}:${JSON.stringify(canonical(JSON.parse(args)))}`; } catch { return `${name}:${args}`; }
+}
+
+const digest = (text: string) => createHash("sha256").update(text).digest("base64");
+
+export class ChatRepeatGuard {
+ private readonly seen = new Map<string, Seen>();
+ private refusals = 0;
+ private stuck: string | null = null;
+
+ /** Why this call must not run again, or null. Asked before it runs. */
+ refuses(name: string, args: string): string | null {
+ const seen = this.seen.get(callKey(name, args));
+ if (!seen || seen.ok || seen.streak < REFUSE_AFTER_FAILURES) return null;
+ if (++this.refusals >= REFUSALS_BEFORE_STOP) {
+ this.stuck = `The model kept repeating a call to ${name} that had already failed ${seen.streak} times the same way, so the turn was stopped. Try again with a clearer request, or choose a stronger model.`;
+ }
+ return `[OpenMausBot: this exact call was not run. It already failed ${seen.streak} times the same way. Use different inputs, try another approach, or say what is blocking.]`;
+ }
+
+ /** A result the model has seen before, with a note to add to it. A screenshot is never the same answer: its text says
+ * little, and the picture is what changed. */
+ noteAfter(name: string, args: string, result: { ok: boolean; text: string; images?: readonly unknown[] }): string | undefined {
+ const key = callKey(name, args);
+ if (result.images?.length) {
+ this.seen.delete(key);
+ return undefined;
+ }
+ const answer = digest(result.text);
+ const before = this.seen.get(key);
+ const streak = before && before.ok === result.ok && before.answer === answer ? before.streak + 1 : 1;
+ this.seen.set(key, { ok: result.ok, answer, streak });
+ if (!result.ok) {
+ return streak === REFUSE_AFTER_FAILURES ? `[OpenMausBot: this exact call has now failed ${streak} times the same way, so it will not run again this turn. Change approach, or say what is blocking.]` : undefined;
+ }
+ if (streak >= SAME_ANSWER_STOP_AT) {
+ this.stuck = `The model made the same call to ${name} ${streak} times and got the same answer each time, so the turn was stopped. Try again with a clearer request, or choose a stronger model.`;
+ }
+ return streak >= SAME_ANSWER_NOTE_AT ? `[OpenMausBot: this call has returned this same result ${streak} times. If that was expected, carry on. Otherwise use the result, try something else, or give your answer.]` : undefined;
+ }
+
+ /** Set once the turn should end: the words to end it with. */
+ get stopped(): string | null {
+ return this.stuck;
+ }
+}
diff --git a/server/drivers/chat-text-tool-calls.test.ts b/server/drivers/chat-text-tool-calls.test.ts
new file mode 100644
index 0000000000..5f383ffc78
--- /dev/null
+++ b/server/drivers/chat-text-tool-calls.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vitest";
+import { TextCallHoldback, textToolCalls, type OfferedTool } from "./chat-text-tool-calls.ts";
+
+const tools: OfferedTool[] = [
+ { function: { name: "read_file", parameters: { type: "object", properties: { path: { type: "string" }, lines: { type: "integer" }, opts: { type: "object" } } } } },
+ { function: { name: "list_dir" } },
+];
+
+const calls = (reply: string) => {
+ const found = textToolCalls(reply, tools);
+ if (found?.kind !== "calls") throw new Error(`no calls in ${JSON.stringify(found)}`);
+ return found.calls.map((call) => [call.function.name, JSON.parse(call.function.arguments)]);
+};
+
+describe("textToolCalls", () => {
+ it("reads the JSON tag form with the words before it", () => {
+ const found = textToolCalls('Let me look.\n<tool_call>\n{"name":"read_file","arguments":{"path":"a.md"}}\n</tool_call>', tools);
+ expect(found?.kind === "calls" && found.text).toBe("Let me look.");
+ expect(calls('Let me look.\n<tool_call>\n{"name":"read_file","arguments":{"path":"a.md"}}\n</tool_call>')).toEqual([["read_file", { path: "a.md" }]]);
+ });
+
+ it("reads several calls in order, and gives each its own id", () => {
+ const reply = '<tool_call>{"name":"list_dir","arguments":{}}</tool_call>\n<tool_call>{"name":"read_file","arguments":{"path":"b"}}</tool_call>';
+ expect(calls(reply).map(([name]) => name)).toEqual(["list_dir", "read_file"]);
+ const found = textToolCalls(reply, tools);
+ if (found?.kind !== "calls") throw new Error("no calls");
+ expect(new Set(found.calls.map((call) => call.id)).size).toBe(2);
+ for (const call of found.calls) expect(call.id).toMatch(/^[A-Za-z0-9_-]{1,64}$/);
+ });
+
+ it("reads a call whose closing tag the server stopped on", () => {
+ expect(calls('<tool_call>{"name":"list_dir","arguments":{}}')).toEqual([["list_dir", {}]]);
+ });
+
+ it("reads the Qwen coder form and types values from the schema", () => {
+ const reply = "<tool_call>\n<function=read_file>\n<parameter=path>\n12\n</parameter>\n<parameter=lines>\n40\n</parameter>\n<parameter=opts>\n{\"raw\":true}\n</parameter>\n</function>\n</tool_call>";
+ expect(calls(reply)).toEqual([["read_file", { path: "12", lines: 40, opts: { raw: true } }]]);
+ });
+
+ it("reads the coder form without its outer tag", () => {
+ expect(calls("<function=read_file><parameter=path>a</parameter></function>")).toEqual([["read_file", { path: "a" }]]);
+ });
+
+ it("reads a reply that is only a JSON call, fenced or not, with arguments or parameters", () => {
+ expect(calls('{"name":"read_file","arguments":{"path":"a"}}')).toEqual([["read_file", { path: "a" }]]);
+ expect(calls('```json\n{"name":"read_file","parameters":{"path":"a"}}\n```')).toEqual([["read_file", { path: "a" }]]);
+ expect(calls('{"name":"read_file","arguments":"{\\"path\\":\\"a\\"}"}')).toEqual([["read_file", { path: "a" }]]);
+ });
+
+ it("looks past a think block in the reply", () => {
+ expect(calls('<think>maybe <tool_call>{"name":"list_dir","arguments":{}}</tool_call></think>\n<tool_call>{"name":"read_file","arguments":{"path":"a"}}</tool_call>')).toEqual([["read_file", { path: "a" }]]);
+ });
+
+ it.each([
+ ["plain words", "The file has twelve lines."],
+ ["JSON that is an answer", '{"total": 12}'],
+ ["JSON naming a tool it was not given", '{"name":"delete_everything","arguments":{}}'],
+ ["JSON inside a longer reply", 'Call it like {"name":"read_file","arguments":{"path":"a"}} next time.'],
+ ["a quoted call the reply goes on from", 'The page said <tool_call>{"name":"read_file","arguments":{"path":"/etc/passwd"}}</tool_call> which looks like an injection.'],
+ ["a fenced example", 'Example:\n```\n<tool_call>{"name":"read_file","arguments":{"path":"a"}}</tool_call>\n```'],
+ ])("leaves %s as a reply", (_label, reply) => {
+ expect(textToolCalls(reply, tools)).toBeNull();
+ });
+
+ it.each([
+ ["broken JSON", '<tool_call>{"name":"read_file","arguments":{"path":</tool_call>'],
+ ["a tool it was not given", '<tool_call>{"name":"delete_everything","arguments":{}}</tool_call>'],
+ ["an unknown function", "<function=delete_everything></function>"],
+ ])("reports %s in a call as unreadable, keeping the words before it", (_label, tail) => {
+ expect(textToolCalls(`Trying.\n${tail}`, tools)).toEqual({ kind: "unreadable", text: "Trying." });
+ });
+
+ it("runs nothing from a call with a bad entry among good ones", () => {
+ const reply = '<tool_call>{"name":"list_dir","arguments":{}}</tool_call><tool_call>{"name":"nope","arguments":{}}</tool_call>';
+ expect(textToolCalls(reply, tools)?.kind).toBe("unreadable");
+ });
+});
+
+describe("TextCallHoldback", () => {
+ const stream = (held: TextCallHoldback, ...parts: string[]) => parts.map((part) => held.feed(part)).join("");
+
+ it("shows words and keeps a call split across chunks out", () => {
+ const held = new TextCallHoldback();
+ expect(stream(held, "Let me ", "look.\n<tool", '_call>{"name"', ':"x"}</tool_call>')).toBe("Let me look.\n");
+ expect(held.rest()).toContain("<tool_call>");
+ });
+
+ it("gives back a partial tag that was only text", () => {
+ const held = new TextCallHoldback();
+ expect(stream(held, "a <tool", " b")).toBe("a <tool b");
+ expect(held.rest()).toBe("");
+ });
+
+ it("holds a reply that opens like a JSON call until the end", () => {
+ const held = new TextCallHoldback();
+ expect(stream(held, '{"total"', ": 12}")).toBe("");
+ expect(held.rest()).toBe('{"total": 12}');
+ });
+
+ it("holds a fence, then releases it whole", () => {
+ const held = new TextCallHoldback();
+ expect(stream(held, "``", "`sh\nls\n```")).toBe("");
+ expect(held.rest()).toBe("```sh\nls\n```");
+ });
+});
diff --git a/server/drivers/chat-text-tool-calls.ts b/server/drivers/chat-text-tool-calls.ts
new file mode 100644
index 0000000000..f56913115a
--- /dev/null
+++ b/server/drivers/chat-text-tool-calls.ts
@@ -0,0 +1,164 @@
+// A tool call a local model wrote as text instead of as a structured call. Local servers turn this text into tool_calls
+// only when their chat template and parser match the model, and when they do not the call reaches us as the reply: Qwen
+// through Ollama's /v1, a GGUF with a stock template, a server started without --jinja.
+//
+// The forms are the ones the servers' own parsers read: `<tool_call>{json}</tool_call>` (Hermes and Qwen templates),
+// `<function=name><parameter=key>…` (Qwen coder templates) and a reply that is nothing but one JSON call. This is stricter
+// than those parsers, which take a tag anywhere in the output: the calls must end the reply and name an offered tool, so
+// a reply that quotes a call and goes on talking stays a reply. Reasoning is never read. A recovered call then takes the
+// same schema check and approval as any other.
+import { randomUUID } from "node:crypto";
+import type { ChatToolCall } from "./openai-chat-protocol.ts";
+import { object } from "./openai-chat-protocol.ts";
+
+export interface OfferedTool {
+ function: { name: string; parameters?: Record<string, unknown> };
+}
+
+export type TextToolCalls =
+ /** `text` is what the model said before the calls. */
+ | { kind: "calls"; calls: ChatToolCall[]; text: string }
+ /** It tried to call a tool and the call cannot be read: worth one request to send it again. */
+ | { kind: "unreadable"; text: string };
+
+const MAX_CALLS = 32;
+const OPEN_TAG = "<tool_call>";
+const CLOSE_TAG = "</tool_call>";
+const OPEN_FUNCTION = "<function=";
+const THINK_END = "</think>";
+
+const FUNCTION_BLOCK = /<function=([^>\s]+)\s*>([\s\S]*?)(?:<\/function>|$)/;
+const PARAMETER = /<parameter=([^>\s]+)\s*>([\s\S]*?)(?:<\/parameter>|(?=<parameter=)|$)/g;
+const FENCED_JSON = /^```(?:json)?\s*\n?([\s\S]*?)\n?```$/;
+
+function parsedObject(text: string): Record<string, unknown> | undefined {
+ try { return object(JSON.parse(text)); } catch { return undefined; }
+}
+
+function declaredType(tool: OfferedTool, key: string): unknown {
+ return object(object(tool.function.parameters?.properties)?.[key])?.type;
+}
+
+/** A parameter's body is text; the tool's schema says when it is a number, an object or a list. */
+function parameterValue(tool: OfferedTool, key: string, raw: string): unknown {
+ const value = raw.replace(/^\n/, "").replace(/\n$/, "");
+ const type = declaredType(tool, key);
+ if (type === "string" || (Array.isArray(type) && type.includes("string"))) return value;
+ try { return JSON.parse(value.trim()); } catch { return value; }
+}
+
+function toCall(name: string, args: Record<string, unknown>): ChatToolCall {
+ return { id: `text_${randomUUID().replaceAll("-", "")}`, type: "function", function: { name, arguments: JSON.stringify(args) } };
+}
+
+function jsonCall(body: string, offered: ReadonlyMap<string, OfferedTool>): ChatToolCall | undefined {
+ const parsed = parsedObject(body);
+ if (typeof parsed?.name !== "string" || !offered.has(parsed.name)) return undefined;
+ // Llama-family templates write `parameters`; an argument object some models double-encode is still that object.
+ const raw = parsed.arguments ?? parsed.parameters ?? {};
+ const args = typeof raw === "string" ? parsedObject(raw) : object(raw);
+ return args ? toCall(parsed.name, args) : undefined;
+}
+
+function functionCall(body: string, offered: ReadonlyMap<string, OfferedTool>): ChatToolCall | undefined {
+ const block = FUNCTION_BLOCK.exec(body);
+ const tool = block ? offered.get(block[1]!) : undefined;
+ if (!block || !tool) return undefined;
+ const args: Record<string, unknown> = {};
+ for (const [, key, raw] of block[2]!.matchAll(PARAMETER)) args[key!] = parameterValue(tool, key!, raw!);
+ return toCall(block[1]!, args);
+}
+
+/** Each call's body in order, or undefined if anything but calls follows the first one. */
+function taggedBodies(text: string): string[] | undefined {
+ const bodies: string[] = [];
+ let rest = text;
+ while (rest.trim()) {
+ rest = rest.trimStart();
+ if (rest.startsWith(OPEN_FUNCTION)) {
+ const end = rest.indexOf("</function>");
+ if (end === -1) { bodies.push(rest); return bodies; }
+ bodies.push(rest.slice(0, end + "</function>".length));
+ rest = rest.slice(end + "</function>".length);
+ continue;
+ }
+ if (!rest.startsWith(OPEN_TAG)) return undefined;
+ rest = rest.slice(OPEN_TAG.length);
+ const end = rest.indexOf(CLOSE_TAG);
+ // A server that stops on the closing tag never sends it.
+ if (end === -1) { bodies.push(rest); return bodies; }
+ bodies.push(rest.slice(0, end));
+ rest = rest.slice(end + CLOSE_TAG.length);
+ }
+ return bodies;
+}
+
+const firstCallAt = (text: string) => {
+ const found = [text.indexOf(OPEN_TAG), text.indexOf(OPEN_FUNCTION)].filter((at) => at !== -1);
+ return found.length ? Math.min(...found) : -1;
+};
+
+const withoutThinking = (text: string) => {
+ const end = text.lastIndexOf(THINK_END);
+ return end === -1 ? text : text.slice(end + THINK_END.length);
+};
+
+/** Null when the reply is a reply. */
+export function textToolCalls(reply: string, tools: readonly OfferedTool[]): TextToolCalls | null {
+ const offered = new Map(tools.map((tool) => [tool.function.name, tool]));
+ const text = withoutThinking(reply).trim();
+ const at = firstCallAt(text);
+ if (at === -1) {
+ const fenced = FENCED_JSON.exec(text)?.[1];
+ const call = text.startsWith("{") || fenced ? jsonCall(fenced ?? text, offered) : undefined;
+ return call ? { kind: "calls", calls: [call], text: "" } : null;
+ }
+ const said = text.slice(0, at).trimEnd();
+ const bodies = taggedBodies(text.slice(at));
+ // Calls followed by more words: an example or a quotation, not a request to run something.
+ if (!bodies?.length || bodies.length > MAX_CALLS) return null;
+ const calls: ChatToolCall[] = [];
+ for (const body of bodies) {
+ const call = body.includes(OPEN_FUNCTION) ? functionCall(body, offered) : jsonCall(body.trim(), offered);
+ if (!call) return { kind: "unreadable", text: said };
+ calls.push(call);
+ }
+ return { kind: "calls", calls, text: said };
+}
+
+const MARKERS = [OPEN_TAG, OPEN_FUNCTION];
+
+function partialMarkerLength(text: string): number {
+ for (let length = Math.min(text.length, Math.max(...MARKERS.map((marker) => marker.length - 1))); length > 0; length--) {
+ const tail = text.slice(-length);
+ if (MARKERS.some((marker) => marker.startsWith(tail))) return length;
+ }
+ return 0;
+}
+
+/** Keeps a call out of the streamed reply: words before it show as they arrive, and from where a call might start the
+ * text waits until the reply ends and `textToolCalls` has decided. */
+export class TextCallHoldback {
+ private seen = "";
+ private shown = 0;
+
+ feed(delta: string): string {
+ this.seen += delta;
+ const start = this.seen.trimStart();
+ // A reply opening like this may be one bare JSON call, which is only known at the end.
+ if (!start || start.startsWith("{") || "```".startsWith(start.slice(0, 3)) || start.startsWith("```")) return "";
+ const at = firstCallAt(this.seen);
+ const end = at !== -1 ? at : this.seen.length - partialMarkerLength(this.seen);
+ if (end <= this.shown) return "";
+ const visible = this.seen.slice(this.shown, end);
+ this.shown = end;
+ return visible;
+ }
+
+ /** What is still held, for a reply that turned out to have no call in it. */
+ rest(): string {
+ const held = this.seen.slice(this.shown);
+ this.shown = this.seen.length;
+ return held;
+ }
+}
diff --git a/server/drivers/openai-chat-local-model.test.ts b/server/drivers/openai-chat-local-model.test.ts
new file mode 100644
index 0000000000..5d2bbd5297
--- /dev/null
+++ b/server/drivers/openai-chat-local-model.test.ts
@@ -0,0 +1,248 @@
+// Real HTTP and real stdio MCP: what a model on this machine gets that a hosted one does not.
+import { randomUUID } from "node:crypto";
+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { createServer, type ServerResponse } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import type { ProviderInstance, SendTurnInput } from "../contracts.ts";
+import { removeTempDir } from "../testing/cleanup.ts";
+import { recordEvents } from "../testing/events.ts";
+import { GrokDriver } from "./grok.ts";
+import { OpenAICompatDriver } from "./openai-compat.ts";
+
+interface ChatRequest { messages: Array<{ role: string; content: unknown; tool_call_id?: string; tool_calls?: Array<{ id: string; function: { name: string; arguments: string } }> }> }
+type Script = (body: ChatRequest, response: ServerResponse, round: number) => void;
+
+const MCP_SCRIPT = `
+import { appendFileSync } from "node:fs";
+import { createInterface } from "node:readline";
+const [effects] = process.argv.slice(2);
+const reply = (id, result) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\\n");
+const schema = { type: "object", properties: { name: { type: "string" } }, required: ["name"], additionalProperties: false };
+createInterface({ input: process.stdin }).on("line", (line) => {
+ const request = JSON.parse(line);
+ if (request.method === "initialize") reply(request.id, { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "fixture", version: "1" } });
+ else if (request.method === "tools/list") reply(request.id, { tools: ["write", "fail", "status"].map((name) => ({ name, description: "Fixture", inputSchema: schema })) });
+ else if (request.method === "tools/call") {
+ const { name, arguments: args } = request.params;
+ appendFileSync(effects, JSON.stringify({ name, ...args }) + "\\n");
+ if (name === "fail") reply(request.id, { isError: true, content: [{ type: "text", text: "Always fails." }] });
+ else if (name === "status") reply(request.id, { content: [{ type: "text", text: "still running" }] });
+ else reply(request.id, { content: [{ type: "text", text: "Stored " + args.name }] });
+ } else if (request.id !== undefined) reply(request.id, {});
+});
+`;
+
+const chunk = (delta: unknown, finishReason: string | null = null) => ({ choices: [{ index: 0, delta, finish_reason: finishReason }] });
+function sse(response: ServerResponse, chunks: unknown[]) {
+ response.writeHead(200, { "content-type": "text/event-stream" });
+ for (const value of chunks) response.write(`data: ${JSON.stringify(value)}\n\n`);
+ response.end("data: [DONE]\n\n");
+}
+const say = (response: ServerResponse, ...parts: string[]) =>
+ sse(response, [...parts.map((content) => chunk({ content })), chunk({}, "stop")]);
+const structured = (response: ServerResponse, name: string, id: string) =>
+ sse(response, [chunk({ tool_calls: [{ index: 0, id, type: "function", function: { name, arguments: '{"name":"same"}' } }] }, "tool_calls")]);
+
+const cleanups: Array<() => Promise<void>> = [];
+afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); });
+
+async function fixture(script: Script, driver: "local" | "hosted" = "local") {
+ const directory = mkdtempSync(join(tmpdir(), "omb-chat-local-"));
+ const requests: ChatRequest[] = [];
+ const server = createServer(async (request, response) => {
+ if (request.url === "/v1/models") { response.setHeader("content-type", "application/json"); response.end('{"data":[]}'); return; }
+ let data = "";
+ for await (const part of request) data += part.toString();
+ const body = JSON.parse(data) as ChatRequest;
+ requests.push(body);
+ script(body, response, requests.length);
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("fixture did not bind TCP");
+ const helper = join(directory, "mcp.mjs");
+ const effectsFile = join(directory, "effects.ndjson");
+ writeFileSync(helper, MCP_SCRIPT);
+ const instance: ProviderInstance = await (driver === "hosted" ? GrokDriver : OpenAICompatDriver).create({
+ instanceId: randomUUID(), displayName: "Local fixture", enabled: true,
+ config: { url: `http://127.0.0.1:${address.port}/v1`, apiKeyEnv: "FIXTURE_CHAT_KEY" },
+ environment: { FIXTURE_CHAT_KEY: "fixture-key" },
+ });
+ const recorder = recordEvents(instance.adapter);
+ const threadId = randomUUID();
+ const integrations: SendTurnInput["integrations"] = { custom: { audit: { command: process.execPath, args: [helper, effectsFile], env: {} } } };
+ cleanups.push(async () => {
+ recorder.stop();
+ await instance.dispose();
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ await removeTempDir(directory);
+ });
+ return {
+ requests, recorder, threadId,
+ respond: (requestId: string, behavior: "allow" | "deny") => instance.adapter.respondToRequest(threadId, requestId, { behavior }),
+ effects: () => existsSync(effectsFile) ? readFileSync(effectsFile, "utf8").trim().split("\n").map((line) => JSON.parse(line) as { name: string }) : [],
+ start: (input: Partial<SendTurnInput> = {}) => instance.adapter.sendTurn({ threadId, text: "Do it.", model: "fixture-model", integrations, approvalMode: "full", ...input }),
+ completed: () => recorder.until((event) => event.type === "turn.completed"),
+ shown: () => recorder.events.flatMap((event) => event.type === "content.delta" ? [event.delta] : []).join(""),
+ replies: () => recorder.events.flatMap((event) => event.type === "item.completed" && event.itemType === "assistant_text" ? [event.text] : []),
+ opened: () => recorder.events.flatMap((event) => event.type === "request.opened" ? [event] : []),
+ };
+}
+
+const TAGGED = '<tool_call>{"name":"audit_write","arguments":{"name":"receipt"}}</tool_call>';
+
+describe("a tool call a local model wrote as text", () => {
+ it("runs it, hides the markup, and sends the result back as a tool result", async () => {
+ const f = await fixture((_body, response, round) => round === 1
+ ? say(response, "Saving it.\n<tool", '_call>{"name":"audit_write",', '"arguments":{"name":"receipt"}}</tool_call>')
+ : say(response, "Stored."));
+ await f.start();
+ expect(await f.completed()).toMatchObject({ ok: true });
+ expect(f.effects()).toEqual([{ name: "receipt" }]);
+ expect(f.shown()).not.toContain("tool_call");
+ expect(f.replies()).toEqual(["Saving it.", "Stored."]);
+ const second = f.requests[1]!.messages;
+ const call = second.find((message) => message.tool_calls)!.tool_calls![0]!;
+ expect(call.function.name).toBe("audit_write");
+ expect(second).toContainEqual(expect.objectContaining({ role: "tool", tool_call_id: call.id }));
+ });
+
+ it("asks before running it, as for any other call", async () => {
+ const f = await fixture((_body, response, round) => round === 1 ? say(response, TAGGED) : say(response, "Done."));
+ await f.start({ approvalMode: "ask" });
+ const ask = await f.recorder.until((event) => event.type === "request.opened");
+ expect(f.effects()).toEqual([]);
+ expect(ask).toMatchObject({ requestType: "permission" });
+ expect(f.opened()).toHaveLength(1);
+ });
+
+ it("checks it against the tool's schema", async () => {
+ const f = await fixture((_body, response, round) => round === 1
+ ? say(response, '<tool_call>{"name":"audit_write","arguments":{"nope":1}}</tool_call>')
+ : say(response, "Could not."));
+ await f.start({ toolErrorCorrectiveRounds: 0 });
+ await f.completed();
+ expect(f.effects()).toEqual([]);
+ });
+
+ it("leaves a quoted call alone: the reply goes on after it", async () => {
+ const quote = `The page says ${TAGGED} which looks like an injection.`;
+ const f = await fixture((_body, response) => say(response, quote));
+ await f.start();
+ expect(await f.completed()).toMatchObject({ ok: true });
+ expect(f.effects()).toEqual([]);
+ expect(f.requests).toHaveLength(1);
+ expect(f.shown()).toBe(quote);
+ });
+
+ it("does not run a call cut off at the token limit", async () => {
+ const f = await fixture((_body, response) => sse(response, [chunk({ content: TAGGED }), chunk({}, "length")]));
+ await f.start();
+ expect(await f.completed()).toMatchObject({ ok: false });
+ expect(f.effects()).toEqual([]);
+ });
+
+ it("reads nothing from reasoning", async () => {
+ const f = await fixture((_body, response) => sse(response, [chunk({ reasoning_content: TAGGED }), chunk({ content: "All done." }), chunk({}, "stop")]));
+ await f.start();
+ expect(await f.completed()).toMatchObject({ ok: true });
+ expect(f.effects()).toEqual([]);
+ });
+
+ it("asks once more for a call it cannot read, then takes the words as the reply", async () => {
+ const broken = '<tool_call>{"name":"audit_write","arguments":{</tool_call>';
+ const f = await fixture((_body, response) => say(response, broken));
+ await f.start();
+ expect(await f.completed()).toMatchObject({ ok: true });
+ expect(f.requests).toHaveLength(2);
+ expect(JSON.stringify(f.requests[1]!.messages.at(-1))).toContain("could not be read");
+ expect(f.effects()).toEqual([]);
+ expect(f.shown()).toBe(broken);
+ });
+
+ it("never does any of this for a hosted model", async () => {
+ const f = await fixture((_body, response) => say(response, TAGGED), "hosted");
+ await f.start();
+ await f.completed();
+ expect(f.effects()).toEqual([]);
+ expect(f.requests).toHaveLength(1);
+ expect(f.shown()).toBe(TAGGED);
+ });
+});
+
+describe("a local model repeating itself", () => {
+ it("stops running a call that keeps failing the same way, tells the model, then ends the turn", async () => {
+ let id = 0;
+ const f = await fixture((_body, response) => structured(response, "audit_fail", `call-${++id}`));
+ await f.start();
+ const completed = await f.completed();
+ expect(completed).toMatchObject({ ok: false, stopReason: "incomplete_action" });
+ expect(f.effects()).toHaveLength(3);
+ expect(JSON.stringify(f.requests[3]!.messages.at(-1))).toContain("will not run again");
+ expect(JSON.stringify(f.requests[4]!.messages.at(-1))).toContain("was not run");
+ expect(f.recorder.events).toContainEqual(expect.objectContaining({ type: "runtime.error", message: expect.stringContaining("audit_fail") }));
+ });
+
+ it("ends a turn stuck on one unchanging answer", async () => {
+ let id = 0;
+ const f = await fixture((_body, response) => structured(response, "audit_status", `call-${++id}`));
+ await f.start();
+ expect(await f.completed()).toMatchObject({ ok: false, stopReason: "incomplete_action" });
+ expect(f.effects()).toHaveLength(10);
+ expect(JSON.stringify(f.requests[3]!.messages.at(-1))).toContain("same result");
+ });
+
+ it("gets a failed call corrected, without being configured to", async () => {
+ const f = await fixture((_body, response, round) => {
+ if (round === 1) structured(response, "audit_fail", "call-1");
+ else if (round === 2) say(response, "It is finished.");
+ else if (round === 3) structured(response, "audit_write", "call-3");
+ else say(response, "Now it is finished.");
+ });
+ await f.start();
+ expect(await f.completed()).toMatchObject({ ok: true });
+ expect(f.effects().map((effect) => effect.name)).toEqual(["same", "same"]);
+ expect(JSON.stringify(f.requests[2]!.messages.at(-1))).toContain("Re-run the failed operations");
+ });
+
+ it("does not nag a model that reacted to a failure by using more tools", async () => {
+ const f = await fixture((_body, response, round) => {
+ if (round === 1) structured(response, "audit_fail", "call-1");
+ else if (round === 2) structured(response, "audit_write", "call-2");
+ else say(response, "Done another way.");
+ });
+ await f.start();
+ expect(await f.completed()).toMatchObject({ ok: true });
+ expect(f.requests).toHaveLength(3);
+ });
+
+ it("still ends the turn if the model never fixes it", async () => {
+ const f = await fixture((_body, response, round) => round === 1 ? structured(response, "audit_fail", "call-1") : say(response, "It is finished."));
+ await f.start();
+ expect(await f.completed()).toMatchObject({ ok: false, stopReason: "tool_error" });
+ expect(f.requests).toHaveLength(4);
+ });
+
+ it("a person's no is never argued with", async () => {
+ const f = await fixture((_body, response, round) => round === 1 ? structured(response, "audit_write", "call-1") : say(response, "I could not."));
+ await f.start({ approvalMode: "ask" });
+ const ask = await f.recorder.until((event) => event.type === "request.opened");
+ await f.respond(ask.requestId!, "deny");
+ expect(await f.completed()).toMatchObject({ ok: false });
+ expect(f.requests).toHaveLength(2);
+ expect(f.effects()).toEqual([]);
+ });
+
+ it("a hosted model's failed turn ends as before", async () => {
+ let id = 0;
+ const f = await fixture((_body, response, round) => round === 1 ? structured(response, "audit_fail", `call-${++id}`) : say(response, "It is finished."), "hosted");
+ await f.start();
+ expect(await f.completed()).toMatchObject({ ok: false, stopReason: "tool_error" });
+ expect(f.requests).toHaveLength(2);
+ });
+});
diff --git a/server/drivers/openai-chat-protocol.ts b/server/drivers/openai-chat-protocol.ts
index af5059faf3..6e8b0d77cd 100644
--- a/server/drivers/openai-chat-protocol.ts
+++ b/server/drivers/openai-chat-protocol.ts
@@ -1,4 +1,4 @@
-// Structured chat-completions calls. Assistant content is never parsed as a tool.
+// Structured chat-completions calls. Assistant content becomes a tool call only for a local model, in chat-text-tool-calls.ts.
export interface ChatToolCall {
id: string;
type: "function";
diff --git a/server/drivers/openai-chat-refusals.ts b/server/drivers/openai-chat-refusals.ts
new file mode 100644
index 0000000000..7a13e21c09
--- /dev/null
+++ b/server/drivers/openai-chat-refusals.ts
@@ -0,0 +1,60 @@
+// How a chat-completions provider says no to a request, and what that means for the turn.
+import { ChatProtocolError, object } from "./openai-chat-protocol.ts";
+
+export class UnsupportedChatToolsError extends Error {}
+
+export function rejectsToolsParameter(status: number, body: string): boolean {
+ if (status !== 400 && status !== 422) return false;
+ let envelope: Record<string, unknown> | undefined;
+ try { envelope = object(JSON.parse(body)); } catch { return false; }
+ const error = object(envelope?.error);
+ if (error?.param === "tools" && error.code === "unsupported_parameter") return true;
+ const message = error?.message ?? envelope?.error;
+ return typeof message === "string" && (
+ /\bdoes not support (?:tools|tool calling|function calling)(?:[.!]?$|[.!]?\s)/i.test(message) ||
+ /\b(?:tools|tool calling|function calling) (?:is|are) not supported\b/i.test(message) ||
+ /^(?:unsupported|unknown|unrecognized) (?:parameter|field):?\s*['"]?tools['"]?[.!]?$/i.test(message.trim())
+ );
+}
+
+export class UnsupportedReasoningReplayError extends Error {}
+
+/** DeepSeek-style providers need `reasoning_content` echoed on a tool-call message; Groq rejects it. */
+export function rejectsReasoningReplay(status: number, body: string): boolean {
+ if (status !== 400 && status !== 422) return false;
+ let envelope: Record<string, unknown> | undefined;
+ try { envelope = object(JSON.parse(body)); } catch { return false; }
+ const message = object(envelope?.error)?.message ?? envelope?.error;
+ return typeof message === "string" && /\breasoning_content\b/.test(message) &&
+ /\b(?:unsupported|not supported|unknown|unrecognized|unexpected|not permitted|not allowed)\b/i.test(message);
+}
+
+/** Groq fails a completion with `tool_use_failed` when a generated tool call is invalid: usually a
+ * tool it was not offered (gpt-oss inventing a "json" tool), sometimes arguments missing the schema. */
+export class RejectedToolCallError extends ChatProtocolError {
+ readonly refusal: Record<string, unknown>;
+ constructor(message: string, refusal: Record<string, unknown>) {
+ super(message);
+ this.refusal = refusal;
+ }
+}
+
+export const toolCallRefusal = (error: unknown) => {
+ const body = object(error);
+ return body?.code === "tool_use_failed" ? body : undefined;
+};
+
+export function refusedToolCall(status: number, body: string) {
+ if (status !== 400) return undefined;
+ try { return toolCallRefusal(object(JSON.parse(body))?.error); } catch { return undefined; }
+}
+
+export function refusedToolCallFailure(error: RejectedToolCallError, earlierSteps: boolean): string {
+ const words = typeof error.refusal.message === "string" ? error.refusal.message : error.message;
+ const tool = /attempted to call tool '([^']+)'/.exec(words)?.[1];
+ const what = tool ? `tried to use a tool it was not given ("${tool}")` : "made a tool call the provider rejected";
+ const next = earlierSteps
+ ? "The steps before it already ran, so ask only for what's left."
+ : "Nothing ran. Retry; if it keeps happening, rephrase the request or choose another model.";
+ return `The model ${what}. ${next} Provider: ${words.slice(0, 200)}`;
+}
diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.ts
index 6a9aba7ea9..e5aed70893 100644
--- a/server/drivers/openai-chat-tools.test.ts
+++ b/server/drivers/openai-chat-tools.test.ts
@@ -213,7 +213,8 @@ describe("bounded action announcement recovery", () => {
: answer(response, "I'll write the receipt now."));
await f.start({ approvalMode: "full" });
expect(await f.completed()).toMatchObject({ ok: false });
- expect(f.requests).toHaveLength(2);
+ // This fixture is on this machine, so the model is sent back twice to fix the call before the turn ends on it.
+ expect(f.requests).toHaveLength(4);
expect(f.effects()).toEqual([]);
});
@@ -703,7 +704,8 @@ describe.each<Provider>(["openai-compat", "grok", "minimax"])("%s structured too
it("preserves ordinary transcript chat and leaves textual tool imitations as text", async () => {
const imitation = '<tool_call>{"name":"audit_write","arguments":{"value":"pretend"}}</tool_call>';
- const f = await fixture((_body, response) => answer(response, imitation), provider);
+ // Only a hosted model: a server on this machine counts as a local one, covered in openai-chat-local-model.test.ts.
+ const f = await fixture((_body, response) => answer(response, imitation), provider === "openai-compat" ? "grok" : provider);
await f.start({ integrations: undefined, system: "Fixture persona", transcript: [{ role: "user", text: "Earlier question" }, { role: "assistant", text: "Earlier answer" }] });
expect(await f.completed()).toMatchObject({ ok: true });
expect(f.requests).toHaveLength(1);
@@ -1008,9 +1010,9 @@ describe("structured tool execution boundaries", () => {
expect(readFileSync(join(NATIVE_DIR, `${f.threadId}.ndjson`), "utf8")).not.toContain(API_KEY_CANARY);
});
- it("never promotes textual tool syntax into execution, even when that tool is mounted", async () => {
+ it("never promotes a hosted model's textual tool syntax into execution, even when that tool is mounted", async () => {
const imitation = '<tool_call>{"name":"audit_write","arguments":{"name":"receipt","value":"pretend"}}</tool_call>';
- const f = await fixture((_body, response) => answer(response, imitation));
+ const f = await fixture((_body, response) => answer(response, imitation), "grok");
await f.start();
expect(await f.completed()).toMatchObject({ ok: true });
expect(f.requests[0].tools?.some((tool) => tool.function.name === "audit_write")).toBe(true);
@@ -1207,7 +1209,7 @@ describe("structured tool execution boundaries", () => {
it("stops a model that keeps requesting tools after 64 steps, with one next action that does not repeat the steps that ran", async () => {
const f = await fixture((_body, response, round) => sse(response, [
chunk({ tool_calls: [toolCall("audit_write", '{"name":"receipt","value":"done"}', `call_${round}`)] }, "tool_calls"),
- ]));
+ ]), "grok");
const stop = f.instance.adapter.onEvent((event) => {
if (event.type === "request.opened") void f.instance.adapter.respondToRequest(f.threadId, event.requestId!, { behavior: "allow" });
});
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index 939a6624be..d3a4616570 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -19,6 +19,9 @@ import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent,
import { promptHalves, volatileContextNote, withContextNote } from "./prompt-split.ts";
import { createChatToolApproval, refusal } from "./chat-tool-approval.ts";
import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, object, type ChatToolCall } from "./openai-chat-protocol.ts";
+import { refusedToolCall, refusedToolCallFailure, rejectsReasoningReplay, rejectsToolsParameter, RejectedToolCallError, toolCallRefusal, UnsupportedChatToolsError, UnsupportedReasoningReplayError } from "./openai-chat-refusals.ts";
+import { ChatRepeatGuard } from "./chat-repeat-guard.ts";
+import { TextCallHoldback, textToolCalls } from "./chat-text-tool-calls.ts";
import { appendNative } from "./native.ts";
import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS } from "./retry.ts";
import { plainFailureMessage } from "./engine-errors.ts"; import { toolFailureMessage } from "./tool-failure.ts";
@@ -144,6 +147,9 @@ interface RuntimeOptions<Config> {
/** Smaller models announce a step and end the turn without calling a tool; such a reply gets a nudge, at most three
* per turn and each only after tool progress since the last. */
nudgeAnnouncedAction?: boolean;
+ /** A model on this machine or network: read a tool call it wrote as text, stop it repeating itself, and send it back
+ * to fix a failed call instead of ending the turn on it. */
+ localModel?: boolean;
}
const usageFrom = (usage: CompletionJson["usage"]): Usage | null =>
@@ -156,8 +162,6 @@ const completionUsage = (json: CompletionJson) => json.usage ?? json.x_groq?.usa
const asError = (value: unknown): Error =>
value instanceof Error ? value : new Error(String(value));
-class UnsupportedChatToolsError extends Error {}
-
const MAX_CHAT_ROUNDS = 64;
const MAX_TURN_TOOL_CALLS = 200;
const MAX_ANNOUNCEMENT_NUDGES = 3;
@@ -223,55 +227,12 @@ export function announcesAction(text: string): boolean {
/^i(?:['\u2019]m| am)\b[^.!?\n]*\band (?:i )?will\s+(?:launch|open|check|pull|look|search|navigate|read|fetch|load|run|inspect)\b/i.test(reply);
}
+const UNREADABLE_CALL = "[OpenMausBot: your last tool call could not be read, so nothing ran. Call the tool again using only the tools you were given, with valid JSON arguments.]";
+const LOCAL_CORRECTIVE_ROUNDS = 2;
+
const TEXT_ONLY_ATTACHMENT_NOTE = "[The person attached image(s), but this model cannot see images. Say so if the request depends on them.]";
const TEXT_ONLY_SCREENSHOT_NOTE = "[Screenshot not shown: this model cannot see images. Read the page with a snapshot or a text tool instead.]";
-function rejectsToolsParameter(status: number, body: string): boolean {
- if (status !== 400 && status !== 422) return false;
- let envelope: Record<string, unknown> | undefined;
- try { envelope = object(JSON.parse(body)); } catch { return false; }
- const error = object(envelope?.error);
- if (error?.param === "tools" && error.code === "unsupported_parameter") return true;
- const message = error?.message ?? envelope?.error;
- return typeof message === "string" && (
- /\bdoes not support (?:tools|tool calling|function calling)(?:[.!]?$|[.!]?\s)/i.test(message) ||
- /\b(?:tools|tool calling|function calling) (?:is|are) not supported\b/i.test(message) ||
- /^(?:unsupported|unknown|unrecognized) (?:parameter|field):?\s*['"]?tools['"]?[.!]?$/i.test(message.trim())
- );
-}
-
-class UnsupportedReasoningReplayError extends Error {}
-
-/** DeepSeek-style providers need `reasoning_content` echoed on a tool-call message; Groq rejects it. */
-function rejectsReasoningReplay(status: number, body: string): boolean {
- if (status !== 400 && status !== 422) return false;
- let envelope: Record<string, unknown> | undefined;
- try { envelope = object(JSON.parse(body)); } catch { return false; }
- const message = object(envelope?.error)?.message ?? envelope?.error;
- return typeof message === "string" && /\breasoning_content\b/.test(message) &&
- /\b(?:unsupported|not supported|unknown|unrecognized|unexpected|not permitted|not allowed)\b/i.test(message);
-}
-
-/** Groq fails a completion with `tool_use_failed` when a generated tool call is invalid: usually a
- * tool it was not offered (gpt-oss inventing a "json" tool), sometimes arguments missing the schema. */
-class RejectedToolCallError extends ChatProtocolError {
- readonly refusal: Record<string, unknown>;
- constructor(message: string, refusal: Record<string, unknown>) {
- super(message);
- this.refusal = refusal;
- }
-}
-
-const toolCallRefusal = (error: unknown) => {
- const body = object(error);
- return body?.code === "tool_use_failed" ? body : undefined;
-};
-
-function refusedToolCall(status: number, body: string) {
- if (status !== 400) return undefined;
- try { return toolCallRefusal(object(JSON.parse(body))?.error); } catch { return undefined; }
-}
-
function completionError(json: CompletionJson, label: string): ChatProtocolError | null {
const message = providerError(json);
if (!message) return null;
@@ -280,16 +241,6 @@ function completionError(json: CompletionJson, label: string): ChatProtocolError
return refusal ? new RejectedToolCallError(text, refusal) : new ChatProtocolError(text);
}
-function refusedToolCallFailure(error: RejectedToolCallError, earlierSteps: boolean): string {
- const words = typeof error.refusal.message === "string" ? error.refusal.message : error.message;
- const tool = /attempted to call tool '([^']+)'/.exec(words)?.[1];
- const what = tool ? `tried to use a tool it was not given ("${tool}")` : "made a tool call the provider rejected";
- const next = earlierSteps
- ? "The steps before it already ran, so ask only for what's left."
- : "Nothing ran. Retry; if it keeps happening, rephrase the request or choose another model.";
- return `The model ${what}. ${next} Provider: ${words.slice(0, 200)}`;
-}
-
export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>): ProviderInstance {
const { input } = options;
const listeners = new Set<RuntimeEventListener>();
@@ -640,6 +591,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
let nudges = 0;
let unread: string[] = [];
let callsAtNudge = -1;
+ const repeats = options.localModel ? new ChatRepeatGuard() : undefined;
+ let unreadable = false, askedAgain = false;
try {
const parsed = parseToolScope(turn.toolScope);
if (!parsed.ok) throw new Error(parsed.error);
@@ -667,6 +620,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
for (;;) {
let streamed = false;
let answerStreamed = false;
+ const holdback = options.localModel && tools.definitions.length ? new TextCallHoldback() : undefined;
const pending = { assistant_text: "", reasoning_text: "" };
const delta = (text: string, streamKind: keyof typeof pending, flush = false) => {
let combined = pending[streamKind] + text;
@@ -687,8 +641,22 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
completion = await complete(messages, model, true, abort.signal, (text, streamKind) => {
streamed = true;
if (streamKind === "assistant_text") answerStreamed = true;
- delta(text, streamKind);
+ const shown = holdback && streamKind === "assistant_text" ? holdback.feed(text) : text;
+ if (shown) delta(shown, streamKind);
}, tools.definitions);
+ // A reply cut off at the token limit may be a call cut short; running half of one is worse than saying so.
+ const written = holdback && !completion.toolCalls.length && completion.finishReason !== "length" ? textToolCalls(completion.text, tools.definitions) : null;
+ unreadable = written?.kind === "unreadable" && !askedAgain;
+ if (written?.kind === "calls") {
+ completion = { ...completion, text: written.text, toolCalls: written.calls, finishReason: "tool_calls" };
+ native("in", { recovered: "text_tool_calls", calls: written.calls.map((call) => call.function.name) });
+ } else if (unreadable) {
+ completion = { ...completion, text: written!.text };
+ native("in", { recovered: "unreadable_tool_call" });
+ } else {
+ const rest = holdback?.rest();
+ if (rest) delta(rest, "assistant_text");
+ }
delta("", "assistant_text", true);
delta("", "reasoning_text", true);
break;
@@ -749,9 +717,14 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
contextTokens: completion.usage.input + completion.usage.output, ...(contextWindow ? { contextWindow } : {}) });
}
// Reasoning on a tool-call round belongs to the protocol, not a final reply.
- const reply = completion.text.trim() ? completion.text : completion.toolCalls.length ? "" : completion.reasoning;
+ const reply = completion.text.trim() ? completion.text : completion.toolCalls.length || unreadable ? "" : completion.reasoning;
if (reply.trim()) emit({ ...base(turn.threadId, turnId), type: "item.completed", itemType: "assistant_text", text: safeText(reply) });
abort.signal.throwIfAborted();
+ if (unreadable) {
+ askedAgain = true;
+ messages.push(assistantReply(model, completion, completion.text), { role: "user", content: UNREADABLE_CALL });
+ continue;
+ }
if (!completion.toolCalls.length) {
if (!reply.trim()) throw new ChatProtocolError("provider returned an empty response");
if (completion.finishReason && completion.finishReason !== "stop") {
@@ -759,7 +732,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
}
if (toolFailed) {
// A person's "no" is never answered with another attempt; a failure may first get the configured corrective rounds.
- if (!denials.length && !turnEntry.ending && correctiveRounds < (turn.toolErrorCorrectiveRounds ?? 0)) {
+ if (!denials.length && !turnEntry.ending && correctiveRounds < Math.max(turn.toolErrorCorrectiveRounds ?? 0, options.localModel ? LOCAL_CORRECTIVE_ROUNDS : 0)) {
correctiveRounds += 1;
messages.push({ role: "user", content: CORRECTIVE_ROUND });
continue;
@@ -796,14 +769,15 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
}
if (seenCalls.size > MAX_TURN_TOOL_CALLS) throw new ChatProtocolError(stoppedAfter(`${MAX_TURN_TOOL_CALLS} tool calls`));
messages.push({ ...assistantReply(model, completion, completion.text || null), tool_calls: completion.toolCalls });
- // After a corrective round, the failure stays pending only until the bot runs tools again.
- if (correctiveRounds && !denials.length) { toolFailed = false; failedCalls.length = 0; }
+ // After a corrective round, the failure stays pending only until the bot runs tools again. A local model that
+ // went on to use more tools has already reacted: a wrong guess, a search, then the right call is not a failed turn.
+ if ((correctiveRounds || options.localModel) && !denials.length) { toolFailed = false; failedCalls.length = 0; }
const screenshotParts: ChatContentPart[] = [];
for (const call of completion.toolCalls) {
abort.signal.throwIfAborted();
let result: ChatToolResult;
let started = false;
- let fatal: Error | undefined, title = call.function.name;
+ let fatal: Error | undefined, title = call.function.name, skipRepeatCount = false;
try {
let args: unknown;
try { args = JSON.parse(call.function.arguments); }
@@ -832,6 +806,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
}
}
} else {
+ const refused = repeats?.refuses(call.function.name, call.function.arguments);
+ if (refused) { skipRepeatCount = true; throw new Error(refused); }
tools.validate(call.function.name, args);
const shown = tools.view(call.function.name, args as Record<string, unknown>); title = shown.title;
const shownPreview = shown.input === args ? inputPreview : preview(shown.input);
@@ -871,14 +847,16 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
: safeText(asError(error).message).slice(0, 2_000) };
}
if (!started) emit({ ...base(turn.threadId, turnId), type: "item.started", itemType: "tool", itemId: call.id, title: call.function.name });
+ const repeatNote = skipRepeatCount ? undefined : repeats?.noteAfter(call.function.name, call.function.arguments, result);
const text = safeText(result.text);
const output = preview({ ok: result.ok, result: text });
emit({ ...base(turn.threadId, turnId), type: "item.completed", itemType: "tool", itemId: call.id, ok: result.ok, output });
if (!result.ok) { toolFailed = true; failedCalls.push(title); }
- messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify({ ok: result.ok, result: text }) });
+ messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify({ ok: result.ok, result: repeatNote ? `${text}\n\n${repeatNote}` : text }) });
screenshotParts.push(...chatToolImages(call.id, result.images));
abort.signal.throwIfAborted();
if (fatal) throw fatal;
+ if (repeats?.stopped) { stopReason = "incomplete_action"; throw new ChatProtocolError(repeats.stopped); }
}
if (screenshotParts.length) messages.push({ role: "user", content: screenshotParts });
}
diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.ts
index 353458411d..4150faa45e 100644
--- a/server/drivers/openai-compat.ts
+++ b/server/drivers/openai-compat.ts
@@ -298,7 +298,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {
missingKeyError: missingKey,
unavailableReason: missingKey,
timeoutMs: config.replyWaitMinutes ? config.replyWaitMinutes * 60_000 : idleTimeoutMs(),
- ...(onThisNetwork(config.url) ? { livenessEveryMs: livenessEveryMs() } : {}),
+ ...(onThisNetwork(config.url) ? { livenessEveryMs: livenessEveryMs(), localModel: true } : {}),
reasoning: true,
billing: "metered",
includeUsageInCompleted: true,