@opengeni/runtime 6.7.0 → 6.8.0

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 (49) hide show
  1. package/dist/anthropic-messages.d.ts +14 -1
  2. package/dist/assets/codemode-client.json +1 -1
  3. package/dist/{chunk-3MNZZ2B4.js → chunk-2MBI6D2F.js} +2 -2
  4. package/dist/{chunk-JY5NSZ37.js → chunk-5K2NI7NX.js} +15 -13
  5. package/dist/chunk-5K2NI7NX.js.map +1 -0
  6. package/dist/{chunk-77NQGL66.js → chunk-6MHS5OUN.js} +1 -1
  7. package/dist/chunk-6MHS5OUN.js.map +1 -0
  8. package/dist/{chunk-RZJXTSVA.js → chunk-E2YB7OIA.js} +2 -2
  9. package/dist/{chunk-JF5UTPEU.js → chunk-JRM6HEPY.js} +2 -2
  10. package/dist/{chunk-GFAFQMZV.js → chunk-QNQGZKHJ.js} +3 -3
  11. package/dist/{chunk-FNAYH3SN.js → chunk-RXCYGCX7.js} +1282 -477
  12. package/dist/chunk-RXCYGCX7.js.map +1 -0
  13. package/dist/{chunk-OAW6MMSY.js → chunk-V7MCFH4O.js} +3 -3
  14. package/dist/gmail-rest-mcp.js +3 -3
  15. package/dist/google-calendar-rest-mcp.js +2 -2
  16. package/dist/index.js +8 -8
  17. package/dist/metrics.d.ts +15 -0
  18. package/dist/model-call.js +1 -1
  19. package/dist/model-provider-client.d.ts +3 -0
  20. package/dist/provider-history-adapter.d.ts +0 -6
  21. package/dist/provider-invalid-request.d.ts +12 -0
  22. package/dist/provider-request-tool-names.d.ts +134 -0
  23. package/dist/provider-tool-names.d.ts +4 -5
  24. package/dist/replayable-json-body.d.ts +5 -1
  25. package/dist/sandbox/index.js +2 -2
  26. package/dist/sandbox/routing/backend-resolver.d.ts +6 -5
  27. package/dist/slack-rest-mcp.js +3 -3
  28. package/dist/workspace-tool-gateway.js +8 -8
  29. package/package.json +15 -15
  30. package/src/anthropic-messages.ts +98 -11
  31. package/src/index.ts +2 -1
  32. package/src/metrics.ts +15 -0
  33. package/src/model-provider-client.ts +16 -0
  34. package/src/model-provider-routing.ts +2 -3
  35. package/src/provider-history-adapter.ts +6 -21
  36. package/src/provider-invalid-request.ts +90 -19
  37. package/src/provider-request-tool-names.ts +900 -0
  38. package/src/provider-tool-names.ts +14 -20
  39. package/src/replayable-json-body.ts +171 -3
  40. package/src/sandbox/routing/backend-resolver.ts +9 -9
  41. package/src/single-model-call.ts +2 -1
  42. package/dist/chunk-77NQGL66.js.map +0 -1
  43. package/dist/chunk-FNAYH3SN.js.map +0 -1
  44. package/dist/chunk-JY5NSZ37.js.map +0 -1
  45. /package/dist/{chunk-3MNZZ2B4.js.map → chunk-2MBI6D2F.js.map} +0 -0
  46. /package/dist/{chunk-RZJXTSVA.js.map → chunk-E2YB7OIA.js.map} +0 -0
  47. /package/dist/{chunk-JF5UTPEU.js.map → chunk-JRM6HEPY.js.map} +0 -0
  48. /package/dist/{chunk-GFAFQMZV.js.map → chunk-QNQGZKHJ.js.map} +0 -0
  49. /package/dist/{chunk-OAW6MMSY.js.map → chunk-V7MCFH4O.js.map} +0 -0
