1
import { parse as partialParse } from "partial-json";2
import type { ToolCall } from "../types.ts";4
const VALID_JSON_ESCAPES = new Set(['"', "\\", "/", "b", "f", "n", "r", "t"]);6
function isControlCharacter(char: string): boolean {7
const codePoint = char.codePointAt(0);8
return codePoint !== undefined && codePoint >= 0x00 && codePoint <= 0x1f;9
}11
function escapeControlCharacter(char: string): string {12
switch (char) {13
case "\b":14
return "\\b";15
case "\f":16
return "\\f";17
case "\n":18
return "\\n";19
case "\r":20
return "\\r";21
case "\t":22
return "\\t";23
default:24
return `\\u${char.codePointAt(0)?.toString(16).padStart(4, "0") ?? "0000"}`;25
}26
}28
/**29
* Repairs malformed JSON string literals by:30
* - escaping raw control characters inside strings31
* - doubling backslashes before invalid escape characters32
*/33
export function repairJson(json: string): string {34
let repaired = "";35
let inString = false;37
for (let index = 0; index < json.length; index++) {38
const char = json[index];40
if (!inString) {41
repaired += char;42
if (char === '"') {43
inString = true;44
}45
continue;46
}48
if (char === '"') {49
repaired += char;50
inString = false;51
continue;52
}54
if (char === "\\") {55
const nextChar = json[index + 1];56
if (nextChar === undefined) {57
repaired += "\\\\";58
continue;59
}61
if (nextChar === "u") {62
const unicodeDigits = json.slice(index + 2, index + 6);63
if (/^[0-9a-fA-F]{4}$/.test(unicodeDigits)) {64
repaired += `\\u${unicodeDigits}`;65
index += 5;66
continue;67
}68
}70
if (VALID_JSON_ESCAPES.has(nextChar)) {71
repaired += `\\${nextChar}`;72
index += 1;73
continue;74
}76
repaired += "\\\\";77
continue;78
}80
repaired += isControlCharacter(char) ? escapeControlCharacter(char) : char;81
}83
return repaired;84
}86
export function parseJsonWithRepair<T>(json: string): T {87
try {88
return JSON.parse(json) as T;89
} catch (error) {90
const repairedJson = repairJson(json);91
if (repairedJson !== json) {92
return JSON.parse(repairedJson) as T;93
}94
throw error;95
}96
}98
/**99
* Parses the model's complete arguments text of a finished tool call.100
*101
* Unlike {@link parseStreamingJson}, this never keeps a partially parsed prefix: once the call is102
* finished, text that is not a valid JSON object means the model sent malformed arguments. In that103
* case `arguments` is `{}` and `argumentsError` describes the problem, including the text the104
* model sent, so tool validation can report it back to the model.105
*/106
export function parseToolCallArguments(json: string | undefined): Pick<ToolCall, "arguments" | "argumentsError"> {107
if (!json?.trim()) return { arguments: {} };108
try {109
const parsed = parseJsonWithRepair<ToolCall["arguments"] | null>(json);110
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {111
throw new Error("Tool arguments must be a JSON object");112
}113
return { arguments: parsed };114
} catch (error) {115
return {116
arguments: {},117
argumentsError: `${error instanceof Error ? error.message : String(error)}\n\nReceived arguments:\n${json}`,118
};119
}120
}122
/**123
* Attempts to parse potentially incomplete JSON during streaming.124
* Always returns a valid object, even if the JSON is incomplete.125
*126
* @param partialJson The partial JSON string from streaming127
* @returns Parsed object or empty object if parsing fails128
*/129
export function parseStreamingJson<T = Record<string, unknown>>(partialJson: string | undefined): T {130
if (!partialJson || partialJson.trim() === "") {131
return {} as T;132
}134
try {135
return parseJsonWithRepair<T>(partialJson);136
} catch {137
try {138
const result = partialParse(partialJson);139
return (result ?? {}) as T;140
} catch {141
try {142
const result = partialParse(repairJson(partialJson));143
return (result ?? {}) as T;144
} catch {145
return {} as T;146
}147
}148
}149
}