one-model-router 0.0.10 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +21 -21
  2. package/package.json +1 -1
  3. package/src/admin.js +941 -941
  4. package/src/balances.js +61 -61
  5. package/src/boot.js +117 -117
  6. package/src/channels/buddy.js +2031 -2031
  7. package/src/channels/cline.js +753 -753
  8. package/src/channels/codearts.js +2051 -2051
  9. package/src/channels/comate.js +830 -830
  10. package/src/channels/doubaowork.js +1784 -1784
  11. package/src/channels/freebuff.js +1316 -1316
  12. package/src/channels/gemini.js +1721 -1721
  13. package/src/channels/index.js +270 -270
  14. package/src/channels/joycode.js +936 -936
  15. package/src/channels/kimi.js +572 -572
  16. package/src/channels/lobsterai.js +1226 -1226
  17. package/src/channels/loomy.js +1032 -1032
  18. package/src/channels/miaoshou.js +1396 -1396
  19. package/src/channels/mimo.js +474 -474
  20. package/src/channels/minimax.js +1451 -1451
  21. package/src/channels/qoder-wasm.js +434 -434
  22. package/src/channels/qoder.js +1619 -1619
  23. package/src/channels/raccoon.js +1842 -1842
  24. package/src/channels/tabbit.js +1457 -1457
  25. package/src/channels/trae.js +1405 -1405
  26. package/src/channels/zcode-global.js +35 -35
  27. package/src/channels/zcode.js +2085 -2085
  28. package/src/checkin.js +496 -496
  29. package/src/credits.js +464 -464
  30. package/src/crypto.js +132 -132
  31. package/src/free-models.js +683 -683
  32. package/src/gateway.js +596 -578
  33. package/src/health.js +86 -86
  34. package/src/model-key.js +35 -35
  35. package/src/paths.js +96 -96
  36. package/src/probe.js +318 -318
  37. package/src/providers/builtin.js +626 -626
  38. package/src/providers/index.js +483 -457
  39. package/src/providers/kilo.js +111 -111
  40. package/src/providers/last-good.js +69 -69
  41. package/src/providers/modelsdev.js +242 -242
  42. package/src/providers/openai-compat.js +312 -312
  43. package/src/providers/opencode/bun-fetch.js +226 -226
  44. package/src/providers/opencode/lane.js +186 -186
  45. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  46. package/src/providers/opencode/o2a/asset-source.js +43 -43
  47. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  48. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  49. package/src/providers/opencode/o2a/entry.js +17 -17
  50. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  51. package/src/providers/opencode/o2a/headers.js +133 -133
  52. package/src/providers/opencode/o2a/identity.js +148 -148
  53. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  54. package/src/providers/opencode/o2a/official-tools.js +110 -110
  55. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  56. package/src/providers/opencode/o2a/toolshape.js +418 -418
  57. package/src/providers/opencode/o2a/version.js +37 -37
  58. package/src/providers/opencode/upstream.js +403 -403
  59. package/src/providers/opencode/wire.js +496 -496
  60. package/src/providers/opencode.js +652 -652
  61. package/src/router.js +629 -629
  62. package/src/server.js +33 -33
  63. package/src/store.js +467 -467
  64. package/src/sync/index.js +1529 -1529
  65. package/src/sync/login-preload.cjs +52 -52
  66. package/src/sync/noise.js +141 -141
  67. package/src/sync/relay-http.js +176 -176
  68. package/src/sync/remote-host.js +818 -818
  69. package/src/sync/remote-http.js +112 -112
  70. package/src/sync/remote-login.js +657 -657
  71. package/src/sync/remote-pairing.js +204 -204
  72. package/src/sync/remote-protocol.js +321 -321
  73. package/src/sync/snapshot.js +211 -211
  74. package/src/util.js +334 -334
  75. package/web/app.js +3972 -3972
  76. package/web/index.html +32 -32
  77. package/web/style.css +971 -971
