@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
@@ -26,7 +26,16 @@ import { withClaudeModelRequest } from "./claude-subscription-usage";
26
26
  import { createModelImageSizer } from "./model-image-sizing";
27
27
  import { isModelPreempted, preemptedResponseDone } from "./model-preemption";
28
28
  import { projectHistoryForProvider } from "./provider-history-adapter";
29
- import { requestFunctionToolNames } from "./provider-tool-names";
29
+ import {
30
+ guardRequestToolNames,
31
+ RejectedToolNames,
32
+ observeToolNames,
33
+ rejectsToolName,
34
+ restoreClaudeToolNames,
35
+ type ToolNameAliases,
36
+ type ToolNameObservers,
37
+ } from "./provider-request-tool-names";
38
+ import { parseInvalidRequestText } from "./provider-invalid-request";
30
39
  import { projectHostedSearchEvidence } from "./hosted-search-evidence";
31
40
  import { splitStableSystemPromptPrefix } from "./system-prompt-cache-prefix";
32
41
  import {
@@ -707,9 +716,7 @@ export function buildAnthropicRequest(
707
716
  const input =
708
717
  typeof request.input === "string"
709
718
  ? request.input
710
- : (projectHistoryForProvider(request.input, "anthropic-messages", {
711
- knownToolNames: requestFunctionToolNames(request.tools),
712
- }) as ModelRequest["input"]);
719
+ : (projectHistoryForProvider(request.input, "anthropic-messages") as ModelRequest["input"]);
713
720
  const webSearch = request.tools.some(isHostedWebSearchTool);
714
721
  let messages = anthropicMessages(input, {
715
722
  webSearch,
@@ -1148,12 +1155,23 @@ export class AnthropicMessagesModel implements Model {
1148
1155
  // The same bound applies from the first image onward. A growing conversation
1149
1156
  // must not resize its old prefix when it crosses the many-image threshold.
1150
1157
  private readonly sizeImage = createModelImageSizer(2000, ANTHROPIC_IMAGE_MAX_ENCODED_BYTES);
1158
+ /** The tool-name aliases each response answers (see provider-request-tool-names.ts). */
1159
+ private readonly toolNameAliases = new WeakMap<Response, ToolNameAliases>();
1160
+ /** Names this model's route rejected (see RejectedToolNames). */
1161
+ private readonly rejectedToolNames = new RejectedToolNames();
1151
1162
  constructor(
1152
1163
  readonly provider: ResolvedModelProvider,
1153
1164
  readonly model: string,
1154
1165
  private readonly fetch: typeof globalThis.fetch = globalThis.fetch,
1166
+ private readonly toolNameObservers: ToolNameObservers = {},
1155
1167
  ) {}
1156
1168
 
1169
+ /** A Claude message or stream event with aliased tool names mapped back. */
1170
+ private restoredToolNames<T>(response: Response, payload: T): T {
1171
+ const aliases = this.toolNameAliases.get(response);
1172
+ return aliases ? restoreClaudeToolNames(payload, aliases) : payload;
1173
+ }
1174
+
1157
1175
  /** Project inline images only; never fetch arbitrary URLs or edit stored history. */
1158
1176
  private async sizeImageBlocks(
1159
1177
  blocks: Json[],
@@ -1210,7 +1228,7 @@ export class AnthropicMessagesModel implements Model {
1210
1228
  );
1211
1229
  }
1212
1230
 
1213
- private async prepare(request: ModelRequest, stream: boolean) {
1231
+ private async prepare(request: ModelRequest, stream: boolean, strictToolNames = false) {
1214
1232
  request.signal?.throwIfAborted();
1215
1233
  const body = buildAnthropicRequest(request, this.model, this.provider, stream);
1216
1234
  const projection = { resized: false };
@@ -1295,8 +1313,20 @@ export class AnthropicMessagesModel implements Model {
1295
1313
  previousRequestId: this.previousRequestId,
1296
1314
  });
1297
1315
  }
1298
- const serialized = JSON.stringify(body);
1299
- return { url, headers, serialized, size: anthropicRequestSize(body, serialized) };
1316
+ // The outbound tool-name guard runs last, on the body as it is sent.
1317
+ const guarded = guardRequestToolNames("anthropic-messages", body, {
1318
+ strict: strictToolNames,
1319
+ rejected: this.rejectedToolNames.forModel(body.model),
1320
+ });
1321
+ const serialized = JSON.stringify(guarded.body);
1322
+ return {
1323
+ url,
1324
+ headers,
1325
+ serialized,
1326
+ size: anthropicRequestSize(guarded.body, serialized),
1327
+ toolNames: guarded,
1328
+ unguardedBody: body,
1329
+ };
1300
1330
  }
1301
1331
 
1302
1332
  /** Uses the same final serialization as dispatch, but performs no network I/O. */
@@ -1304,8 +1334,32 @@ export class AnthropicMessagesModel implements Model {
1304
1334
  return (await this.prepare(request, stream)).size;
1305
1335
  }
1306
1336
 
1307
- private async send(request: ModelRequest, stream: boolean): Promise<Response> {
1308
- const { url, headers, serialized, size } = await this.prepare(request, stream);
1337
+ /**
1338
+ * Send one request. A 400 that rejects a tool name is answered by sending
1339
+ * the request once more with every tool name aliased (strict mode); that
1340
+ * resend is never repeated, and its own answer is final.
1341
+ */
1342
+ private async send(
1343
+ request: ModelRequest,
1344
+ stream: boolean,
1345
+ strictToolNames = false,
1346
+ ): Promise<Response> {
1347
+ const {
1348
+ url,
1349
+ headers,
1350
+ serialized,
1351
+ size,
1352
+ toolNames: guardedToolNames,
1353
+ unguardedBody,
1354
+ } = await this.prepare(request, stream, strictToolNames);
1355
+ if (!strictToolNames) {
1356
+ for (const field of guardedToolNames.repaired) {
1357
+ observeToolNames(this.toolNameObservers.onToolNameRepair, {
1358
+ api: "anthropic-messages",
1359
+ field,
1360
+ });
1361
+ }
1362
+ }
1309
1363
  if (size.requestBytes > ANTHROPIC_REQUEST_MAX_BYTES)
1310
1364
  throw new AnthropicRequestSizeError(size, "preflight");
1311
1365
  request.signal?.throwIfAborted();
@@ -1331,6 +1385,36 @@ export class AnthropicMessagesModel implements Model {
1331
1385
  Math.min(this.provider.anthropic?.streamIdleTimeoutMs ?? 600000, 5000),
1332
1386
  request.signal,
1333
1387
  );
1388
+ if (
1389
+ !strictToolNames &&
1390
+ response.status === 400 &&
1391
+ rejectsToolName(parseInvalidRequestText(detail)) &&
1392
+ // Without a tool name to alias, a resend would repeat the same request.
1393
+ guardRequestToolNames("anthropic-messages", unguardedBody, { strict: true }).body !==
1394
+ unguardedBody
1395
+ ) {
1396
+ let resent: Response;
1397
+ try {
1398
+ resent = await this.send(request, stream, true);
1399
+ } catch (error) {
1400
+ observeToolNames(this.toolNameObservers.onToolNameRetry, {
1401
+ api: "anthropic-messages",
1402
+ outcome: "failed",
1403
+ });
1404
+ throw error;
1405
+ }
1406
+ observeToolNames(this.toolNameObservers.onToolNameRetry, {
1407
+ api: "anthropic-messages",
1408
+ outcome: "completed",
1409
+ });
1410
+ this.rejectedToolNames.rememberRejection(
1411
+ "anthropic-messages",
1412
+ guardedToolNames.body,
1413
+ guardedToolNames.aliases,
1414
+ parseInvalidRequestText(detail),
1415
+ );
1416
+ return resent;
1417
+ }
1334
1418
  const contextExceeded =
1335
1419
  response.status === 400 &&
1336
1420
  /prompt is too long|context_length_exceeded|exceeds.*context window/i.test(detail);
@@ -1378,6 +1462,8 @@ export class AnthropicMessagesModel implements Model {
1378
1462
  );
1379
1463
  }
1380
1464
  this.previousRequestId = response.headers.get("request-id") ?? undefined;
1465
+ if (guardedToolNames.aliases.size > 0)
1466
+ this.toolNameAliases.set(response, guardedToolNames.aliases);
1381
1467
  return response;
1382
1468
  }
1383
1469
 
@@ -1393,7 +1479,7 @@ export class AnthropicMessagesModel implements Model {
1393
1479
  : request;
1394
1480
  const response = await this.send(current, false);
1395
1481
  requestId = response.headers.get("request-id") ?? undefined;
1396
- const message = object(await response.json());
1482
+ const message = object(this.restoredToolNames(response, await response.json()));
1397
1483
  if (message.stop_reason === "refusal")
1398
1484
  throw new AnthropicProviderRejection("content_policy_violation", 200, requestId);
1399
1485
  merged = mergePausedMessage(merged, message);
@@ -1510,11 +1596,12 @@ export class AnthropicMessagesModel implements Model {
1510
1596
  partial.blocks = blocks;
1511
1597
  let message: Json | undefined;
1512
1598
  let finalDelta = false;
1513
- for await (const event of anthropicSse(
1599
+ for await (const streamed of anthropicSse(
1514
1600
  response.body,
1515
1601
  this.provider.anthropic?.streamIdleTimeoutMs ?? 600000,
1516
1602
  request.signal,
1517
1603
  )) {
1604
+ const event = this.restoredToolNames(response, streamed);
1518
1605
  request.signal?.throwIfAborted();
1519
1606
  if (event.type === "error") {
1520
1607
  const kind = event.error?.type;
package/src/index.ts CHANGED
@@ -76,7 +76,7 @@ export {
76
76
  type SingleModelCallResult,
77
77
  type SingleModelCallTarget,
78
78
  } from "./single-model-call";
79
- import { instrumentedModelFetch } from "./model-provider-client";
79
+ import { instrumentedModelFetch, modelToolNameObservers } from "./model-provider-client";
80
80
  import { inferenceResidencyRequirement, sideFeatureRouteRunnable } from "./inference-residency";
81
81
  import type { ModelProviderApi, ResolvedModelProvider, Settings } from "@opengeni/config";
82
82
  import { isRunMcpCredentialError, RunMcpCredentials } from "./mcp-run-credentials";
@@ -1571,6 +1571,7 @@ export async function summarizeForCompaction(
1571
1571
  false,
1572
1572
  inferenceResidencyRequirement(settings),
1573
1573
  ),
1574
+ modelToolNameObservers(provider.id),
1574
1575
  );
1575
1576
  const claudeRequest = (forbidToolCalls: boolean) =>
1576
1577
  anthropicCompactionRequest(input, {
package/src/metrics.ts CHANGED
@@ -111,6 +111,21 @@ export type RuntimeMetricsHooks = {
111
111
  * path it names (indices collapsed) and its error code. Monitoring only.
112
112
  */
113
113
  onModelInvalidRequest?: (input: { provider: string; path: string; code: string }) => void;
114
+ /**
115
+ * The outbound tool-name guard changed a tool name a provider could reject,
116
+ * once per request and field (`tools`, `tool_choice`, `history`).
117
+ */
118
+ onModelToolNameRepair?: (input: {
119
+ provider: string;
120
+ api: "responses" | "chat" | "anthropic-messages";
121
+ field: "tools" | "tool_choice" | "history";
122
+ }) => void;
123
+ /** The one strict resend after a provider still rejected a tool name, by its outcome. */
124
+ onModelToolNameRetry?: (input: {
125
+ provider: string;
126
+ api: "responses" | "chat" | "anthropic-messages";
127
+ outcome: "completed" | "failed";
128
+ }) => void;
114
129
  onSandboxCreate?: (input: {
115
130
  backend: string;
116
131
  imageSource: "logical" | "provider_immutable";
@@ -66,6 +66,7 @@ import {
66
66
  } from "./model-provider-request-policy";
67
67
  import { isModelCallFetch, vercelGatewayRoutingFetch } from "./model-provider-transport";
68
68
  import { ReplayableJsonOpenAI } from "./replayable-json-body";
69
+ import type { ToolNameObservers } from "./provider-request-tool-names";
69
70
  import {
70
71
  recordModelTransportDispatched,
71
72
  recordModelTransportStarted,
@@ -88,6 +89,16 @@ export function configureRuntimeMetricsHooks(hooks: RuntimeMetricsHooks | null |
88
89
  runtimeMetricsHooks = hooks ?? null;
89
90
  }
90
91
 
92
+ /** The outbound tool-name guard's observations for one provider, as metrics. */
93
+ export function modelToolNameObservers(provider: string): ToolNameObservers {
94
+ return {
95
+ onToolNameRepair: ({ api, field }) =>
96
+ runtimeMetricsHooks?.onModelToolNameRepair?.({ provider, api, field }),
97
+ onToolNameRetry: ({ api, outcome }) =>
98
+ runtimeMetricsHooks?.onModelToolNameRetry?.({ provider, api, outcome }),
99
+ };
100
+ }
101
+
91
102
  export function recordRuntimeMcpToolCallMetric(
92
103
  outcome: McpToolCallOutcome,
93
104
  tool: string,
@@ -176,6 +187,7 @@ export function buildOpenAIClientFromSettings(
176
187
  ),
177
188
  },
178
189
  {
190
+ ...modelToolNameObservers(providerId),
179
191
  modelRequestPolicy: (request) =>
180
192
  chatModelRequestPolicy(request) ?? azureModelRequestPolicy(request),
181
193
  },
@@ -201,6 +213,7 @@ export function buildOpenAIClientFromSettings(
201
213
  ),
202
214
  },
203
215
  {
216
+ ...modelToolNameObservers(providerId),
204
217
  // Only the OpenAI platform; a compatible server keeps its own contract.
205
218
  modelRequestPolicy: isDirectOpenAiApiBaseUrl(settings.openaiBaseUrl)
206
219
  ? withStorelessResponses(chatModelRequestPolicy)
@@ -679,6 +692,7 @@ export function buildProviderClient(provider: ResolvedModelProvider, settings: S
679
692
  ),
680
693
  },
681
694
  {
695
+ ...modelToolNameObservers(provider.id),
682
696
  modelRequestPolicy: modelRequestPolicyForProvider(
683
697
  provider,
684
698
  gatewayPolicies,
@@ -705,6 +719,7 @@ export function buildProviderClient(provider: ResolvedModelProvider, settings: S
705
719
  ),
706
720
  },
707
721
  {
722
+ ...modelToolNameObservers(provider.id),
708
723
  modelRequestPolicy: modelRequestPolicyForProvider(
709
724
  provider,
710
725
  gatewayPolicies,
@@ -788,6 +803,7 @@ export function buildProviderClient(provider: ResolvedModelProvider, settings: S
788
803
  ),
789
804
  },
790
805
  {
806
+ ...modelToolNameObservers(provider.id),
791
807
  modelRequestPolicy: modelRequestPolicyForProvider(
792
808
  provider,
793
809
  gatewayPolicies,
@@ -27,7 +27,6 @@ import {
27
27
  projectHistoryForProvider,
28
28
  responsesRouteDeclaresAdditionalTools,
29
29
  } from "./provider-history-adapter";
30
- import { requestFunctionToolNames } from "./provider-tool-names";
31
30
  import {
32
31
  appendChatReasoningDetails,
33
32
  chatReasoning,
@@ -37,7 +36,7 @@ import {
37
36
  withChatReasoning,
38
37
  type ChatReasoning,
39
38
  } from "./chat-reasoning";
40
- import { instrumentedModelFetch } from "./model-provider-client";
39
+ import { instrumentedModelFetch, modelToolNameObservers } from "./model-provider-client";
41
40
  import { CODEX_MODEL_ID_PREFIX } from "@opengeni/codex";
42
41
  import { XAI_SUBSCRIPTION_MODEL_ID_PREFIX } from "@opengeni/xai-subscription";
43
42
 
@@ -366,7 +365,6 @@ export class OpenGeniResponsesModel extends AppendOnlyOpenAIResponsesModel {
366
365
  ? request.input
367
366
  : (projectHistoryForProvider(request.input, "responses", {
368
367
  declaresAdditionalTools: responsesRouteDeclaresAdditionalTools(this.provider.kind),
369
- knownToolNames: requestFunctionToolNames(request.tools),
370
368
  }) as ModelRequest["input"]);
371
369
  return super._buildResponsesCreateRequest(
372
370
  input === request.input ? request : { ...request, input },
@@ -398,6 +396,7 @@ export function buildModelInstance(
398
396
  provider,
399
397
  modelId,
400
398
  instrumentedModelFetch(provider.id, globalThis.fetch, false, residency),
399
+ modelToolNameObservers(provider.id),
401
400
  );
402
401
  return provider.api === "chat"
403
402
  ? new OpenGeniChatCompletionsModel(client, modelId)
@@ -7,7 +7,6 @@ import {
7
7
  withSearchRecordsAfterOpenCalls,
8
8
  type SearchRecordForm,
9
9
  } from "./hosted-search-evidence";
10
- import { withProviderValidToolNames } from "./provider-tool-names";
11
10
 
12
11
  export type HistoryProviderApi = "responses" | "chat" | "anthropic-messages";
13
12
 
@@ -33,12 +32,6 @@ export type ProviderHistoryOptions = {
33
32
  * replay them natively.
34
33
  */
35
34
  searchRecordForm?: SearchRecordForm;
36
- /**
37
- * The request's function tool names, which history keeps as written. Any
38
- * other history tool name a provider would reject gets its stable alias
39
- * (see withProviderValidToolNames).
40
- */
41
- knownToolNames?: readonly string[];
42
35
  };
43
36
 
44
37
  /** The one tool-name format every Chat route and gateway accepts. */
@@ -345,20 +338,12 @@ export function projectHistoryForProvider(
345
338
  }),
346
339
  );
347
340
  const input = projected.every((item, index) => item === items[index]) ? items : projected;
348
- // Every API validates the tool names of history items that carry tool
349
- // definitions or call a tool, and one invalid name fails the whole request.
350
- // The lazy tool transport already bound names to the authorized catalog;
351
- // with only the request's tools here, a name is never guessed, only aliased,
352
- // so a definition, a disclosure and the calls that name it keep one valid
353
- // name. Chat keeps its own treatment: a call with an invalid name replays as
354
- // a historical fact (isChatIncompatibleCall) rather than as a native call to
355
- // a tool the request never declares.
356
- const wireValid = withWireValidFunctionCallArguments(input);
357
- const named =
358
- providerApi === "chat"
359
- ? wireValid
360
- : withProviderValidToolNames(wireValid, { names: options.knownToolNames ?? [] });
361
- return projectWireHistory(named, providerApi, options);
341
+ // Tool names a provider would reject are made valid on the wire by the
342
+ // outbound guard (provider-request-tool-names.ts), one alias per name in
343
+ // every position. Chat keeps its own treatment of history: a call with an
344
+ // invalid name replays as a historical fact (isChatIncompatibleCall) rather
345
+ // than as a native call to a tool the request never declares.
346
+ return projectWireHistory(withWireValidFunctionCallArguments(input), providerApi, options);
362
347
  }
363
348
 
364
349
  /**
@@ -18,7 +18,7 @@ const CODE = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;
18
18
  * roots count, so no other word of a message is ever taken for a path.
19
19
  */
20
20
  const EMBEDDED_PATH =
21
- /\b((?:input|messages|tools|contents|system|instructions)(?:\[\d+\]|\.\d+|\.[A-Za-z_]\w*)+)/;
21
+ /\b((?:input|messages|tools|tool_choice|contents|system|instructions)(?:\[\d+\]|\.\d+|\.[A-Za-z_]\w*)+)/;
22
22
 
23
23
  function record(value: unknown): Record<string, unknown> | null {
24
24
  return typeof value === "object" && value !== null && !Array.isArray(value)
@@ -47,31 +47,102 @@ function errorCode(error: Record<string, unknown>): string {
47
47
  return "unknown";
48
48
  }
49
49
 
50
- /** The signature of a parsed provider error body (OpenAI, Claude, gateways). */
51
- export function invalidRequestSignature(body: unknown): InvalidRequestSignature {
50
+ function errorRecord(body: unknown): Record<string, unknown> {
52
51
  const envelope = record(body);
53
- const error = record(envelope?.error) ?? envelope ?? {};
52
+ return record(envelope?.error) ?? envelope ?? {};
53
+ }
54
+
55
+ /** The message of a parsed provider error body, never recorded. */
56
+ export function invalidRequestMessage(body: unknown): string {
57
+ const message = errorRecord(body).message;
58
+ return typeof message === "string" ? message : "";
59
+ }
60
+
61
+ /**
62
+ * The request path a parsed provider error body names, as written
63
+ * (`input[26].tools[1].name`), or null. Used to find the rejected value in
64
+ * the request; never recorded.
65
+ */
66
+ export function invalidRequestRawPath(body: unknown): string | null {
67
+ const error = errorRecord(body);
54
68
  const message = typeof error.message === "string" ? error.message : "";
55
- const raw =
56
- (typeof error.param === "string" && error.param) || EMBEDDED_PATH.exec(message)?.[1] || null;
57
- return { path: (raw && normalizedPath(raw)) || "unknown", code: errorCode(error) };
69
+ return (
70
+ (typeof error.param === "string" && error.param) || EMBEDDED_PATH.exec(message)?.[1] || null
71
+ );
58
72
  }
59
73
 
60
- /** The signature of a 400 response's body, read from a clone; null when unreadable. */
61
- export async function invalidRequestSignatureOfResponse(
62
- response: Response,
63
- ): Promise<InvalidRequestSignature | null> {
74
+ /** The signature of a parsed provider error body (OpenAI, Claude, gateways). */
75
+ export function invalidRequestSignature(body: unknown): InvalidRequestSignature {
76
+ const raw = invalidRequestRawPath(body);
77
+ return {
78
+ path: (raw && normalizedPath(raw)) || "unknown",
79
+ code: errorCode(errorRecord(body)),
80
+ };
81
+ }
82
+
83
+ /** A provider error body's text, parsed; text that is not JSON is its message. */
84
+ export function parseInvalidRequestText(text: string): unknown {
85
+ if (text.length > MAX_BODY_CHARACTERS) return {};
64
86
  try {
65
- const text = await response.clone().text();
66
- if (text.length > MAX_BODY_CHARACTERS) return { path: "unknown", code: "unknown" };
67
- let body: unknown;
68
- try {
69
- body = JSON.parse(text);
70
- } catch {
71
- body = { message: text };
87
+ return JSON.parse(text);
88
+ } catch {
89
+ return { message: text };
90
+ }
91
+ }
92
+
93
+ const ERROR_BODY_READ_TIMEOUT_MS = 5_000;
94
+
95
+ /**
96
+ * A response's text from a clone, or null when it is longer than
97
+ * MAX_BODY_CHARACTERS bytes or does not arrive within a few seconds.
98
+ */
99
+ async function boundedCloneText(response: Response): Promise<string | null> {
100
+ const reader = response.clone().body?.getReader();
101
+ if (!reader) return "";
102
+ const chunks: Uint8Array[] = [];
103
+ let bytes = 0;
104
+ let timer: ReturnType<typeof setTimeout> | undefined;
105
+ const deadline = new Promise<null>((resolve) => {
106
+ timer = setTimeout(() => resolve(null), ERROR_BODY_READ_TIMEOUT_MS);
107
+ });
108
+ const read = (async (): Promise<string | null> => {
109
+ for (;;) {
110
+ const next = await reader.read();
111
+ if (next.done) break;
112
+ bytes += next.value.byteLength;
113
+ if (bytes > MAX_BODY_CHARACTERS) return null;
114
+ chunks.push(next.value);
72
115
  }
73
- return invalidRequestSignature(body);
116
+ const joined = new Uint8Array(bytes);
117
+ let offset = 0;
118
+ for (const chunk of chunks) {
119
+ joined.set(chunk, offset);
120
+ offset += chunk.byteLength;
121
+ }
122
+ return new TextDecoder().decode(joined);
123
+ })().catch(() => null);
124
+ try {
125
+ return await Promise.race([read, deadline]);
126
+ } finally {
127
+ clearTimeout(timer);
128
+ void reader.cancel().catch(() => undefined);
129
+ }
130
+ }
131
+
132
+ /** A 400 response's error body, read from a bounded clone; null when unreadable. */
133
+ export async function invalidRequestBodyOfResponse(response: Response): Promise<unknown> {
134
+ try {
135
+ const text = await boundedCloneText(response);
136
+ return text === null ? null : parseInvalidRequestText(text);
74
137
  } catch {
75
138
  return null;
76
139
  }
77
140
  }
141
+
142
+ /** The signature of a 400 response's body, read from a clone; null when unreadable. */
143
+ export async function invalidRequestSignatureOfResponse(
144
+ response: Response,
145
+ ): Promise<InvalidRequestSignature | null> {
146
+ const body = await invalidRequestBodyOfResponse(response);
147
+ return body === null ? null : invalidRequestSignature(body);
148
+ }