@@ -0,0 +1,900 @@
1
+ import {
2
+ invalidRequestBodyOfResponse,
3
+ invalidRequestMessage,
4
+ invalidRequestRawPath,
5
+ invalidRequestSignature,
6
+ } from "./provider-invalid-request";
7
+ import { isProviderToolName, providerToolNameAlias } from "./provider-tool-names";
8
+
9
+ /**
10
+ * The outbound tool-name guard (docs/model-providers.md, "Tool names on the
11
+ * wire").
12
+ *
13
+ * Every model request passes through it once, as the last step before its
14
+ * body is serialized: Responses (HTTP, the Codex WebSocket `response.create`
15
+ * payload, xAI, Azure and gateways), Chat Completions (OpenRouter, Opper,
16
+ * Gemini and other compatible gateways) and Claude Messages. It visits every
17
+ * position a provider validates as a tool name: the request's tool
18
+ * definitions and namespaces, `tool_choice`, and every history item that
19
+ * names a tool or carries definitions (`function_call`, `custom_tool_call`,
20
+ * `tool_search_output`, `additional_tools`, MCP items, Chat `tool_calls`,
21
+ * Claude `tool_use`).
22
+ *
23
+ * A name every provider accepts (`^[a-zA-Z0-9_-]{1,64}$`) is sent byte for
24
+ * byte, and a request without any other name is returned unchanged, so prompt
25
+ * caches never move. Any other name gets its stable alias
26
+ * (`providerToolNameAlias`): the same in every position of the request, never
27
+ * equal to another name of the request (a numeric suffix settles the
28
+ * vanishingly rare clash), and a definition that comes to repeat an earlier
29
+ * name in the same list is dropped. The aliases are remembered for the
30
+ * request, and the provider's answer is mapped back before anything reads
31
+ * it, so a call to an alias runs, is approved and is shown as the original
32
+ * tool.
33
+ *
34
+ * Strict mode, used once after a provider still rejects a tool name, aliases
35
+ * every name, valid or not, to a name of letters, digits and `_` that starts
36
+ * with a letter. When that resend succeeds, the client remembers the one name
37
+ * the provider's error pointed at, for that model (`RejectedToolNames`), so
38
+ * its later requests alias it straight away instead of paying the rejection
39
+ * again; every other name stays byte for byte.
40
+ */
41
+
42
+ export type ToolNameWireApi = "responses" | "chat" | "anthropic-messages";
43
+ /** Where a repaired name sat: the request's tools, `tool_choice`, or history. */
44
+ export type ToolNameField = "tools" | "tool_choice" | "history";
45
+
46
+ type NameRef =
47
+ | { kind: "flat"; name: string; field: ToolNameField }
48
+ | { kind: "namespace"; name: string; field: ToolNameField }
49
+ | { kind: "leaf"; name: string; namespace: string; field: ToolNameField };
50
+ type Visit = (ref: NameRef) => string;
51
+ type Walker = (value: Record<string, unknown>, visit: Visit) => Record<string, unknown>;
52
+
53
+ /** A request's aliases, by the name the provider saw. */
54
+ export class ToolNameAliases {
55
+ constructor(
56
+ private readonly flat: ReadonlyMap<string, string> = new Map(),
57
+ private readonly namespaces: ReadonlyMap<string, string> = new Map(),
58
+ private readonly leaves: ReadonlyMap<string, string> = new Map(),
59
+ ) {}
60
+
61
+ get size(): number {
62
+ return this.flat.size + this.namespaces.size + this.leaves.size;
63
+ }
64
+
65
+ /** The original of a tool name the provider saw (unchanged when it is no alias). */
66
+ restoreFlat(name: string): string {
67
+ return this.flat.get(name) ?? name;
68
+ }
69
+
70
+ restoreNamespace(name: string): string {
71
+ return this.namespaces.get(name) ?? name;
72
+ }
73
+
74
+ /** The original of a name inside a namespace, given the namespace's original. */
75
+ restoreLeaf(namespace: string, name: string): string {
76
+ return this.leaves.get(leafKey(namespace, name)) ?? name;
77
+ }
78
+ }
79
+
80
+ const NO_ALIASES = new ToolNameAliases();
81
+
82
+ const REJECTED_TOOL_NAMES_LIMIT = 1024;
83
+
84
+ /**
85
+ * The tool names a client's route rejected, per model: after a strict
86
+ * resend succeeded, the one name at the path the provider's 400 named.
87
+ * Later requests for that model through the client alias it without a
88
+ * failed attempt first; every other name stays byte for byte. Bounded; the
89
+ * oldest name is forgotten first.
90
+ */
91
+ export class RejectedToolNames {
92
+ private readonly entries = new Set<string>();
93
+
94
+ get size(): number {
95
+ return this.entries.size;
96
+ }
97
+
98
+ /** The names rejected for one model, as the guard's `rejected` option. */
99
+ forModel(model: unknown): RejectedToolNameSet {
100
+ const scope = typeof model === "string" ? model : "";
101
+ return { has: (name) => this.entries.has(rejectedKey(scope, name)) };
102
+ }
103
+
104
+ /**
105
+ * Remember the tool name at the path a provider's error names, in the
106
+ * body that was sent, when it is one of the request's tool names. A path
107
+ * that names no tool name of the request is ignored.
108
+ */
109
+ rememberRejection(
110
+ api: ToolNameWireApi,
111
+ sent: Record<string, unknown>,
112
+ aliases: ToolNameAliases,
113
+ error: unknown,
114
+ ): string | null {
115
+ const name = rejectedToolName(api, sent, error);
116
+ if (name === null) return null;
117
+ const flat = aliases.restoreFlat(name);
118
+ const original = flat !== name ? flat : aliases.restoreNamespace(name);
119
+ const key = rejectedKey(typeof sent.model === "string" ? sent.model : "", original);
120
+ this.entries.delete(key);
121
+ this.entries.add(key);
122
+ if (this.entries.size > REJECTED_TOOL_NAMES_LIMIT) {
123
+ const oldest = this.entries.values().next().value;
124
+ if (oldest !== undefined) this.entries.delete(oldest);
125
+ }
126
+ return original;
127
+ }
128
+ }
129
+
130
+ export type RejectedToolNameSet = { has(name: string): boolean };
131
+
132
+ /**
133
+ * A path segment that names a record's variant rather than a key: its
134
+ * `type`, or Claude's `custom` for a client tool, which has no `type`.
135
+ */
136
+ function isVariantSegment(record: Record<string, unknown>, segment: string): boolean {
137
+ return record.type === segment || (segment === "custom" && record.type === undefined);
138
+ }
139
+
140
+ function rejectedKey(model: string, name: string): string {
141
+ return `${model}\u0000${name}`;
142
+ }
143
+
144
+ /**
145
+ * The tool name at the path of a provider's error (`input[26].tools[1].name`,
146
+ * `messages.1.content.0.tool_use.name`, `tools.0.custom.name`,
147
+ * `tool_choice`), when it is one of the request's tool names. A path
148
+ * segment that is no key of its record but names its variant (Claude's
149
+ * `tool_use`, `custom`) is skipped.
150
+ */
151
+ function rejectedToolName(
152
+ api: ToolNameWireApi,
153
+ sent: Record<string, unknown>,
154
+ error: unknown,
155
+ ): string | null {
156
+ const path = invalidRequestRawPath(error);
157
+ if (path === null) return null;
158
+ let current: unknown = sent;
159
+ for (const match of path.matchAll(/\[(\d+)\]|([^.[\]]+)/g)) {
160
+ const segment = match[1] ?? match[2] ?? "";
161
+ if (Array.isArray(current) && /^\d+$/.test(segment)) {
162
+ current = current[Number(segment)];
163
+ } else if (isRecord(current) && Object.hasOwn(current, segment)) {
164
+ current = current[segment];
165
+ } else if (!(isRecord(current) && isVariantSegment(current, segment))) {
166
+ return null;
167
+ }
168
+ }
169
+ const candidate =
170
+ typeof current === "string"
171
+ ? current
172
+ : isRecord(current) && typeof current.name === "string"
173
+ ? current.name
174
+ : null;
175
+ if (candidate === null) return null;
176
+ let known = false;
177
+ WALKERS[api](sent, (ref) => {
178
+ if (ref.name === candidate) known = true;
179
+ return ref.name;
180
+ });
181
+ return known ? candidate : null;
182
+ }
183
+
184
+ /** Monitoring-only observations of the guard; they never affect a request. */
185
+ export type ToolNameObservers = {
186
+ /** The guard changed a tool name: once per request and field. */
187
+ onToolNameRepair?: (observation: { api: ToolNameWireApi; field: ToolNameField }) => void;
188
+ /** The one strict resend after a provider rejected a tool name. */
189
+ onToolNameRetry?: (observation: {
190
+ api: ToolNameWireApi;
191
+ outcome: "completed" | "failed";
192
+ }) => void;
193
+ };
194
+
195
+ /** Call an observer; a failing one never affects the model call. */
196
+ export function observeToolNames<T>(
197
+ observer: ((observation: T) => void) | undefined,
198
+ observation: T,
199
+ ): void {
200
+ try {
201
+ observer?.(observation);
202
+ } catch {
203
+ // Metrics must never affect a model call.
204
+ }
205
+ }
206
+
207
+ export type GuardedToolNames<T> = {
208
+ /** The request body, the same object when no name changed. */
209
+ body: T;
210
+ aliases: ToolNameAliases;
211
+ /** The fields in which a name changed, for the repair counter. */
212
+ repaired: ToolNameField[];
213
+ };
214
+
215
+ function isRecord(value: unknown): value is Record<string, unknown> {
216
+ return typeof value === "object" && value !== null && !Array.isArray(value);
217
+ }
218
+
219
+ function namespaceOf(record: Record<string, unknown>): string | undefined {
220
+ return typeof record.namespace === "string" && record.namespace.length > 0
221
+ ? record.namespace
222
+ : undefined;
223
+ }
224
+
225
+ function leafKey(namespace: string, name: string): string {
226
+ return `${namespace}\u0000${name}`;
227
+ }
228
+
229
+ /** The record with `key` set, the same record when the value is unchanged. */
230
+ function withValue(
231
+ record: Record<string, unknown>,
232
+ key: string,
233
+ value: unknown,
234
+ ): Record<string, unknown> {
235
+ return record[key] === value ? record : { ...record, [key]: value };
236
+ }
237
+
238
+ function mapList(list: unknown[], map: (entry: unknown) => unknown): unknown[] {
239
+ let changed = false;
240
+ const next = list.map((entry) => {
241
+ const mapped = map(entry);
242
+ if (mapped !== entry) changed = true;
243
+ return mapped;
244
+ });
245
+ return changed ? next : list;
246
+ }
247
+
248
+ /**
249
+ * A definition list with each entry mapped. When a name changed, a
250
+ * definition that repeats an earlier one's name is dropped: providers reject
251
+ * a list that declares one name twice.
252
+ */
253
+ function definitionList(
254
+ list: unknown[],
255
+ map: (entry: unknown) => unknown,
256
+ nameOf: (entry: unknown) => string | undefined,
257
+ ): unknown[] {
258
+ const next = mapList(list, map);
259
+ if (next === list) return list;
260
+ const seen = new Set<string>();
261
+ return next.filter((entry) => {
262
+ const name = nameOf(entry);
263
+ if (name === undefined) return true;
264
+ if (seen.has(name)) return false;
265
+ seen.add(name);
266
+ return true;
267
+ });
268
+ }
269
+
270
+ function nameRef(name: string, namespace: string | undefined, field: ToolNameField): NameRef {
271
+ return namespace === undefined
272
+ ? { kind: "flat", name, field }
273
+ : { kind: "leaf", name, namespace, field };
274
+ }
275
+
276
+ /** Hosted MCP tools are named within their server, like a namespace of their own. */
277
+ function mcpScope(record: Record<string, unknown>): string {
278
+ return `\u0000mcp:${typeof record.server_label === "string" ? record.server_label : ""}`;
279
+ }
280
+
281
+ // ---------------------------------------------------------------- Responses
282
+
283
+ /** A definition's name, with namespaces and tools kept apart. */
284
+ function responsesDefinitionName(entry: unknown): string | undefined {
285
+ if (!isRecord(entry)) return undefined;
286
+ if (entry.type === "tool_reference" || typeof entry.name !== "string") return undefined;
287
+ return `${entry.type === "namespace" ? "namespace" : "tool"}\u0000${entry.name}`;
288
+ }
289
+
290
+ /**
291
+ * One Responses tool definition: a function or custom tool, a namespace and
292
+ * the tools inside it, or a tool search `tool_reference`. Hosted tools carry
293
+ * no name of ours.
294
+ */
295
+ function responsesDefinition(
296
+ entry: unknown,
297
+ visit: Visit,
298
+ field: ToolNameField,
299
+ inNamespace?: string,
300
+ ): unknown {
301
+ if (!isRecord(entry)) return entry;
302
+ if (entry.type === "namespace" && inNamespace === undefined && typeof entry.name === "string") {
303
+ const namespace = entry.name;
304
+ let next = withValue(entry, "name", visit({ kind: "namespace", name: namespace, field }));
305
+ if (Array.isArray(entry.tools)) {
306
+ next = withValue(
307
+ next,
308
+ "tools",
309
+ definitionList(
310
+ entry.tools,
311
+ (tool) => responsesDefinition(tool, visit, field, namespace),
312
+ responsesDefinitionName,
313
+ ),
314
+ );
315
+ }
316
+ return next;
317
+ }
318
+ const nameKey =
319
+ entry.type === "tool_reference"
320
+ ? "function_name"
321
+ : entry.type === "function" || entry.type === "custom"
322
+ ? "name"
323
+ : null;
324
+ if (nameKey === null || typeof entry[nameKey] !== "string") return entry;
325
+ const own = inNamespace === undefined ? namespaceOf(entry) : undefined;
326
+ const namespace = inNamespace ?? own;
327
+ let next = withValue(entry, nameKey, visit(nameRef(entry[nameKey], namespace, field)));
328
+ if (own !== undefined) {
329
+ next = withValue(next, "namespace", visit({ kind: "namespace", name: own, field }));
330
+ }
331
+ return next;
332
+ }
333
+
334
+ /** A call (or forced choice) that names a tool by `name` and an optional `namespace`. */
335
+ function responsesNamedCall(
336
+ record: Record<string, unknown>,
337
+ visit: Visit,
338
+ field: ToolNameField,
339
+ ): Record<string, unknown> {
340
+ if (typeof record.name !== "string") return record;
341
+ const namespace = namespaceOf(record);
342
+ let next = withValue(record, "name", visit(nameRef(record.name, namespace, field)));
343
+ if (namespace !== undefined) {
344
+ next = withValue(next, "namespace", visit({ kind: "namespace", name: namespace, field }));
345
+ }
346
+ return next;
347
+ }
348
+
349
+ function responsesMcpItem(
350
+ record: Record<string, unknown>,
351
+ visit: Visit,
352
+ field: ToolNameField,
353
+ ): Record<string, unknown> {
354
+ const scope = mcpScope(record);
355
+ if (record.type === "mcp_list_tools") {
356
+ if (!Array.isArray(record.tools)) return record;
357
+ return withValue(
358
+ record,
359
+ "tools",
360
+ definitionList(
361
+ record.tools,
362
+ (tool) =>
363
+ isRecord(tool) && typeof tool.name === "string"
364
+ ? withValue(tool, "name", visit(nameRef(tool.name, scope, field)))
365
+ : tool,
366
+ responsesDefinitionName,
367
+ ),
368
+ );
369
+ }
370
+ return typeof record.name === "string"
371
+ ? withValue(record, "name", visit(nameRef(record.name, scope, field)))
372
+ : record;
373
+ }
374
+
375
+ /** One Responses input or output item. */
376
+ function responsesItem(item: unknown, visit: Visit, field: ToolNameField): unknown {
377
+ if (!isRecord(item)) return item;
378
+ switch (item.type) {
379
+ case "function_call":
380
+ case "custom_tool_call":
381
+ return responsesNamedCall(item, visit, field);
382
+ case "tool_search_output":
383
+ case "additional_tools":
384
+ return Array.isArray(item.tools)
385
+ ? withValue(
386
+ item,
387
+ "tools",
388
+ definitionList(
389
+ item.tools,
390
+ (tool) => responsesDefinition(tool, visit, field),
391
+ responsesDefinitionName,
392
+ ),
393
+ )
394
+ : item;
395
+ case "mcp_call":
396
+ case "mcp_approval_request":
397
+ case "mcp_list_tools":
398
+ return responsesMcpItem(item, visit, field);
399
+ default:
400
+ return item;
401
+ }
402
+ }
403
+
404
+ /** The namespaces declared by a request's tools, for qualified forced choices. */
405
+ function declaredNamespaces(tools: unknown): Map<string, Set<string>> {
406
+ const namespaces = new Map<string, Set<string>>();
407
+ if (!Array.isArray(tools)) return namespaces;
408
+ for (const tool of tools) {
409
+ if (!isRecord(tool) || tool.type !== "namespace" || typeof tool.name !== "string") continue;
410
+ const leaves = new Set<string>();
411
+ for (const entry of Array.isArray(tool.tools) ? tool.tools : []) {
412
+ if (isRecord(entry) && typeof entry.name === "string") leaves.add(entry.name);
413
+ }
414
+ namespaces.set(tool.name, leaves);
415
+ }
416
+ return namespaces;
417
+ }
418
+
419
+ /**
420
+ * A forced function choice. The SDK names a tool inside a namespace as
421
+ * `namespace.name`; each part is mapped as the definitions map it.
422
+ */
423
+ function responsesChoiceEntry(
424
+ entry: unknown,
425
+ visit: Visit,
426
+ namespaces: Map<string, Set<string>>,
427
+ ): unknown {
428
+ if (!isRecord(entry)) return entry;
429
+ if (entry.type === "mcp") return responsesMcpItem(entry, visit, "tool_choice");
430
+ if (entry.type !== "function" && entry.type !== "custom") return entry;
431
+ if (typeof entry.name !== "string") return entry;
432
+ if (namespaceOf(entry) === undefined) {
433
+ const name = entry.name;
434
+ for (let dot = name.indexOf("."); dot > 0; dot = name.indexOf(".", dot + 1)) {
435
+ const namespace = name.slice(0, dot);
436
+ const leaf = name.slice(dot + 1);
437
+ if (!namespaces.get(namespace)?.has(leaf)) continue;
438
+ const qualifiedNamespace = visit({
439
+ kind: "namespace",
440
+ name: namespace,
441
+ field: "tool_choice",
442
+ });
443
+ const qualifiedLeaf = visit({ kind: "leaf", name: leaf, namespace, field: "tool_choice" });
444
+ return withValue(entry, "name", `${qualifiedNamespace}.${qualifiedLeaf}`);
445
+ }
446
+ }
447
+ return responsesNamedCall(entry, visit, "tool_choice");
448
+ }
449
+
450
+ function responsesToolChoice(
451
+ choice: unknown,
452
+ visit: Visit,
453
+ namespaces: Map<string, Set<string>>,
454
+ ): unknown {
455
+ if (!isRecord(choice)) return choice;
456
+ if (choice.type === "allowed_tools" && Array.isArray(choice.tools)) {
457
+ return withValue(
458
+ choice,
459
+ "tools",
460
+ mapList(choice.tools, (entry) => responsesChoiceEntry(entry, visit, namespaces)),
461
+ );
462
+ }
463
+ return responsesChoiceEntry(choice, visit, namespaces);
464
+ }
465
+
466
+ const responsesBody: Walker = (body, visit) => {
467
+ let next = body;
468
+ if (Array.isArray(body.tools)) {
469
+ next = withValue(
470
+ next,
471
+ "tools",
472
+ definitionList(
473
+ body.tools,
474
+ (tool) => responsesDefinition(tool, visit, "tools"),
475
+ responsesDefinitionName,
476
+ ),
477
+ );
478
+ }
479
+ if (isRecord(body.tool_choice)) {
480
+ next = withValue(
481
+ next,
482
+ "tool_choice",
483
+ responsesToolChoice(body.tool_choice, visit, declaredNamespaces(body.tools)),
484
+ );
485
+ }
486
+ if (Array.isArray(body.input)) {
487
+ next = withValue(
488
+ next,
489
+ "input",
490
+ mapList(body.input, (item) => responsesItem(item, visit, "history")),
491
+ );
492
+ }
493
+ return next;
494
+ };
495
+
496
+ // -------------------------------------------------------- Chat Completions
497
+
498
+ /** `{type, function: {name}}` or `{type: "custom", custom: {name}}`, as Chat nests names. */
499
+ function chatNamed(entry: unknown, visit: Visit, field: ToolNameField): unknown {
500
+ if (!isRecord(entry)) return entry;
501
+ const key = entry.type === "custom" ? "custom" : "function";
502
+ const inner = entry[key];
503
+ if (!isRecord(inner) || typeof inner.name !== "string") return entry;
504
+ return withValue(
505
+ entry,
506
+ key,
507
+ withValue(inner, "name", visit(nameRef(inner.name, undefined, field))),
508
+ );
509
+ }
510
+
511
+ function chatDefinitionName(entry: unknown): string | undefined {
512
+ if (!isRecord(entry)) return undefined;
513
+ const inner = entry[entry.type === "custom" ? "custom" : "function"];
514
+ return isRecord(inner) && typeof inner.name === "string" ? inner.name : undefined;
515
+ }
516
+
517
+ function chatToolChoice(choice: unknown, visit: Visit): unknown {
518
+ if (!isRecord(choice)) return choice;
519
+ if (choice.type === "allowed_tools" && isRecord(choice.allowed_tools)) {
520
+ const allowed = choice.allowed_tools;
521
+ if (!Array.isArray(allowed.tools)) return choice;
522
+ return withValue(
523
+ choice,
524
+ "allowed_tools",
525
+ withValue(
526
+ allowed,
527
+ "tools",
528
+ mapList(allowed.tools, (entry) => chatNamed(entry, visit, "tool_choice")),
529
+ ),
530
+ );
531
+ }
532
+ return chatNamed(choice, visit, "tool_choice");
533
+ }
534
+
535
+ function chatMessage(message: unknown, visit: Visit): unknown {
536
+ if (!isRecord(message)) return message;
537
+ let next = message;
538
+ if (Array.isArray(message.tool_calls)) {
539
+ next = withValue(
540
+ next,
541
+ "tool_calls",
542
+ mapList(message.tool_calls, (call) => chatNamed(call, visit, "history")),
543
+ );
544
+ }
545
+ if (isRecord(message.function_call) && typeof message.function_call.name === "string") {
546
+ next = withValue(
547
+ next,
548
+ "function_call",
549
+ withValue(
550
+ message.function_call,
551
+ "name",
552
+ visit(nameRef(message.function_call.name, undefined, "history")),
553
+ ),
554
+ );
555
+ }
556
+ if (message.role === "function" && typeof message.name === "string") {
557
+ next = withValue(next, "name", visit(nameRef(message.name, undefined, "history")));
558
+ }
559
+ return next;
560
+ }
561
+
562
+ const chatBody: Walker = (body, visit) => {
563
+ let next = body;
564
+ if (Array.isArray(body.tools)) {
565
+ next = withValue(
566
+ next,
567
+ "tools",
568
+ definitionList(body.tools, (tool) => chatNamed(tool, visit, "tools"), chatDefinitionName),
569
+ );
570
+ }
571
+ if (Array.isArray(body.functions)) {
572
+ next = withValue(
573
+ next,
574
+ "functions",
575
+ definitionList(
576
+ body.functions,
577
+ (fn) =>
578
+ isRecord(fn) && typeof fn.name === "string"
579
+ ? withValue(fn, "name", visit(nameRef(fn.name, undefined, "tools")))
580
+ : fn,
581
+ (fn) => (isRecord(fn) && typeof fn.name === "string" ? fn.name : undefined),
582
+ ),
583
+ );
584
+ }
585
+ if (isRecord(body.tool_choice)) {
586
+ next = withValue(next, "tool_choice", chatToolChoice(body.tool_choice, visit));
587
+ }
588
+ if (isRecord(body.function_call) && typeof body.function_call.name === "string") {
589
+ next = withValue(
590
+ next,
591
+ "function_call",
592
+ withValue(
593
+ body.function_call,
594
+ "name",
595
+ visit(nameRef(body.function_call.name, undefined, "tool_choice")),
596
+ ),
597
+ );
598
+ }
599
+ if (Array.isArray(body.messages)) {
600
+ next = withValue(
601
+ next,
602
+ "messages",
603
+ mapList(body.messages, (message) => chatMessage(message, visit)),
604
+ );
605
+ }
606
+ return next;
607
+ };
608
+
609
+ // ----------------------------------------------------------- Claude Messages
610
+
611
+ /** Claude's own server tools (web search and the like) keep their fixed names. */
612
+ function isClaudeClientTool(tool: Record<string, unknown>): boolean {
613
+ return tool.type === undefined || tool.type === "custom";
614
+ }
615
+
616
+ function claudeDefinitionName(entry: unknown): string | undefined {
617
+ return isRecord(entry) && typeof entry.name === "string" ? entry.name : undefined;
618
+ }
619
+
620
+ function claudeBlock(block: unknown, visit: Visit): unknown {
621
+ if (!isRecord(block) || block.type !== "tool_use" || typeof block.name !== "string") return block;
622
+ return withValue(block, "name", visit(nameRef(block.name, undefined, "history")));
623
+ }
624
+
625
+ const claudeBody: Walker = (body, visit) => {
626
+ let next = body;
627
+ if (Array.isArray(body.tools)) {
628
+ next = withValue(
629
+ next,
630
+ "tools",
631
+ definitionList(
632
+ body.tools,
633
+ (tool) =>
634
+ isRecord(tool) && isClaudeClientTool(tool) && typeof tool.name === "string"
635
+ ? withValue(tool, "name", visit(nameRef(tool.name, undefined, "tools")))
636
+ : tool,
637
+ claudeDefinitionName,
638
+ ),
639
+ );
640
+ }
641
+ if (
642
+ isRecord(body.tool_choice) &&
643
+ body.tool_choice.type === "tool" &&
644
+ typeof body.tool_choice.name === "string"
645
+ ) {
646
+ next = withValue(
647
+ next,
648
+ "tool_choice",
649
+ withValue(
650
+ body.tool_choice,
651
+ "name",
652
+ visit(nameRef(body.tool_choice.name, undefined, "tool_choice")),
653
+ ),
654
+ );
655
+ }
656
+ if (Array.isArray(body.messages)) {
657
+ next = withValue(
658
+ next,
659
+ "messages",
660
+ mapList(body.messages, (message) =>
661
+ isRecord(message) && Array.isArray(message.content)
662
+ ? withValue(
663
+ message,
664
+ "content",
665
+ mapList(message.content, (block) => claudeBlock(block, visit)),
666
+ )
667
+ : message,
668
+ ),
669
+ );
670
+ }
671
+ return next;
672
+ };
673
+
674
+ const WALKERS: Record<ToolNameWireApi, Walker> = {
675
+ responses: responsesBody,
676
+ chat: chatBody,
677
+ "anthropic-messages": claudeBody,
678
+ };
679
+
680
+ // -------------------------------------------------------------------- Guard
681
+
682
+ function identityKey(ref: NameRef): string {
683
+ return ref.kind === "leaf"
684
+ ? `l\u0000${leafKey(ref.namespace, ref.name)}`
685
+ : `${ref.kind === "flat" ? "f" : "n"}\u0000${ref.name}`;
686
+ }
687
+
688
+ /** Flat tools and namespaces share the request's top level; each namespace is its own scope. */
689
+ function scopeKey(ref: NameRef): string {
690
+ return ref.kind === "leaf" ? `l\u0000${ref.namespace}` : "top";
691
+ }
692
+
693
+ export type ToolNameGuardOptions = {
694
+ /** Alias every name, valid or not (the one retry after a rejected name). */
695
+ strict?: boolean;
696
+ /** Names the client's route rejected before; they are aliased too. */
697
+ rejected?: RejectedToolNameSet;
698
+ };
699
+
700
+ /**
701
+ * The request body with every tool name a provider could reject replaced by
702
+ * its alias, consistently across the request, and the aliases to map the
703
+ * answer back with (see the module comment).
704
+ */
705
+ export function guardRequestToolNames<T extends Record<string, unknown>>(
706
+ api: ToolNameWireApi,
707
+ body: T,
708
+ options: ToolNameGuardOptions = {},
709
+ ): GuardedToolNames<T> {
710
+ const walk = WALKERS[api];
711
+ const strict = options.strict === true;
712
+ const rejected = options.rejected;
713
+ const refs: NameRef[] = [];
714
+ walk(body, (ref) => {
715
+ refs.push(ref);
716
+ return ref.name;
717
+ });
718
+ const renames = (ref: NameRef) =>
719
+ strict || !isProviderToolName(ref.name) || rejected?.has(ref.name) === true;
720
+ if (!refs.some(renames)) return { body, aliases: NO_ALIASES, repaired: [] };
721
+
722
+ // Names that stay as they are, per scope; an alias never takes one.
723
+ const taken = new Map<string, Set<string>>();
724
+ const takenIn = (scope: string) => {
725
+ let names = taken.get(scope);
726
+ if (!names) taken.set(scope, (names = new Set()));
727
+ return names;
728
+ };
729
+ const pending = new Map<string, NameRef>();
730
+ const repaired = new Set<ToolNameField>();
731
+ for (const ref of refs) {
732
+ if (!renames(ref)) {
733
+ takenIn(scopeKey(ref)).add(ref.name);
734
+ continue;
735
+ }
736
+ repaired.add(ref.field);
737
+ const key = identityKey(ref);
738
+ if (!pending.has(key)) pending.set(key, ref);
739
+ }
740
+
741
+ const forward = new Map<string, string>();
742
+ const flat = new Map<string, string>();
743
+ const namespaces = new Map<string, string>();
744
+ const leaves = new Map<string, string>();
745
+ for (const key of [...pending.keys()].sort()) {
746
+ const ref = pending.get(key)!;
747
+ const names = takenIn(scopeKey(ref));
748
+ const base = providerToolNameAlias(ref.name);
749
+ let alias = base;
750
+ for (let suffix = 2; names.has(alias); suffix += 1) alias = `${base}_${suffix}`;
751
+ names.add(alias);
752
+ forward.set(key, alias);
753
+ if (ref.kind === "flat") flat.set(alias, ref.name);
754
+ else if (ref.kind === "namespace") namespaces.set(alias, ref.name);
755
+ else leaves.set(leafKey(ref.namespace, alias), ref.name);
756
+ }
757
+ const guarded = walk(body, (ref) => forward.get(identityKey(ref)) ?? ref.name) as T;
758
+ return {
759
+ body: guarded,
760
+ aliases: new ToolNameAliases(flat, namespaces, leaves),
761
+ repaired: [...repaired].sort(),
762
+ };
763
+ }
764
+
765
+ /**
766
+ * The visitor that maps the names a provider saw back to their originals. A
767
+ * name inside a namespace is looked up under the namespace's original.
768
+ */
769
+ function restoring(aliases: ToolNameAliases): Visit {
770
+ return (ref) =>
771
+ ref.kind === "flat"
772
+ ? aliases.restoreFlat(ref.name)
773
+ : ref.kind === "namespace"
774
+ ? aliases.restoreNamespace(ref.name)
775
+ : aliases.restoreLeaf(aliases.restoreNamespace(ref.namespace), ref.name);
776
+ }
777
+
778
+ /**
779
+ * A Responses answer with its tool names restored: a response (`output`),
780
+ * or a stream event (`item`, `response`, or a call event's `name`).
781
+ */
782
+ export function restoreResponsesToolNames<T>(payload: T, aliases: ToolNameAliases): T {
783
+ if (aliases.size === 0 || !isRecord(payload)) return payload;
784
+ const visit = restoring(aliases);
785
+ let next: Record<string, unknown> = payload;
786
+ if (Array.isArray(payload.output)) {
787
+ next = withValue(
788
+ next,
789
+ "output",
790
+ mapList(payload.output, (item) => responsesItem(item, visit, "history")),
791
+ );
792
+ }
793
+ if (isRecord(payload.item)) {
794
+ next = withValue(next, "item", responsesItem(payload.item, visit, "history"));
795
+ }
796
+ if (isRecord(payload.response)) {
797
+ next = withValue(next, "response", restoreResponsesToolNames(payload.response, aliases));
798
+ }
799
+ if (
800
+ typeof payload.type === "string" &&
801
+ payload.type.startsWith("response.") &&
802
+ typeof payload.name === "string"
803
+ ) {
804
+ if (typeof payload.namespace === "string") {
805
+ const namespace = aliases.restoreNamespace(payload.namespace);
806
+ next = withValue(next, "namespace", namespace);
807
+ next = withValue(next, "name", aliases.restoreLeaf(namespace, payload.name));
808
+ } else {
809
+ next = withValue(next, "name", aliases.restoreFlat(payload.name));
810
+ }
811
+ }
812
+ return next as T;
813
+ }
814
+
815
+ /** A Chat completion or stream chunk with its tool call names restored. */
816
+ export function restoreChatToolNames<T>(payload: T, aliases: ToolNameAliases): T {
817
+ if (aliases.size === 0 || !isRecord(payload) || !Array.isArray(payload.choices)) return payload;
818
+ const visit = restoring(aliases);
819
+ return withValue(
820
+ payload,
821
+ "choices",
822
+ mapList(payload.choices, (choice) => {
823
+ if (!isRecord(choice)) return choice;
824
+ let next = choice;
825
+ for (const key of ["message", "delta"]) {
826
+ if (isRecord(choice[key])) next = withValue(next, key, chatMessage(choice[key], visit));
827
+ }
828
+ return next;
829
+ }),
830
+ ) as T;
831
+ }
832
+
833
+ /** A Claude message (`content`) or stream event (`content_block`) with tool names restored. */
834
+ export function restoreClaudeToolNames<T>(payload: T, aliases: ToolNameAliases): T {
835
+ if (aliases.size === 0 || !isRecord(payload)) return payload;
836
+ const visit = restoring(aliases);
837
+ let next: Record<string, unknown> = payload;
838
+ if (Array.isArray(payload.content)) {
839
+ next = withValue(
840
+ next,
841
+ "content",
842
+ mapList(payload.content, (block) => claudeBlock(block, visit)),
843
+ );
844
+ }
845
+ if (isRecord(payload.content_block)) {
846
+ next = withValue(next, "content_block", claudeBlock(payload.content_block, visit));
847
+ }
848
+ return next as T;
849
+ }
850
+
851
+ /** The tool names an answer of this API carries, restored. */
852
+ export function restoreToolNames<T>(api: ToolNameWireApi, payload: T, aliases: ToolNameAliases): T {
853
+ return api === "responses"
854
+ ? restoreResponsesToolNames(payload, aliases)
855
+ : api === "chat"
856
+ ? restoreChatToolNames(payload, aliases)
857
+ : restoreClaudeToolNames(payload, aliases);
858
+ }
859
+
860
+ // ------------------------------------------------------- Rejected-name retry
861
+
862
+ const NAME_FIELD_PATH = /(?:^|\.)(?:name|namespace|function_name|tool_name)$/;
863
+ const STRING_CONSTRAINT =
864
+ /pattern|invalid_string|invalid string|maximum length|too long|string_above_max_length|invalid (?:tool|function) name/i;
865
+
866
+ /**
867
+ * Whether a provider's 400 says a tool name (a `…name` or `…namespace` field,
868
+ * or `tool_choice`) breaks its string constraints: the one rejection the
869
+ * strict retry can fix. Its path is read as the invalid-request counter reads
870
+ * it (`invalidRequestSignature`).
871
+ */
872
+ export function isToolNameRejection(
873
+ signature: { path: string; code: string },
874
+ message: string,
875
+ ): boolean {
876
+ if (signature.path === "unknown") return false;
877
+ const path = signature.path.replace(/\[\]$/, "");
878
+ const namePath = NAME_FIELD_PATH.test(path) || /^tool_choice\b/.test(path);
879
+ return namePath && (STRING_CONSTRAINT.test(signature.code) || STRING_CONSTRAINT.test(message));
880
+ }
881
+
882
+ /** Whether a provider error body rejects a tool name (see isToolNameRejection). */
883
+ export function rejectsToolName(body: unknown): boolean {
884
+ return isToolNameRejection(invalidRequestSignature(body), invalidRequestMessage(body));
885
+ }
886
+
887
+ /**
888
+ * The error body of a 400 response that rejects a tool name, read from a
889
+ * bounded clone; null for every other response.
890
+ */
891
+ export async function toolNameRejectionOfResponse(response: Response): Promise<unknown> {
892
+ if (response.status !== 400) return null;
893
+ const body = await invalidRequestBodyOfResponse(response);
894
+ return body !== null && rejectsToolName(body) ? body : null;
895
+ }
896
+
897
+ /** Whether a 400 response rejects a tool name; its body is read from a clone. */
898
+ export async function responseRejectsToolName(response: Response): Promise<boolean> {
899
+ return (await toolNameRejectionOfResponse(response)) !== null;
900
+ }