@@ -1,418 +1,418 @@
1
- /**
2
- * `renameAndCompleteTools` and `rewriteToolReferences`: make the tool list read
3
- * as an official CLI session.
4
- *
5
- * The walk, per shaped request:
6
- *
7
- * 1. Legacy `functions` arrays (the pre-tools OpenAI shape) are converted to
8
- * the wire's tool shape and renamed like any other client tool.
9
- * 2. Every named client tool is renamed to an opaque `clint_` wire name (see
10
- * tool-renames.js — the free tier refuses bodies that still carry another
11
- * client's vocabulary). Responses built-ins and Anthropic server tools have
12
- * no client name and are left untouched.
13
- * 3. The full official tool set for the lane is appended (official-tools.js).
14
- * 4. Every outbound reference to a client tool is renamed with it — named
15
- * `tool_choice` (including the Responses `allowed_tools` form), legacy
16
- * `function_call`, and the tool-call history each wire keeps — so the body
17
- * stays self-consistent. String choices pass through untouched.
18
- *
19
- * Documented deviations from a straightforward in-place implementation, all
20
- * caller-side necessities:
21
- *
22
- * - **Clone, don't mutate.** The caller's tool objects are shared with
23
- * the host harness, so a renamed entry is replaced with a shallow copy and
24
- * the caller's object is left untouched.
25
- * - **Idempotence.** A fresh body is normally shaped once per request, but an
26
- * already-shaped body can be shaped again (retried turns), so (a) a name whose
27
- * definition is verbatim-official is treated as the official declaration and
28
- * not renamed or re-appended (`options.keep`), and (b) a name already
29
- * carrying the `clint_` prefix is a wire name from a previous pass and is
30
- * left alone.
31
- *
32
- * @module src/o2a/toolshape.js
33
- */
34
-
35
- import { ToolRenameMap, CLIENT_TOOL_PREFIX, clientToolWireName, officialForClientName } from './tool-renames.js'
36
- import { V2_OFFICIAL_TOOL_ORDER, officialTool, officialToolDefinition, renamableToolName } from './official-tools.js'
37
-
38
- /**
39
- * Shape the tool list of `payload` in place.
40
- *
41
- * @param {object} payload - request body, mutated in place
42
- * @param {'chat'|'flat'|'claude'} shape - the wire shape the body speaks
43
- * @param {object} [options]
44
- * @param {Set<string>} [options.keep] - official tool names already declared
45
- * verbatim; left untouched and not appended again
46
- * @returns {{ renames: ToolRenameMap, injected: string[], known: Set<string> }}
47
- * the rename set, the official names this pass appended, and every wire tool
48
- * name the shaped body considers valid (bound and appended officials plus
49
- * the `clint_` renames) — the history sanitizer's whitelist
50
- */
51
- export function renameAndCompleteTools(payload, shape, { keep } = {}) {
52
- if (shape !== 'chat' && shape !== 'flat' && shape !== 'claude') {
53
- return { renames: new ToolRenameMap(), injected: [], known: new Set() }
54
- }
55
- const renames = new ToolRenameMap()
56
- const used = new Set()
57
- const keepNames = keep instanceof Set ? keep : new Set()
58
- /** Officials spoken on the wire this pass: verbatim declarations, alias
59
- * bindings and the appended set. Everything else in the call history is a
60
- * ghost the sanitizer drops. */
61
- const officialUsed = new Set(keepNames)
62
- let items = Array.isArray(payload.tools) ? [...payload.tools] : []
63
- if ((shape === 'chat' || shape === 'flat') && Array.isArray(payload.functions)) {
64
- items = items.concat(convertLegacyFunctions(payload.functions, shape, renames, used))
65
- delete payload.functions
66
- }
67
- // The sanitizer's scope: tools the CALLER declared this request — officials
68
- // we append do not make a body agent-shaped on their own.
69
- const declaredClientTools = items.filter(item => renamableToolName(shape, item) !== null).length
70
- const shaped = []
71
- for (const item of items) {
72
- const name = renamableToolName(shape, item)
73
- if (name === null) {
74
- shaped.push(item)
75
- continue
76
- }
77
- // An already-shaped body's officials and wire names are not client tools.
78
- if (keepNames.has(name) || name.startsWith(CLIENT_TOOL_PREFIX)) {
79
- shaped.push(item)
80
- continue
81
- }
82
- // `BindOfficial`: a client tool whose folded name is one of an
83
- // official's known client spellings rides the wire under the official
84
- // name — the caller's own definition, not a `clint_` opaque, and the
85
- // official definition is not appended a second time. Each official binds
86
- // once; the response side restores the caller's spelling through the same
87
- // rename map as every other rename.
88
- const official = officialForClientName(name)
89
- if (official !== null && officialUsed.has(official) === false && officialToolDefinition(official) !== undefined) {
90
- officialUsed.add(official)
91
- renames.add(name, official)
92
- shaped.push(withToolName(shape, item, official))
93
- continue
94
- }
95
- let wireName = renames.wireOf(name)
96
- if (wireName === undefined) {
97
- wireName = clientToolWireName(name, used)
98
- renames.add(name, wireName)
99
- }
100
- shaped.push(wireName !== name ? withToolName(shape, item, wireName) : item)
101
- }
102
- const injected = []
103
- for (const name of V2_OFFICIAL_TOOL_ORDER) {
104
- if (officialUsed.has(name)) continue
105
- shaped.push(officialTool(shape, name))
106
- injected.push(name)
107
- officialUsed.add(name)
108
- }
109
- payload.tools = shaped
110
- rewriteToolReferences(payload, shape, renames)
111
- const known = new Set(officialUsed)
112
- for (const wire of renames.keys()) known.add(wire)
113
- if (declaredClientTools > 0) sanitizeToolHistory(payload, shape, known)
114
- dropDanglingToolChoice(payload, shape, known)
115
- return { renames, injected, known }
116
- }
117
-
118
- /**
119
- * Drop ghost tool calls and their paired results (`sanitizeToolHistory`).
120
- *
121
- * A shaped body's call history is valid only when every call names a tool the
122
- * wire actually serves this pass: a bound or appended official, or one of this
123
- * request's `clint_` renames. Everything else is a ghost — a client tool the
124
- * caller dropped from its declarations, a foreign name from a mid-conversation
125
- * change — and the free tier answers a body that carries one with the
126
- * same refusals it saves for vocabulary leaks. The call goes, and the result
127
- * message paired to it goes with it, because an orphaned result is its own
128
- * shape violation.
129
- *
130
- * Only agent-shaped traffic is sanitized: the vocabulary gate inspects bodies
131
- * that carry a tool list, so the pass runs exactly when this request declares
132
- * tools. A toolless forwarding client replaying a conversation with tool
133
- * history keeps that history verbatim — there is no gate to satisfy, and the
134
- * model needs its context.
135
- *
136
- * Copy-on-write like every other edit here: the caller's message objects are
137
- * shared with the host harness, so touched rows are replaced, never mutated.
138
- */
139
- function sanitizeToolHistory(payload, shape, known) {
140
- /** A history call's fate: kept, rewritten to a served official alias, or dropped. */
141
- const fateOf = name => {
142
- if (typeof name !== 'string' || name === '') return { verdict: 'drop' }
143
- if (known.has(name)) return { verdict: 'keep' }
144
- const official = officialForClientName(name)
145
- if (official !== null && known.has(official)) return { verdict: 'rename', official }
146
- return { verdict: 'drop' }
147
- }
148
- if (shape === 'chat') {
149
- const messages = Array.isArray(payload.messages) ? payload.messages : null
150
- if (messages === null) return
151
- const droppedCalls = new Set()
152
- const droppedFunctions = new Set()
153
- let changed = false
154
- for (let i = 0; i < messages.length; i += 1) {
155
- const message = messages[i]
156
- if (!message || typeof message !== 'object') continue
157
- if (Array.isArray(message.tool_calls)) {
158
- const kept = []
159
- let touched = false
160
- for (const call of message.tool_calls) {
161
- const fate = fateOf(call?.function?.name)
162
- if (fate.verdict === 'keep') { kept.push(call); continue }
163
- if (fate.verdict === 'rename') {
164
- const fn = call.function ?? {}
165
- kept.push({ ...call, function: { ...fn, name: fate.official } })
166
- touched = true
167
- continue
168
- }
169
- if (typeof call?.id === 'string' && call.id !== '') droppedCalls.add(call.id)
170
- touched = true
171
- }
172
- if (touched) {
173
- messages[i] = { ...message, tool_calls: kept }
174
- changed = true
175
- }
176
- }
177
- if (message.function_call && typeof message.function_call === 'object') {
178
- const fate = fateOf(message.function_call.name)
179
- if (fate.verdict === 'rename') {
180
- messages[i] = { ...message, function_call: { ...message.function_call, name: fate.official } }
181
- changed = true
182
- } else if (fate.verdict === 'drop') {
183
- if (typeof message.function_call.name === 'string') droppedFunctions.add(message.function_call.name)
184
- const { function_call: _dropped, ...rest } = messages[i]
185
- messages[i] = rest
186
- changed = true
187
- }
188
- }
189
- if (message.role === 'tool' && typeof message.tool_call_id === 'string' && droppedCalls.has(message.tool_call_id)) {
190
- messages.splice(i, 1)
191
- i -= 1
192
- changed = true
193
- }
194
- if (message.role === 'function' && typeof message.name === 'string' && droppedFunctions.has(message.name)) {
195
- messages.splice(i, 1)
196
- i -= 1
197
- changed = true
198
- }
199
- }
200
- if (changed && messages.length === 0) payload.messages = []
201
- return
202
- }
203
- if (shape === 'flat') {
204
- const input = Array.isArray(payload.input) ? payload.input : null
205
- if (input === null) return
206
- const droppedCalls = new Set()
207
- let changed = false
208
- for (let i = 0; i < input.length; i += 1) {
209
- const item = input[i]
210
- const type = typeof item?.type === 'string' ? item.type : ''
211
- if (type === 'function_call') {
212
- const fate = fateOf(item.name)
213
- if (fate.verdict === 'rename') {
214
- input[i] = { ...item, name: fate.official }
215
- changed = true
216
- } else if (fate.verdict === 'drop') {
217
- if (typeof item.call_id === 'string' && item.call_id !== '') droppedCalls.add(item.call_id)
218
- input.splice(i, 1)
219
- i -= 1
220
- changed = true
221
- }
222
- continue
223
- }
224
- if (type === 'function_call_output' && typeof item.call_id === 'string' && droppedCalls.has(item.call_id)) {
225
- input.splice(i, 1)
226
- i -= 1
227
- changed = true
228
- }
229
- }
230
- if (changed && input.length === 0) payload.input = []
231
- return
232
- }
233
- const messages = Array.isArray(payload.messages) ? payload.messages : null
234
- if (messages === null) return
235
- const droppedCalls = new Set()
236
- let changed = false
237
- for (let i = 0; i < messages.length; i += 1) {
238
- const message = messages[i]
239
- if (!message || typeof message !== 'object' || !Array.isArray(message.content)) continue
240
- const kept = []
241
- let touched = false
242
- for (const block of message.content) {
243
- if (block?.type === 'tool_use') {
244
- const fate = fateOf(block.name)
245
- if (fate.verdict === 'keep') { kept.push(block); continue }
246
- if (fate.verdict === 'rename') { kept.push({ ...block, name: fate.official }); touched = true; continue }
247
- if (typeof block.id === 'string' && block.id !== '') droppedCalls.add(block.id)
248
- touched = true
249
- continue
250
- }
251
- if (block?.type === 'tool_result' && typeof block.tool_use_id === 'string' && droppedCalls.has(block.tool_use_id)) {
252
- touched = true
253
- continue
254
- }
255
- kept.push(block)
256
- }
257
- if (touched) {
258
- messages[i] = kept.length === 0 ? null : { ...message, content: kept }
259
- changed = true
260
- }
261
- }
262
- if (changed) payload.messages = messages.filter(message => message !== null)
263
- }
264
-
265
- /** Remove a named `tool_choice` that names a tool the shaped body no longer serves. */
266
- function dropDanglingToolChoice(payload, shape, known) {
267
- const choice = payload?.tool_choice
268
- if (choice === null || typeof choice !== 'object') return
269
- const name = shape === 'chat' && choice.function && typeof choice.function === 'object'
270
- ? choice.function.name
271
- : choice.name
272
- if (typeof name === 'string' && name !== '' && !known.has(name)) delete payload.tool_choice
273
- }
274
-
275
- /** Replace a renamed entry with a shallow copy carrying the wire name. */
276
- function withToolName(shape, entry, name) {
277
- if (shape === 'chat') {
278
- return { ...entry, function: { ...entry.function, name } }
279
- }
280
- return { ...entry, name }
281
- }
282
-
283
- /** Turn the pre-tools `functions` array into wire-shaped, renamed entries. */
284
- function convertLegacyFunctions(entries, shape, renames, used) {
285
- const converted = []
286
- for (const raw of entries) {
287
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue
288
- const name = typeof raw.name === 'string' ? raw.name : ''
289
- if (name === '') continue
290
- let wireName = renames.wireOf(name)
291
- if (wireName === undefined) {
292
- wireName = clientToolWireName(name, used)
293
- renames.add(name, wireName)
294
- }
295
- const description = typeof raw.description === 'string' ? raw.description : undefined
296
- const parameters = raw.parameters ?? { type: 'object', properties: {} }
297
- if (shape === 'chat') {
298
- const fn = { name: wireName, description, parameters }
299
- if (raw.strict !== undefined) fn.strict = raw.strict
300
- converted.push({ type: 'function', function: fn })
301
- } else {
302
- const tool = { type: 'function', name: wireName, description, parameters }
303
- if (raw.strict !== undefined) tool.strict = raw.strict
304
- converted.push(tool)
305
- }
306
- }
307
- return converted
308
- }
309
-
310
- /**
311
- * Rename every outbound reference to a client tool:
312
- * named `tool_choice` (including legacy Chat and Responses `allowed_tools`
313
- * forms), legacy `function_call`, and the tool-call history each wire keeps.
314
- * String choices pass through untouched. Copy-on-write: the caller's history
315
- * objects are shared with the host harness, so renamed rows are replaced with
316
- * shallow copies instead of edited in place (see the deviations note above).
317
- */
318
- function rewriteToolReferences(payload, shape, renames) {
319
- if (renames.size === 0) return
320
- const renamed = container => {
321
- if (!container || typeof container !== 'object') return null
322
- const name = container.name
323
- if (typeof name !== 'string') return null
324
- const wireName = renames.wireOf(name)
325
- return wireName !== undefined && wireName !== name ? wireName : null
326
- }
327
- if (shape === 'chat') {
328
- const choice = objectOf(payload.tool_choice)
329
- if (choice) {
330
- if (choice.function && typeof choice.function === 'object') {
331
- const wire = renamed(choice.function)
332
- if (wire !== null) payload.tool_choice = { ...choice, function: { ...choice.function, name: wire } }
333
- } else {
334
- const wire = renamed(choice)
335
- if (wire !== null) payload.tool_choice = { ...choice, name: wire }
336
- }
337
- }
338
- const call = objectOf(payload.function_call)
339
- if (call) {
340
- const wire = renamed(call)
341
- if (wire !== null) payload.function_call = { ...call, name: wire }
342
- }
343
- const messages = Array.isArray(payload.messages) ? payload.messages : []
344
- for (let i = 0; i < messages.length; i += 1) {
345
- const message = messages[i]
346
- if (!message || typeof message !== 'object') continue
347
- let next = null
348
- const fnCall = objectOf(message.function_call)
349
- if (fnCall) {
350
- const wire = renamed(fnCall)
351
- if (wire !== null) next = { ...message, function_call: { ...fnCall, name: wire } }
352
- }
353
- if (Array.isArray(message.tool_calls)) {
354
- const calls = message.tool_calls.map(entry => {
355
- const fn = objectOf(entry?.function)
356
- if (!fn) return entry
357
- const wire = renamed(fn)
358
- return wire !== null ? { ...entry, function: { ...fn, name: wire } } : entry
359
- })
360
- if (calls.some((entry, j) => entry !== message.tool_calls[j])) {
361
- next = { ...(next ?? message), tool_calls: calls }
362
- }
363
- }
364
- if (next !== null) messages[i] = next
365
- }
366
- return
367
- }
368
- if (shape === 'flat') {
369
- const choice = objectOf(payload.tool_choice)
370
- if (choice) {
371
- let next = null
372
- const wire = renamed(choice)
373
- if (wire !== null) next = { ...choice, name: wire }
374
- if (Array.isArray(choice.allowed_tools)) {
375
- const allowed = choice.allowed_tools.map(entry => {
376
- if (!entry || typeof entry !== 'object') return entry
377
- const entryWire = renamed(entry)
378
- return entryWire !== null ? { ...entry, name: entryWire } : entry
379
- })
380
- if (allowed.some((entry, j) => entry !== choice.allowed_tools[j])) {
381
- next = { ...(next ?? choice), allowed_tools: allowed }
382
- }
383
- }
384
- if (next !== null) payload.tool_choice = next
385
- }
386
- const input = Array.isArray(payload.input) ? payload.input : []
387
- for (let i = 0; i < input.length; i += 1) {
388
- const item = input[i]
389
- const type = typeof item?.type === 'string' ? item.type : ''
390
- if (type !== 'function_call' && type !== 'custom_tool_call') continue
391
- const wire = renamed(item)
392
- if (wire !== null) input[i] = { ...item, name: wire }
393
- }
394
- return
395
- }
396
- const choice = objectOf(payload.tool_choice)
397
- if (choice) {
398
- const wire = renamed(choice)
399
- if (wire !== null) payload.tool_choice = { ...choice, name: wire }
400
- }
401
- const messages = Array.isArray(payload.messages) ? payload.messages : []
402
- for (let i = 0; i < messages.length; i += 1) {
403
- const message = messages[i]
404
- if (!message || typeof message !== 'object' || !Array.isArray(message.content)) continue
405
- const content = message.content.map(block => {
406
- if (block?.type !== 'tool_use') return block
407
- const wire = renamed(block)
408
- return wire !== null ? { ...block, name: wire } : block
409
- })
410
- if (content.some((block, j) => block !== message.content[j])) {
411
- messages[i] = { ...message, content }
412
- }
413
- }
414
- }
415
-
416
- function objectOf(value) {
417
- return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null
418
- }
1
+ /**
2
+ * `renameAndCompleteTools` and `rewriteToolReferences`: make the tool list read
3
+ * as an official CLI session.
4
+ *
5
+ * The walk, per shaped request:
6
+ *
7
+ * 1. Legacy `functions` arrays (the pre-tools OpenAI shape) are converted to
8
+ * the wire's tool shape and renamed like any other client tool.
9
+ * 2. Every named client tool is renamed to an opaque `clint_` wire name (see
10
+ * tool-renames.js — the free tier refuses bodies that still carry another
11
+ * client's vocabulary). Responses built-ins and Anthropic server tools have
12
+ * no client name and are left untouched.
13
+ * 3. The full official tool set for the lane is appended (official-tools.js).
14
+ * 4. Every outbound reference to a client tool is renamed with it — named
15
+ * `tool_choice` (including the Responses `allowed_tools` form), legacy
16
+ * `function_call`, and the tool-call history each wire keeps — so the body
17
+ * stays self-consistent. String choices pass through untouched.
18
+ *
19
+ * Documented deviations from a straightforward in-place implementation, all
20
+ * caller-side necessities:
21
+ *
22
+ * - **Clone, don't mutate.** The caller's tool objects are shared with
23
+ * the host harness, so a renamed entry is replaced with a shallow copy and
24
+ * the caller's object is left untouched.
25
+ * - **Idempotence.** A fresh body is normally shaped once per request, but an
26
+ * already-shaped body can be shaped again (retried turns), so (a) a name whose
27
+ * definition is verbatim-official is treated as the official declaration and
28
+ * not renamed or re-appended (`options.keep`), and (b) a name already
29
+ * carrying the `clint_` prefix is a wire name from a previous pass and is
30
+ * left alone.
31
+ *
32
+ * @module src/o2a/toolshape.js
33
+ */
34
+
35
+ import { ToolRenameMap, CLIENT_TOOL_PREFIX, clientToolWireName, officialForClientName } from './tool-renames.js'
36
+ import { V2_OFFICIAL_TOOL_ORDER, officialTool, officialToolDefinition, renamableToolName } from './official-tools.js'
37
+
38
+ /**
39
+ * Shape the tool list of `payload` in place.
40
+ *
41
+ * @param {object} payload - request body, mutated in place
42
+ * @param {'chat'|'flat'|'claude'} shape - the wire shape the body speaks
43
+ * @param {object} [options]
44
+ * @param {Set<string>} [options.keep] - official tool names already declared
45
+ * verbatim; left untouched and not appended again
46
+ * @returns {{ renames: ToolRenameMap, injected: string[], known: Set<string> }}
47
+ * the rename set, the official names this pass appended, and every wire tool
48
+ * name the shaped body considers valid (bound and appended officials plus
49
+ * the `clint_` renames) — the history sanitizer's whitelist
50
+ */
51
+ export function renameAndCompleteTools(payload, shape, { keep } = {}) {
52
+ if (shape !== 'chat' && shape !== 'flat' && shape !== 'claude') {
53
+ return { renames: new ToolRenameMap(), injected: [], known: new Set() }
54
+ }
55
+ const renames = new ToolRenameMap()
56
+ const used = new Set()
57
+ const keepNames = keep instanceof Set ? keep : new Set()
58
+ /** Officials spoken on the wire this pass: verbatim declarations, alias
59
+ * bindings and the appended set. Everything else in the call history is a
60
+ * ghost the sanitizer drops. */
61
+ const officialUsed = new Set(keepNames)
62
+ let items = Array.isArray(payload.tools) ? [...payload.tools] : []
63
+ if ((shape === 'chat' || shape === 'flat') && Array.isArray(payload.functions)) {
64
+ items = items.concat(convertLegacyFunctions(payload.functions, shape, renames, used))
65
+ delete payload.functions
66
+ }
67
+ // The sanitizer's scope: tools the CALLER declared this request — officials
68
+ // we append do not make a body agent-shaped on their own.
69
+ const declaredClientTools = items.filter(item => renamableToolName(shape, item) !== null).length
70
+ const shaped = []
71
+ for (const item of items) {
72
+ const name = renamableToolName(shape, item)
73
+ if (name === null) {
74
+ shaped.push(item)
75
+ continue
76
+ }
77
+ // An already-shaped body's officials and wire names are not client tools.
78
+ if (keepNames.has(name) || name.startsWith(CLIENT_TOOL_PREFIX)) {
79
+ shaped.push(item)
80
+ continue
81
+ }
82
+ // `BindOfficial`: a client tool whose folded name is one of an
83
+ // official's known client spellings rides the wire under the official
84
+ // name — the caller's own definition, not a `clint_` opaque, and the
85
+ // official definition is not appended a second time. Each official binds
86
+ // once; the response side restores the caller's spelling through the same
87
+ // rename map as every other rename.
88
+ const official = officialForClientName(name)
89
+ if (official !== null && officialUsed.has(official) === false && officialToolDefinition(official) !== undefined) {
90
+ officialUsed.add(official)
91
+ renames.add(name, official)
92
+ shaped.push(withToolName(shape, item, official))
93
+ continue
94
+ }
95
+ let wireName = renames.wireOf(name)
96
+ if (wireName === undefined) {
97
+ wireName = clientToolWireName(name, used)
98
+ renames.add(name, wireName)
99
+ }
100
+ shaped.push(wireName !== name ? withToolName(shape, item, wireName) : item)
101
+ }
102
+ const injected = []
103
+ for (const name of V2_OFFICIAL_TOOL_ORDER) {
104
+ if (officialUsed.has(name)) continue
105
+ shaped.push(officialTool(shape, name))
106
+ injected.push(name)
107
+ officialUsed.add(name)
108
+ }
109
+ payload.tools = shaped
110
+ rewriteToolReferences(payload, shape, renames)
111
+ const known = new Set(officialUsed)
112
+ for (const wire of renames.keys()) known.add(wire)
113
+ if (declaredClientTools > 0) sanitizeToolHistory(payload, shape, known)
114
+ dropDanglingToolChoice(payload, shape, known)
115
+ return { renames, injected, known }
116
+ }
117
+
118
+ /**
119
+ * Drop ghost tool calls and their paired results (`sanitizeToolHistory`).
120
+ *
121
+ * A shaped body's call history is valid only when every call names a tool the
122
+ * wire actually serves this pass: a bound or appended official, or one of this
123
+ * request's `clint_` renames. Everything else is a ghost — a client tool the
124
+ * caller dropped from its declarations, a foreign name from a mid-conversation
125
+ * change — and the free tier answers a body that carries one with the
126
+ * same refusals it saves for vocabulary leaks. The call goes, and the result
127
+ * message paired to it goes with it, because an orphaned result is its own
128
+ * shape violation.
129
+ *
130
+ * Only agent-shaped traffic is sanitized: the vocabulary gate inspects bodies
131
+ * that carry a tool list, so the pass runs exactly when this request declares
132
+ * tools. A toolless forwarding client replaying a conversation with tool
133
+ * history keeps that history verbatim — there is no gate to satisfy, and the
134
+ * model needs its context.
135
+ *
136
+ * Copy-on-write like every other edit here: the caller's message objects are
137
+ * shared with the host harness, so touched rows are replaced, never mutated.
138
+ */
139
+ function sanitizeToolHistory(payload, shape, known) {
140
+ /** A history call's fate: kept, rewritten to a served official alias, or dropped. */
141
+ const fateOf = name => {
142
+ if (typeof name !== 'string' || name === '') return { verdict: 'drop' }
143
+ if (known.has(name)) return { verdict: 'keep' }
144
+ const official = officialForClientName(name)
145
+ if (official !== null && known.has(official)) return { verdict: 'rename', official }
146
+ return { verdict: 'drop' }
147
+ }
148
+ if (shape === 'chat') {
149
+ const messages = Array.isArray(payload.messages) ? payload.messages : null
150
+ if (messages === null) return
151
+ const droppedCalls = new Set()
152
+ const droppedFunctions = new Set()
153
+ let changed = false
154
+ for (let i = 0; i < messages.length; i += 1) {
155
+ const message = messages[i]
156
+ if (!message || typeof message !== 'object') continue
157
+ if (Array.isArray(message.tool_calls)) {
158
+ const kept = []
159
+ let touched = false
160
+ for (const call of message.tool_calls) {
161
+ const fate = fateOf(call?.function?.name)
162
+ if (fate.verdict === 'keep') { kept.push(call); continue }
163
+ if (fate.verdict === 'rename') {
164
+ const fn = call.function ?? {}
165
+ kept.push({ ...call, function: { ...fn, name: fate.official } })
166
+ touched = true
167
+ continue
168
+ }
169
+ if (typeof call?.id === 'string' && call.id !== '') droppedCalls.add(call.id)
170
+ touched = true
171
+ }
172
+ if (touched) {
173
+ messages[i] = { ...message, tool_calls: kept }
174
+ changed = true
175
+ }
176
+ }
177
+ if (message.function_call && typeof message.function_call === 'object') {
178
+ const fate = fateOf(message.function_call.name)
179
+ if (fate.verdict === 'rename') {
180
+ messages[i] = { ...message, function_call: { ...message.function_call, name: fate.official } }
181
+ changed = true
182
+ } else if (fate.verdict === 'drop') {
183
+ if (typeof message.function_call.name === 'string') droppedFunctions.add(message.function_call.name)
184
+ const { function_call: _dropped, ...rest } = messages[i]
185
+ messages[i] = rest
186
+ changed = true
187
+ }
188
+ }
189
+ if (message.role === 'tool' && typeof message.tool_call_id === 'string' && droppedCalls.has(message.tool_call_id)) {
190
+ messages.splice(i, 1)
191
+ i -= 1
192
+ changed = true
193
+ }
194
+ if (message.role === 'function' && typeof message.name === 'string' && droppedFunctions.has(message.name)) {
195
+ messages.splice(i, 1)
196
+ i -= 1
197
+ changed = true
198
+ }
199
+ }
200
+ if (changed && messages.length === 0) payload.messages = []
201
+ return
202
+ }
203
+ if (shape === 'flat') {
204
+ const input = Array.isArray(payload.input) ? payload.input : null
205
+ if (input === null) return
206
+ const droppedCalls = new Set()
207
+ let changed = false
208
+ for (let i = 0; i < input.length; i += 1) {
209
+ const item = input[i]
210
+ const type = typeof item?.type === 'string' ? item.type : ''
211
+ if (type === 'function_call') {
212
+ const fate = fateOf(item.name)
213
+ if (fate.verdict === 'rename') {
214
+ input[i] = { ...item, name: fate.official }
215
+ changed = true
216
+ } else if (fate.verdict === 'drop') {
217
+ if (typeof item.call_id === 'string' && item.call_id !== '') droppedCalls.add(item.call_id)
218
+ input.splice(i, 1)
219
+ i -= 1
220
+ changed = true
221
+ }
222
+ continue
223
+ }
224
+ if (type === 'function_call_output' && typeof item.call_id === 'string' && droppedCalls.has(item.call_id)) {
225
+ input.splice(i, 1)
226
+ i -= 1
227
+ changed = true
228
+ }
229
+ }
230
+ if (changed && input.length === 0) payload.input = []
231
+ return
232
+ }
233
+ const messages = Array.isArray(payload.messages) ? payload.messages : null
234
+ if (messages === null) return
235
+ const droppedCalls = new Set()
236
+ let changed = false
237
+ for (let i = 0; i < messages.length; i += 1) {
238
+ const message = messages[i]
239
+ if (!message || typeof message !== 'object' || !Array.isArray(message.content)) continue
240
+ const kept = []
241
+ let touched = false
242
+ for (const block of message.content) {
243
+ if (block?.type === 'tool_use') {
244
+ const fate = fateOf(block.name)
245
+ if (fate.verdict === 'keep') { kept.push(block); continue }
246
+ if (fate.verdict === 'rename') { kept.push({ ...block, name: fate.official }); touched = true; continue }
247
+ if (typeof block.id === 'string' && block.id !== '') droppedCalls.add(block.id)
248
+ touched = true
249
+ continue
250
+ }
251
+ if (block?.type === 'tool_result' && typeof block.tool_use_id === 'string' && droppedCalls.has(block.tool_use_id)) {
252
+ touched = true
253
+ continue
254
+ }
255
+ kept.push(block)
256
+ }
257
+ if (touched) {
258
+ messages[i] = kept.length === 0 ? null : { ...message, content: kept }
259
+ changed = true
260
+ }
261
+ }
262
+ if (changed) payload.messages = messages.filter(message => message !== null)
263
+ }
264
+
265
+ /** Remove a named `tool_choice` that names a tool the shaped body no longer serves. */
266
+ function dropDanglingToolChoice(payload, shape, known) {
267
+ const choice = payload?.tool_choice
268
+ if (choice === null || typeof choice !== 'object') return
269
+ const name = shape === 'chat' && choice.function && typeof choice.function === 'object'
270
+ ? choice.function.name
271
+ : choice.name
272
+ if (typeof name === 'string' && name !== '' && !known.has(name)) delete payload.tool_choice
273
+ }
274
+
275
+ /** Replace a renamed entry with a shallow copy carrying the wire name. */
276
+ function withToolName(shape, entry, name) {
277
+ if (shape === 'chat') {
278
+ return { ...entry, function: { ...entry.function, name } }
279
+ }
280
+ return { ...entry, name }
281
+ }
282
+
283
+ /** Turn the pre-tools `functions` array into wire-shaped, renamed entries. */
284
+ function convertLegacyFunctions(entries, shape, renames, used) {
285
+ const converted = []
286
+ for (const raw of entries) {
287
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue
288
+ const name = typeof raw.name === 'string' ? raw.name : ''
289
+ if (name === '') continue
290
+ let wireName = renames.wireOf(name)
291
+ if (wireName === undefined) {
292
+ wireName = clientToolWireName(name, used)
293
+ renames.add(name, wireName)
294
+ }
295
+ const description = typeof raw.description === 'string' ? raw.description : undefined
296
+ const parameters = raw.parameters ?? { type: 'object', properties: {} }
297
+ if (shape === 'chat') {
298
+ const fn = { name: wireName, description, parameters }
299
+ if (raw.strict !== undefined) fn.strict = raw.strict
300
+ converted.push({ type: 'function', function: fn })
301
+ } else {
302
+ const tool = { type: 'function', name: wireName, description, parameters }
303
+ if (raw.strict !== undefined) tool.strict = raw.strict
304
+ converted.push(tool)
305
+ }
306
+ }
307
+ return converted
308
+ }
309
+
310
+ /**
311
+ * Rename every outbound reference to a client tool:
312
+ * named `tool_choice` (including legacy Chat and Responses `allowed_tools`
313
+ * forms), legacy `function_call`, and the tool-call history each wire keeps.
314
+ * String choices pass through untouched. Copy-on-write: the caller's history
315
+ * objects are shared with the host harness, so renamed rows are replaced with
316
+ * shallow copies instead of edited in place (see the deviations note above).
317
+ */
318
+ function rewriteToolReferences(payload, shape, renames) {
319
+ if (renames.size === 0) return
320
+ const renamed = container => {
321
+ if (!container || typeof container !== 'object') return null
322
+ const name = container.name
323
+ if (typeof name !== 'string') return null
324
+ const wireName = renames.wireOf(name)
325
+ return wireName !== undefined && wireName !== name ? wireName : null
326
+ }
327
+ if (shape === 'chat') {
328
+ const choice = objectOf(payload.tool_choice)
329
+ if (choice) {
330
+ if (choice.function && typeof choice.function === 'object') {
331
+ const wire = renamed(choice.function)
332
+ if (wire !== null) payload.tool_choice = { ...choice, function: { ...choice.function, name: wire } }
333
+ } else {
334
+ const wire = renamed(choice)
335
+ if (wire !== null) payload.tool_choice = { ...choice, name: wire }
336
+ }
337
+ }
338
+ const call = objectOf(payload.function_call)
339
+ if (call) {
340
+ const wire = renamed(call)
341
+ if (wire !== null) payload.function_call = { ...call, name: wire }
342
+ }
343
+ const messages = Array.isArray(payload.messages) ? payload.messages : []
344
+ for (let i = 0; i < messages.length; i += 1) {
345
+ const message = messages[i]
346
+ if (!message || typeof message !== 'object') continue
347
+ let next = null
348
+ const fnCall = objectOf(message.function_call)
349
+ if (fnCall) {
350
+ const wire = renamed(fnCall)
351
+ if (wire !== null) next = { ...message, function_call: { ...fnCall, name: wire } }
352
+ }
353
+ if (Array.isArray(message.tool_calls)) {
354
+ const calls = message.tool_calls.map(entry => {
355
+ const fn = objectOf(entry?.function)
356
+ if (!fn) return entry
357
+ const wire = renamed(fn)
358
+ return wire !== null ? { ...entry, function: { ...fn, name: wire } } : entry
359
+ })
360
+ if (calls.some((entry, j) => entry !== message.tool_calls[j])) {
361
+ next = { ...(next ?? message), tool_calls: calls }
362
+ }
363
+ }
364
+ if (next !== null) messages[i] = next
365
+ }
366
+ return
367
+ }
368
+ if (shape === 'flat') {
369
+ const choice = objectOf(payload.tool_choice)
370
+ if (choice) {
371
+ let next = null
372
+ const wire = renamed(choice)
373
+ if (wire !== null) next = { ...choice, name: wire }
374
+ if (Array.isArray(choice.allowed_tools)) {
375
+ const allowed = choice.allowed_tools.map(entry => {
376
+ if (!entry || typeof entry !== 'object') return entry
377
+ const entryWire = renamed(entry)
378
+ return entryWire !== null ? { ...entry, name: entryWire } : entry
379
+ })
380
+ if (allowed.some((entry, j) => entry !== choice.allowed_tools[j])) {
381
+ next = { ...(next ?? choice), allowed_tools: allowed }
382
+ }
383
+ }
384
+ if (next !== null) payload.tool_choice = next
385
+ }
386
+ const input = Array.isArray(payload.input) ? payload.input : []
387
+ for (let i = 0; i < input.length; i += 1) {
388
+ const item = input[i]
389
+ const type = typeof item?.type === 'string' ? item.type : ''
390
+ if (type !== 'function_call' && type !== 'custom_tool_call') continue
391
+ const wire = renamed(item)
392
+ if (wire !== null) input[i] = { ...item, name: wire }
393
+ }
394
+ return
395
+ }
396
+ const choice = objectOf(payload.tool_choice)
397
+ if (choice) {
398
+ const wire = renamed(choice)
399
+ if (wire !== null) payload.tool_choice = { ...choice, name: wire }
400
+ }
401
+ const messages = Array.isArray(payload.messages) ? payload.messages : []
402
+ for (let i = 0; i < messages.length; i += 1) {
403
+ const message = messages[i]
404
+ if (!message || typeof message !== 'object' || !Array.isArray(message.content)) continue
405
+ const content = message.content.map(block => {
406
+ if (block?.type !== 'tool_use') return block
407
+ const wire = renamed(block)
408
+ return wire !== null ? { ...block, name: wire } : block
409
+ })
410
+ if (content.some((block, j) => block !== message.content[j])) {
411
+ messages[i] = { ...message, content }
412
+ }
413
+ }
414
+ }
415
+
416
+ function objectOf(value) {
417
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null
418
+ }