-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.ts
More file actions
277 lines (262 loc) · 8.66 KB
/
Copy pathparser.ts
File metadata and controls
277 lines (262 loc) · 8.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/**
* Tool-call parser for OpenAI/OpenRouter function-calling responses.
*
* Given a chat completion message with `tool_calls`:
*
* [{ id, type: "function", function: { name, arguments } }]
*
* returns parsed { id, name, args } with `arguments` JSON.parsed. On a JSON
* parse failure we try a best-effort partial-json extraction (balanced-brace
* recovery then key/value scavenging); if that also fails, the call is marked
* with a `parseError` and the loop feeds an error result back to the model.
*
* A message with zero tool_calls yields an empty array (text-only reply).
*/
import type { ChatMessage, ChatToolCall, ParsedToolCall } from "./types.js"
export function parseToolCalls(message: ChatMessage): ParsedToolCall[] {
const calls = message.tool_calls
if (!calls || calls.length === 0) {
return []
}
return calls
.filter((call) => call.type === "function" || !call.type)
.map((call, index) => parseToolCall(call, index))
}
export function parseToolCall(call: ChatToolCall, index = 0): ParsedToolCall {
const id = call.id || `call_${index}`
const name = call.function?.name || "unknown_tool"
const rawArguments = call.function?.arguments ?? ""
let args: Record<string, unknown> = {}
let parseError: string | undefined
const trimmed = rawArguments.trim()
if (trimmed === "") {
// Empty arguments are allowed for some tools; treat as {}.
args = {}
} else {
try {
const parsed: unknown = JSON.parse(trimmed)
if (isPlainObject(parsed)) {
args = parsed as Record<string, unknown>
} else {
parseError = "arguments JSON did not parse to an object"
}
} catch (jsonErr) {
const recovered = bestEffortPartialJson(trimmed)
if (recovered) {
args = recovered
} else {
parseError = `invalid JSON arguments: ${jsonErr instanceof Error ? jsonErr.message : String(jsonErr)}`
}
}
}
return { id, name, args, rawArguments, parseError }
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
/**
* Best-effort extraction of an object from malformed JSON. Tries:
* 1. Balanced-brace recovery: slice from the first "{" to the outermost "}"
* and JSON.parse the substrings at each depth — this handles trailing
* junk like `{"path": "x"} and then some`.
* 2. Key/value scavenging: regex over `"key": value` pairs (strings,
* numbers, booleans, null) — handles truncated tail `{"path": "x", "lim`.
*
* Returns undefined when nothing usable is found.
*/
export function bestEffortPartialJson(input: string): Record<string, unknown> | undefined {
// 1. Balanced-brace recovery.
const firstBrace = input.indexOf("{")
if (firstBrace !== -1) {
let depth = 0
for (let i = firstBrace; i < input.length; i++) {
const ch = input[i]
if (ch === "{") {
depth++
} else if (ch === "}") {
depth--
if (depth === 0) {
const candidate = input.slice(firstBrace, i + 1)
try {
const parsed: unknown = JSON.parse(candidate)
if (isPlainObject(parsed)) {
return parsed as Record<string, unknown>
}
} catch {
// fall through to scavenging
}
break
}
}
}
}
// 2. Key/value scavenging.
const scavenged: Record<string, unknown> = {}
const pairRe = /"((?:\\.|[^"\\])*)"\s*:\s*("(?:\\.|[^"\\])*"|true|false|null|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g
let match: RegExpExecArray | null
let found = false
while ((match = pairRe.exec(input)) !== null) {
const key = unescapeJsonString(match[1])
const rawValue = match[2]
let value: unknown
if (rawValue.startsWith('"')) {
value = unescapeJsonString(rawValue.slice(1, -1))
} else if (rawValue === "true") {
value = true
} else if (rawValue === "false") {
value = false
} else if (rawValue === "null") {
value = null
} else {
const num = Number(rawValue)
value = Number.isNaN(num) ? rawValue : num
}
scavenged[key] = value
found = true
}
return found ? scavenged : undefined
}
function unescapeJsonString(s: string): string {
return s.replace(/\\"/g, '"').replace(/\\\\/g, "\\").replace(/\\n/g, "\n").replace(/\\t/g, "\t")
}
/**
* Recovers a tool call a model wrote as plain text instead of using the
* native tool-calling channel — observed live against Qwen2.5-Coder-14B
* (2026-08-19 local-backend baseline runs, see
* plans/local-dual-model-code-agent.md's handoff doc): the model reasons
* correctly about which tool to call, then emits `{"name": "edit_file",
* "arguments": {...}}` as prose (sometimes fenced in ```json, sometimes
* with Python-literal syntax in the nested arguments — single-quoted
* strings, `None`/`True`/`False`) instead of a real `tool_calls` entry.
*
* This is scanned for ONLY when the caller already knows the turn had zero
* real tool_calls (a text-only reply) — never as an alternative to native
* parsing. The caller must additionally check the extracted `name` against
* the session's real tool catalog before treating this as an actual call;
* this function only extracts a shape, it doesn't know what tools exist.
*
* Also recognizes a second observed shape (same 2026-08-19 session, a
* different iteration): `[Called tool "read_file" with arguments {'path':
* ...}]` — the model narrating, in past tense, that it already invoked a
* tool, when no such call was ever made. Prose that merely CLAIMS an
* action happened is exactly what requireExplicitCompletion exists to
* distrust — but when the named tool is real and the caller (loop.ts)
* confirms it against the session's actual catalog, actually running it
* turns a hallucinated claim into real, verified progress instead of
* wasting the turn on a nudge.
*
* Returns undefined when neither shape can be found — this is a
* best-effort scan, not a guarantee.
*/
export function extractEmbeddedToolCall(text: string): ParsedToolCall | undefined {
const narrated = /\[?Called tool ["']([\w-]+)["'] with arguments\s+(\{[\s\S]*?\})\]?/.exec(text)
if (narrated) {
const args = parsePermissiveObject(narrated[2]) ?? {}
return {
id: "embedded_0",
name: narrated[1],
args,
rawArguments: JSON.stringify(args),
}
}
const fenced = /```(?:json)?\s*(\{[\s\S]*?\})\s*```/.exec(text)
const candidates = fenced ? [fenced[1], text] : [text]
for (const candidate of candidates) {
const obj = parsePermissiveObject(candidate)
if (!obj) {
continue
}
const name = obj.name
if (typeof name !== "string" || name.trim() === "") {
continue
}
const rawArgs = obj.arguments
const args = isPlainObject(rawArgs) ? rawArgs : {}
return {
id: "embedded_0",
name: name.trim(),
args,
rawArguments: JSON.stringify(args),
}
}
return undefined
}
/**
* Like `bestEffortPartialJson`'s balanced-brace recovery, but tolerant of
* Python-literal syntax within the matched span: single-quoted strings and
* `None`/`True`/`False`. Normalizes those to JSON before parsing rather
* than hand-rolling a second recursive-descent parser.
*/
function parsePermissiveObject(input: string): Record<string, unknown> | undefined {
const firstBrace = input.indexOf("{")
if (firstBrace === -1) {
return undefined
}
let depth = 0
for (let i = firstBrace; i < input.length; i++) {
const ch = input[i]
if (ch === "{") {
depth++
} else if (ch === "}") {
depth--
if (depth === 0) {
const candidate = input.slice(firstBrace, i + 1)
try {
const parsed: unknown = JSON.parse(candidate)
if (isPlainObject(parsed)) {
return parsed
}
} catch {
const normalized = normalizePythonLiteral(candidate)
try {
const parsed: unknown = JSON.parse(normalized)
if (isPlainObject(parsed)) {
return parsed
}
} catch {
// give up on this brace span
}
}
return undefined
}
}
}
return undefined
}
/**
* Best-effort Python-dict-repr → JSON normalization: swaps single-quoted
* strings for double-quoted ones (respecting embedded escapes) and maps
* None/True/False to their JSON equivalents. Not a full Python literal
* parser — good enough for the shallow, flat-ish argument dicts a tool
* call carries.
*/
function normalizePythonLiteral(input: string): string {
let out = ""
let inString = false
let quoteChar = ""
for (let i = 0; i < input.length; i++) {
const ch = input[i]
if (inString) {
if (ch === "\\" && i + 1 < input.length) {
out += ch + input[i + 1]
i++
continue
}
if (ch === quoteChar) {
out += '"'
inString = false
continue
}
out += ch === '"' ? '\\"' : ch
continue
}
if (ch === "'" || ch === '"') {
inString = true
quoteChar = ch
out += '"'
continue
}
out += ch
}
return out.replace(/\bNone\b/g, "null").replace(/\bTrue\b/g, "true").replace(/\bFalse\b/g, "false")
}