Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
/**
* Tool Call Recovery Module
*
* Handles recovery from malformed tool calls generated by local models:
* text-based tool call extraction (parse JSON/XML from text), and validation of
* a call's arguments against the tool's own JSON Schema.
*
* It does NOT invent arguments. It used to: `inferMissingParameters` filled a
* missing `Glob.pattern` with `**\/*` (walks the whole tree), took `Task.prompt`
* from "the last meaningful sentence" of the model's prose, and rewrote
* `subagent_type` against a hardcoded list of eight agent names that claudish
* cannot discover and that was already stale. A MISSING argument surfaces as a
* visible harness error; a FABRICATED one is a confident wrong action with no
* error anywhere. The codebase already prices that asymmetry the same way for
* tool `pattern` constraints (`ai-docs/architecture/adapters.md:471-474`), and
* the inference is gone for the same reason.
*
* What survives is only what RENAMES OR TYPES A VALUE THE MODEL SUPPLIED —
* see `schema-validate.ts`.
*/
import { TOOL_NAME_SHAPE, TOOL_NAME_SOURCE } from "../../adapters/tool-name-utils.js";
import { log } from "../../logger.js";
import {
type JsonSchemaNode,
applySchemaDefaults,
coerceToSchema,
missingRequired,
renameToDeclaredKeys,
} from "./schema-validate.js";
export interface ExtractedToolCall {
name: string;
arguments: Record<string, any>;
source: "structured" | "json_text" | "xml_text" | "inferred";
}
export interface ToolSchema {
name: string;
description?: string;
input_schema?: {
type: string;
properties?: Record<string, any>;
required?: string[];
};
}
/**
* A tool name is an identifier, so the extractors must never accept anything else.
*
* Pattern 0 below used to capture `[^>]+`, which accepts every character except
* `>`. A model that opened `<function=` in prose and closed it 80 characters
* later had all 80 characters taken as the tool name — parameter names, type
* fragments and ARGUMENT VALUES included. One such name reached a client:
* `web_search_query_listOpposed["macos security add-generic-password …"]`.
* See `ai-docs/reports/grok-tool-name-mangling-20260827.md`.
*/
const FUNCTION_TAG_SOURCE = `<function=(${TOOL_NAME_SOURCE})>([\\s\\S]*?)(?=<function=|$)`;
/** Unanchored, no `g` flag, so it holds no `lastIndex` and is safe to share. */
const FUNCTION_TAG_PRESENT = new RegExp(`<function=${TOOL_NAME_SOURCE}>`);
/**
* Does this text hold a `<function=NAME>` tag Pattern 0 can actually extract?
*
* Exported so the openai-sse hold-back test uses the SAME shape the extractor
* uses. When the two drifted, text matching the loose hold-back test but not the
* extractor was withheld from the client and then never emitted at all: a silent
* text loss with no tool call to show for it. Called once per streamed chunk, so
* the pattern is built once at module load rather than per call.
*/
export function hasExtractableFunctionTag(text: string): boolean {
return FUNCTION_TAG_PRESENT.test(text);
}
/**
* Drop extracted calls that are not real tools.
*
* Three steps, and the ORDER is the design:
*
* 1. **Shape.** Reject a name that is not an identifier — this is how a
* swallowed argument value is caught. It runs on the name as it came off
* the WIRE, which is the only name `TOOL_NAME_SHAPE`'s 64-character bound
* describes.
* 2. **Decode.** On a wire that renames tools, the model wrote the encoded
* name; the client's own name may legitimately be longer than the wire
* allows. Decoding before step 1 would fail a real 65-character MCP name on
* a shape rule that was never about it.
* 3. **Allowlist.** Reject a well-shaped name the client never advertised —
* this is how a hallucinated tool is caught. The allowlist is the request's
* own tool list, so it is exact rather than a hardcoded tool list.
*/
function keepOnlyRealTools(
extracted: ExtractedToolCall[],
knownToolNames?: string[],
decodeToolName?: (name: string) => string
): ExtractedToolCall[] {
const kept: ExtractedToolCall[] = [];
for (const call of extracted) {
if (!TOOL_NAME_SHAPE.test(call.name)) {
log(
`[ToolRecovery] Dropped extracted call: name is not an identifier: ${JSON.stringify(
call.name.slice(0, 120)
)}`
);
continue;
}
const decoded = decodeToolName ? decodeToolName(call.name) : call.name;
const named = decoded === call.name ? call : { ...call, name: decoded };
if (!knownToolNames || knownToolNames.length === 0) {
kept.push(named);
continue;
}
const canonical = knownToolNames.find((t) => t.toLowerCase() === named.name.toLowerCase());
if (!canonical) {
log(`[ToolRecovery] Dropped extracted call for unadvertised tool: ${named.name}`);
continue;
}
kept.push(canonical === named.name ? named : { ...named, name: canonical });
}
return kept;
}
/** `<function=NAME>` at exactly the cursor. Sticky, so it cannot skip ahead. */
const FUNCTION_TAG_AT_CURSOR = new RegExp(`<function=(${TOOL_NAME_SOURCE})>`, "y");
/** `<parameter=NAME>` at exactly the cursor, inside a function block. */
const PARAMETER_TAG_AT_CURSOR = /<parameter=([^>\s]+)>/y;
/** `<tool_call>` at exactly the cursor, with any whitespace after it. Sticky. */
const TOOL_CALL_OPEN_AT_CURSOR = /<tool_call>\s*/y;
const TOOL_CALL_CLOSE_TAG = "</tool_call>";
/**
* Unwrap the `<tool_call>` envelope Qwen- and Hermes-family models put around a
* function-tag block, so the envelope parser below sees the shape it was written
* for.
*
* This is an ENTRY condition, not a parser change. The wrapped form
*
* <tool_call><function=get_weather><parameter=city>Paris</parameter></function></tool_call>
*
* failed `startsWith("<function=")`, fell through to the six loose regex
* patterns, and came out as `{"city":"Paris</parameter></function></tool_call>"}`
* — the closing tags swallowed into the value, silently, and a tool then ran on
* the corrupted argument. Measured live against the published 9.5.0 binary; the
* same input without the wrapper produced `{"city":"Paris"}`.
*
* The wrapper is REMOVED here rather than tolerated inside the parser, which is
* what keeps `</tool_call>` out of the last parameter's value: the parameter
* value scanner stops at `</parameter>`, `</function>`, `<parameter=` and
* `<function=`, and nothing it can see afterwards belongs to any value.
*
* Multiple wrapped calls in one response fall out of the same loop: each block
* is unwrapped in turn and they are rejoined, so the existing "a block ends at
* the next `<function=`" rule handles the boundary.
*
* Returns `null` — declining, so the caller keeps the original text — for
* anything that is not exactly this shape: a leading `<tool_call>` that wraps
* something other than a function tag (Pattern 1's JSON payload is precisely
* that), or trailing content after the last `</tool_call>`. An UNTERMINATED
* wrapper is accepted, because a truncated stream is a real capture and the
* block inside it is still unambiguous.
*/
function unwrapToolCallTags(body: string): string | null {
if (!body.startsWith("<tool_call>")) return null;
const blocks: string[] = [];
let cursor = 0;
while (cursor < body.length) {
TOOL_CALL_OPEN_AT_CURSOR.lastIndex = cursor;
if (!TOOL_CALL_OPEN_AT_CURSOR.exec(body)) return null;
cursor = TOOL_CALL_OPEN_AT_CURSOR.lastIndex;
const close = body.indexOf(TOOL_CALL_CLOSE_TAG, cursor);
const block = (close === -1 ? body.slice(cursor) : body.slice(cursor, close)).trim();
if (!block.startsWith("<function=")) return null;
blocks.push(block);
if (close === -1) break;
cursor = close + TOOL_CALL_CLOSE_TAG.length;
cursor += /^\s*/.exec(body.slice(cursor))?.[0].length ?? 0;
}
return blocks.length > 0 ? blocks.join("\n") : null;
}
/**
* Parse a response that is ENTIRELY a `<function=NAME><parameter=P>V` envelope.
*
* Returns `null` the moment anything else appears, and that strictness is the
* whole point: it is what makes running this BEFORE the six loose regex
* patterns safe. Prose that merely mentions a function tag — a model explaining
* the format, or quoting a previous turn — does not match, so it cannot
* short-circuit anything.
*
* The loose Pattern 0 that still runs afterwards has a different failure mode: it
* scans anywhere in the text, so it takes the *last* value of a repeated
* parameter and swallows a trailing `</function>` into the value. Parsed as an
* envelope, both are handled — the block is delimited rather than guessed at.
*
* Nothing here relaxes the two gates. The name must be an identifier
* (`TOOL_NAME_SOURCE`), and the caller's own advertised tool list still filters
* the result through `keepOnlyRealTools`.
*
* NOT ADOPTED, deliberately: the upstream heuristic that reads a WebSearch call
* out of ordinary prose. It dispatches a tool from a sentence that only
* describes one.
*/
export function parseFunctionTagEnvelope(text: string): ExtractedToolCall[] | null {
const trimmed = text.trim();
if (trimmed.length === 0) return null;
// The `<tool_call>` wrapper is stripped BEFORE the strict test, never parsed
// through: see `unwrapToolCallTags`.
const body = unwrapToolCallTags(trimmed) ?? trimmed;
if (!body.startsWith("<function=")) return null;
const calls: ExtractedToolCall[] = [];
let cursor = 0;
while (cursor < body.length) {
FUNCTION_TAG_AT_CURSOR.lastIndex = cursor;
const open = FUNCTION_TAG_AT_CURSOR.exec(body);
if (!open) return null;
cursor = FUNCTION_TAG_AT_CURSOR.lastIndex;
const args: Record<string, any> = {};
// Parameters, until the block ends. A block ends at `</function>`, at the
// next `<function=`, or at the end of the text — models emit all three.
while (cursor < body.length) {
const rest = body.slice(cursor);
const closeLen = /^\s*<\/function>/.exec(rest)?.[0].length;
if (closeLen !== undefined) {
cursor += closeLen;
break;
}
if (/^\s*<function=/.test(rest)) break;
const lead = /^\s*/.exec(rest)?.[0].length ?? 0;
PARAMETER_TAG_AT_CURSOR.lastIndex = cursor + lead;
const param = PARAMETER_TAG_AT_CURSOR.exec(body);
// Anything that is not a parameter tag means this is not an envelope.
if (!param) return null;
let valueStart = PARAMETER_TAG_AT_CURSOR.lastIndex;
// A newline directly after the tag is formatting, not content.
if (body[valueStart] === "\n") valueStart += 1;
const tail = body.slice(valueStart);
const end = /<\/parameter>|<\/function>|<parameter=|<function=/.exec(tail);
const raw = end ? tail.slice(0, end.index) : tail;
args[param[1]] = raw.trim();
cursor = valueStart + raw.length;
const consumedClose = /^<\/parameter>/.exec(body.slice(cursor))?.[0].length;
if (consumedClose !== undefined) cursor += consumedClose;
}
calls.push({ name: open[1], arguments: args, source: "xml_text" });
const gap = /^\s*/.exec(body.slice(cursor))?.[0].length ?? 0;
cursor += gap;
}
return calls.length > 0 ? calls : null;
}
/** Give one extracted call's arguments the shape its own schema declares. */
function normalizeAgainstSchema(
call: ExtractedToolCall,
toolSchemas?: ToolSchema[]
): ExtractedToolCall {
const schema = toolSchemas?.find((t) => t.name === call.name)?.input_schema as
| JsonSchemaNode
| undefined;
if (!schema) return call;
const renamed = renameToDeclaredKeys(schema, call.arguments);
const defaulted = applySchemaDefaults(schema, renamed.args);
const coerced = coerceToSchema(schema, defaulted.args);
if (renamed.renamed.length + defaulted.applied.length + coerced.coerced.length === 0) {
return call;
}
log(
`[ToolRecovery] Normalized ${call.name} against its schema: ` +
`renamed=[${renamed.renamed}] defaults=[${defaulted.applied}] coerced=[${coerced.coerced}]`
);
return { ...call, arguments: coerced.args as Record<string, any> };
}
/**
* Extract tool calls from text content
* Many local models output tool calls as JSON in their text rather than using structured tool_calls
*
* `knownToolNames` is the tool list the client advertised on THIS request. Pass
* it whenever it is in hand: every pattern below is then held to it, not just
* the natural-language one.
*
* `toolSchemas`, when supplied, types the extracted values: the envelope format
* carries no types, so every value arrives as a string.
*
* `decodeToolName`, when supplied, turns the name the MODEL wrote back into the
* client's own. The model was given the encoded tool list, so on a renaming wire
* every recovered call carries an encoded name that `knownToolNames` — built
* from the client's originals — would otherwise reject in silence.
*/
export function extractToolCallsFromText(
text: string,
knownToolNames?: string[],
toolSchemas?: ToolSchema[],
decodeToolName?: (name: string) => string
): ExtractedToolCall[] {
// Tried FIRST, and short-circuits: a response that is nothing but function
// tags is unambiguous, and reading it as a delimited envelope beats six
// regexes scanning for fragments of one.
const envelope = parseFunctionTagEnvelope(text);
if (envelope) {
return keepOnlyRealTools(envelope, knownToolNames, decodeToolName).map((call) =>
normalizeAgainstSchema(call, toolSchemas)
);
}
const extracted: ExtractedToolCall[] = [];
// Pattern 0: Qwen-style function calls <function=NAME><parameter=PARAM>VALUE
// Example: <function=SlashCommand><parameter=command>/ls -la
// Fresh instance per call: a `g` regex carries `lastIndex` across calls.
const qwenPattern = new RegExp(FUNCTION_TAG_SOURCE, "gi");
let match: RegExpExecArray | null;
// biome-ignore lint/suspicious/noAssignInExpressions: canonical RegExp.exec() iteration idiom
while ((match = qwenPattern.exec(text)) !== null) {
const funcName = match[1];
const paramsText = match[2];
const args: Record<string, any> = {};
// Extract parameters: <parameter=name>value
const paramPattern = /<parameter=([^>]+)>\s*([\s\S]*?)(?=<parameter=|<function=|$)/gi;
let paramMatch: RegExpExecArray | null;
// biome-ignore lint/suspicious/noAssignInExpressions: canonical RegExp.exec() iteration idiom
while ((paramMatch = paramPattern.exec(paramsText)) !== null) {
const paramName = paramMatch[1];
const paramValue = paramMatch[2].trim();
args[paramName] = paramValue;
}
if (funcName) {
extracted.push({
name: funcName,
arguments: args,
source: "xml_text",
});
log(`[ToolRecovery] Extracted Qwen-style tool call: ${funcName}`);
}
}
// Pattern 1: XML-style tool calls <tool_call>{"name": "...", "arguments": {...}}</tool_call>
const xmlPattern = /<tool_call>\s*(\{[\s\S]*?\})\s*<\/tool_call>/gi;
// biome-ignore lint/suspicious/noAssignInExpressions: canonical RegExp.exec() iteration idiom
while ((match = xmlPattern.exec(text)) !== null) {
try {
const parsed = JSON.parse(match[1]);
if (parsed.name) {
extracted.push({
name: parsed.name,
arguments: parsed.arguments || parsed.input || parsed.parameters || {},
source: "xml_text",
});
}
} catch (e) {
// Continue trying other patterns
}
}
// Pattern 2: Function call format {"name": "tool_name", "arguments": {...}}
const funcCallPattern =
/\{\s*"name"\s*:\s*"([^"]+)"\s*,\s*"(?:arguments|input|parameters)"\s*:\s*(\{[\s\S]*?\})\s*\}/gi;
// biome-ignore lint/suspicious/noAssignInExpressions: canonical RegExp.exec() iteration idiom
while ((match = funcCallPattern.exec(text)) !== null) {
try {
const args = JSON.parse(match[2]);
extracted.push({
name: match[1],
arguments: args,
source: "json_text",
});
} catch (e) {
// Continue
}
}
// Pattern 2b: Alternative format {"tool": "tool_name", "tool_input": {...}}
// Some models (like Qwen) output this format instead
const toolInputPattern =
/\{\s*"tool"\s*:\s*"([^"]+)"\s*,\s*"tool_input"\s*:\s*(\{[\s\S]*?\})\s*\}/gi;
// biome-ignore lint/suspicious/noAssignInExpressions: canonical RegExp.exec() iteration idiom
while ((match = toolInputPattern.exec(text)) !== null) {
try {
const args = JSON.parse(match[2]);
extracted.push({
name: match[1],
arguments: args,
source: "json_text",
});
log(`[ToolRecovery] Extracted tool/tool_input format: ${match[1]}`);
} catch (e) {
// Continue
}
}
// Pattern 3: Anthropic-style tool_use blocks in text
const anthropicPattern =
/\{\s*"type"\s*:\s*"tool_use"\s*,\s*"id"\s*:\s*"[^"]*"\s*,\s*"name"\s*:\s*"([^"]+)"\s*,\s*"input"\s*:\s*(\{[\s\S]*?\})\s*\}/gi;
// biome-ignore lint/suspicious/noAssignInExpressions: canonical RegExp.exec() iteration idiom
while ((match = anthropicPattern.exec(text)) !== null) {
try {
const args = JSON.parse(match[2]);
extracted.push({
name: match[1],
arguments: args,
source: "json_text",
});
} catch (e) {
// Continue
}
}
// Pattern 3b: OpenAI tool_call format in array
// [{"type":"tool_call","id":"...","tool_call":{"name":"...","arguments":{...}}}]
const openaiArrayPattern =
/\{\s*"type"\s*:\s*"tool_call"\s*,\s*"id"\s*:\s*"[^"]*"\s*,\s*"tool_call"\s*:\s*\{\s*"name"\s*:\s*"([^"]+)"\s*,\s*"arguments"\s*:\s*(\{[\s\S]*?\})\s*\}\s*\}/gi;
// biome-ignore lint/suspicious/noAssignInExpressions: canonical RegExp.exec() iteration idiom
while ((match = openaiArrayPattern.exec(text)) !== null) {
try {
const args = JSON.parse(match[2]);
extracted.push({
name: match[1],
arguments: args,
source: "json_text",
});
log(`[ToolRecovery] Extracted OpenAI tool_call format: ${match[1]}`);
} catch (e) {
// Continue
}
}
// Pattern 4: Simple JSON objects that look like tool calls (heuristic)
// Look for JSON with common tool parameter names
const jsonBlockPattern = /```(?:json)?\s*(\{[\s\S]*?\})\s*```/gi;
// biome-ignore lint/suspicious/noAssignInExpressions: canonical RegExp.exec() iteration idiom
while ((match = jsonBlockPattern.exec(text)) !== null) {
try {
const parsed = JSON.parse(match[1]);
// Check if it looks like a tool call
if (parsed.name && (parsed.arguments || parsed.input || parsed.parameters)) {
extracted.push({
name: parsed.name,
arguments: parsed.arguments || parsed.input || parsed.parameters,
source: "json_text",
});
}
} catch (e) {
// Continue
}
}
// Pattern 5: Natural language tool intent extraction
// Matches: "I'll use the Task tool with subagent_type=Explore"
// Matches: "I will use the Read tool to read /path/to/file"
// Matches: "Let me use the Bash tool to run ls -la"
// The caller's own tool list is exact; this fixed list is the fallback for callers
// that have none in hand. Natural-language extraction is the loosest pattern
// here, so it keeps its own guard even though `keepOnlyRealTools` runs after.
const knownTools =
knownToolNames && knownToolNames.length > 0
? knownToolNames
: [
"Task",
"Read",
"Write",
"Edit",
"Bash",
"Grep",
"Glob",
"WebFetch",
"WebSearch",
"ToolSearch",
];
const nlPatterns = [
// "I'll use the X tool with param=value" - ends with period, colon, newline, or end
/(?:I(?:'ll| will| am going to)|Let me|Going to)\s+use\s+(?:the\s+)?(\w+)\s+tool\s+(?:with\s+)?(.+?)(?:[.:\n]|$)/gi,
// "use X tool to do something"
/use\s+(?:the\s+)?(\w+)\s+tool\s+(?:to\s+)?(.+?)(?:[.:\n]|$)/gi,
];
for (const pattern of nlPatterns) {
pattern.lastIndex = 0; // Reset regex state
// biome-ignore lint/suspicious/noAssignInExpressions: canonical RegExp.exec() iteration idiom
while ((match = pattern.exec(text)) !== null) {
const toolName = match[1];
const paramText = match[2];
// Only extract if it's a known tool
if (!knownTools.some((t) => t.toLowerCase() === toolName.toLowerCase())) {
continue;
}
// Normalize tool name
const normalizedToolName =
knownTools.find((t) => t.toLowerCase() === toolName.toLowerCase()) || toolName;
const args: Record<string, any> = {};
// Extract key=value pairs. This is the ONLY argument source here: a value
// the model wrote down, under the name the model gave it.
//
// The per-tool synthesis that used to follow is deleted. It read arguments
// out of the surrounding prose — `Bash.command` from the words after "run",
// `Task.prompt` from the words after "to", `Grep.pattern` from the words
// after "search" — and, failing that, made them up. A sentence merely
// DESCRIBING a tool then dispatched that tool with invented arguments.
const kvPattern = /(\w+)\s*=\s*["']?([^"',\s]+)["']?/g;
let kvMatch: RegExpExecArray | null;
// biome-ignore lint/suspicious/noAssignInExpressions: canonical RegExp.exec() iteration idiom
while ((kvMatch = kvPattern.exec(paramText)) !== null) {
args[kvMatch[1]] = kvMatch[2];
}
// Only add if we extracted meaningful arguments
if (Object.keys(args).length > 0) {
extracted.push({
name: normalizedToolName,
arguments: args,
source: "inferred",
});
log(
`[ToolRecovery] Extracted natural language tool intent: ${normalizedToolName} with args: ${JSON.stringify(args)}`
);
}
}
}
return keepOnlyRealTools(extracted, knownToolNames, decodeToolName);
}
/**
* Validate a tool call's arguments against the tool's own JSON Schema.
*
* `repaired: true` means, and only means, that a schema `default` was applied or
* a supplied value was moved onto the key the schema declares. It must never
* again mean "invented": the inference that used to set it is deleted (see the
* file header).
*
* Coercion runs on every call but does NOT set `repaired`. It changes a value's
* type, never whether the call would have succeeded, and `repaired` drives a
* path in `openai-sse.ts` that supersedes an already-streamed tool block with a
* second one — a flag that fires on ordinary valid calls would mint duplicate
* blocks for nothing.
*
* `valid: false` therefore means the model genuinely omitted a required
* argument, which the caller surfaces to the user as a visible failure rather
* than guessing.
*/
export function validateAndRepairToolCall(
toolName: string,
argsStr: string,
toolSchemas: ToolSchema[],
textContent?: string
): {
valid: boolean;
args: Record<string, any>;
repaired: boolean;
missingParams: string[];
} {
const schema = toolSchemas.find((t) => t.name === toolName);
if (!schema?.input_schema) {
return { valid: true, args: {}, repaired: false, missingParams: [] };
}
let parsedArgs: Record<string, any> = {};
try {
parsedArgs = argsStr ? JSON.parse(argsStr) : {};
} catch (e) {
// Try to extract from text if structured parsing failed
if (textContent) {
const extracted = extractToolCallsFromText(
textContent,
toolSchemas.map((t) => t.name),
toolSchemas
);
const matching = extracted.find((tc) => tc.name === toolName);
if (matching) {
parsedArgs = matching.arguments;
log(`[ToolRecovery] Extracted tool args from text for ${toolName}`);
}
}
}
const input = schema.input_schema as JsonSchemaNode;
// Rename first — a value under a synonym has to land on the declared key
// before anything asks whether that key is absent. Then defaults, which are
// the client's own declaration. Then types, over the final set.
const renamed = renameToDeclaredKeys(input, parsedArgs);
const defaulted = applySchemaDefaults(input, renamed.args);
const coerced = coerceToSchema(input, defaulted.args);
const args = coerced.args as Record<string, any>;
const repaired = renamed.renamed.length > 0 || defaulted.applied.length > 0;
if (repaired) {
log(
`[ToolRecovery] ${toolName}: applied schema defaults [${defaulted.applied}] ` +
`and key renames [${renamed.renamed}] — nothing was invented`
);
}
if (coerced.coerced.length > 0) {
log(`[ToolRecovery] ${toolName}: coerced to declared types [${coerced.coerced}]`);
}
const missingParams = missingRequired(input, args);
if (missingParams.length === 0) {
return { valid: true, args, repaired, missingParams: [] };
}
return { valid: false, args, repaired: false, missingParams };
}