@opengeni/runtime 4.3.0-canary.36855269964001 → 4.3.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 (51) hide show
  1. package/dist/assets/codemode-client.json +1 -1
  2. package/dist/{chunk-PEEYZDLS.js → chunk-22M75RJF.js} +622 -890
  3. package/dist/chunk-22M75RJF.js.map +1 -0
  4. package/dist/{chunk-BK3S65CI.js → chunk-JUFVYQCY.js} +13 -91
  5. package/dist/chunk-JUFVYQCY.js.map +1 -0
  6. package/dist/claude-subscription-usage.d.ts +1 -3
  7. package/dist/index.d.ts +1 -7
  8. package/dist/index.js +2 -8
  9. package/dist/input-wait-yield.d.ts +0 -4
  10. package/dist/mcp-run-credentials.d.ts +2 -3
  11. package/dist/model-preparation-diagnostics.d.ts +0 -9
  12. package/dist/model-provider-routing.d.ts +0 -4
  13. package/dist/model-provider.d.ts +0 -1
  14. package/dist/model-request-capture.d.ts +0 -9
  15. package/dist/replayable-json-body.d.ts +1 -2
  16. package/dist/sandbox/index.d.ts +1 -1
  17. package/dist/sandbox/index.js +1 -3
  18. package/dist/sandbox/provider-command-session.d.ts +0 -6
  19. package/dist/sandbox/providers/modal-command-router-wire.d.ts +0 -5
  20. package/dist/sandbox/routing/routing-session.d.ts +4 -5
  21. package/dist/workspace-tool-gateway.js +2 -2
  22. package/package.json +12 -12
  23. package/src/bundled_default_skills/opengeni-client/SKILL.md +0 -5
  24. package/src/bundled_default_skills/opengeni-client/references/api-workflows.md +0 -8
  25. package/src/bundled_default_skills/opengeni-client/references/product-shapes-and-ui.md +3 -16
  26. package/src/claude-subscription-usage.ts +4 -23
  27. package/src/index.ts +2 -29
  28. package/src/input-wait-yield.ts +0 -7
  29. package/src/interaction-tools.ts +2 -12
  30. package/src/lazy-tool-transport.ts +14 -22
  31. package/src/mcp-run-credentials.ts +3 -18
  32. package/src/model-preparation-diagnostics.ts +1 -48
  33. package/src/model-provider-client.ts +1 -5
  34. package/src/model-provider-routing.ts +1 -95
  35. package/src/model-provider.ts +0 -1
  36. package/src/model-request-capture.ts +1 -28
  37. package/src/provider-history-adapter.ts +3 -24
  38. package/src/replayable-json-body.ts +2 -19
  39. package/src/sandbox/index.ts +0 -1
  40. package/src/sandbox/provider-command-session.ts +0 -12
  41. package/src/sandbox/providers/modal-command-control.ts +8 -14
  42. package/src/sandbox/providers/modal-command-router-wire.ts +3 -20
  43. package/src/sandbox/providers/modal-command-session.ts +0 -11
  44. package/src/sandbox/providers/modal.ts +1 -5
  45. package/src/sandbox/routing/routing-session.ts +6 -61
  46. package/src/sandbox/turn-tool-cancellation.ts +1 -8
  47. package/dist/chunk-BK3S65CI.js.map +0 -1
  48. package/dist/chunk-PEEYZDLS.js.map +0 -1
  49. package/dist/responses-terminal-error.d.ts +0 -17
  50. package/src/bundled_default_skills/opengeni-client/references/usage-allowances.md +0 -189
  51. package/src/responses-terminal-error.ts +0 -136
@@ -13,7 +13,6 @@ import {
13
13
  loadManagedCodemodeClient,
14
14
  managedCodemodeClientDirectory,
15
15
  normalizeProtocolJsonValue,
16
- renderRoutingMutationOutcomeUnknownToolResult,
17
16
  repairSerializedRunStateExposedPorts,
18
17
  restoredSandboxSessionStateFromEntry,
19
18
  runWithToolCallCorrelation,
@@ -28,7 +27,7 @@ import {
28
27
  withRunCredentialsClient,
29
28
  withRunCredentialsSession,
30
29
  wrapCapabilityToolsForTurnCancellation
31
- } from "./chunk-BK3S65CI.js";
30
+ } from "./chunk-JUFVYQCY.js";
32
31
  import {
33
32
  MemorySession,
34
33
  connectMcpServers
@@ -144,14 +143,14 @@ function toolCallIdFromSdkItem(item) {
144
143
  if (!item || typeof item !== "object" || Array.isArray(item)) {
145
144
  return void 0;
146
145
  }
147
- const record2 = item;
148
- if (typeof record2.callId === "string" && record2.callId.length > 0) {
149
- return record2.callId;
146
+ const record = item;
147
+ if (typeof record.callId === "string" && record.callId.length > 0) {
148
+ return record.callId;
150
149
  }
151
- if (typeof record2.call_id === "string" && record2.call_id.length > 0) {
152
- return record2.call_id;
150
+ if (typeof record.call_id === "string" && record.call_id.length > 0) {
151
+ return record.call_id;
153
152
  }
154
- const provider = record2.providerData;
153
+ const provider = record.providerData;
155
154
  if (provider && typeof provider === "object") {
156
155
  if (typeof provider.call_id === "string" && provider.call_id.length > 0) {
157
156
  return provider.call_id;
@@ -448,12 +447,12 @@ function projectRejectedProviderArtifactsFromSerializedRunState(serialized) {
448
447
  }
449
448
  function hasOpaqueProviderArtifact(item) {
450
449
  if (!item || typeof item !== "object") return false;
451
- const record2 = item;
452
- if (record2.type !== "reasoning" && record2.type !== "compaction") return false;
453
- if (typeof record2.encrypted_content === "string" && record2.encrypted_content.length > 0) {
450
+ const record = item;
451
+ if (record.type !== "reasoning" && record.type !== "compaction") return false;
452
+ if (typeof record.encrypted_content === "string" && record.encrypted_content.length > 0) {
454
453
  return true;
455
454
  }
456
- const providerData = record2.providerData && typeof record2.providerData === "object" ? record2.providerData : null;
455
+ const providerData = record.providerData && typeof record.providerData === "object" ? record.providerData : null;
457
456
  return Boolean(
458
457
  providerData && (typeof providerData.encrypted_content === "string" && providerData.encrypted_content.length > 0 || typeof providerData.encryptedContent === "string" && providerData.encryptedContent.length > 0)
459
458
  );
@@ -494,11 +493,11 @@ function normalizeComputerCallActions(items) {
494
493
  }
495
494
  function normalizeComputerCallAction(item) {
496
495
  if (itemType(item) !== "computer_call") return item;
497
- const record2 = item;
498
- const hasAction = record2.action !== void 0 && record2.action !== null;
499
- const hasActions = Array.isArray(record2.actions) && record2.actions.length > 0;
496
+ const record = item;
497
+ const hasAction = record.action !== void 0 && record.action !== null;
498
+ const hasActions = Array.isArray(record.actions) && record.actions.length > 0;
500
499
  if (!hasAction || !hasActions) return item;
501
- const { action: _droppedAction, ...rest } = record2;
500
+ const { action: _droppedAction, ...rest } = record;
502
501
  return rest;
503
502
  }
504
503
  function rewriteComputerCallsToActionsOnly(body) {
@@ -514,22 +513,22 @@ function rewriteComputerCallsToActionsOnly(body) {
514
513
  if (!item || typeof item !== "object") {
515
514
  continue;
516
515
  }
517
- const record2 = item;
518
- if (record2.type !== "computer_call") {
516
+ const record = item;
517
+ if (record.type !== "computer_call") {
519
518
  continue;
520
519
  }
521
- const existingActions = Array.isArray(record2.actions) && record2.actions.length > 0 ? record2.actions : void 0;
522
- const actions = existingActions ?? (record2.action !== void 0 && record2.action !== null ? [record2.action] : void 0);
520
+ const existingActions = Array.isArray(record.actions) && record.actions.length > 0 ? record.actions : void 0;
521
+ const actions = existingActions ?? (record.action !== void 0 && record.action !== null ? [record.action] : void 0);
523
522
  if (actions === void 0) {
524
523
  continue;
525
524
  }
526
- const hadAction = "action" in record2;
525
+ const hadAction = "action" in record;
527
526
  const actionsAlreadyExact = existingActions !== void 0 && !hadAction;
528
527
  if (actionsAlreadyExact) {
529
528
  continue;
530
529
  }
531
- delete record2.action;
532
- record2.actions = actions;
530
+ delete record.action;
531
+ record.actions = actions;
533
532
  changed = true;
534
533
  }
535
534
  return changed;
@@ -547,11 +546,11 @@ function rewriteEmptyComputerCallOutputImageUrls(body) {
547
546
  if (!item || typeof item !== "object") {
548
547
  continue;
549
548
  }
550
- const record2 = item;
551
- if (record2.type !== "computer_call_output") {
549
+ const record = item;
550
+ if (record.type !== "computer_call_output") {
552
551
  continue;
553
552
  }
554
- const output = record2.output;
553
+ const output = record.output;
555
554
  if (!output || typeof output !== "object") {
556
555
  continue;
557
556
  }
@@ -864,13 +863,13 @@ var MAX_NATIVE_IMAGE_TOKENS = 8192;
864
863
  function finitePositiveInteger(value) {
865
864
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : null;
866
865
  }
867
- function dimensionsFromRecord(record2) {
868
- const width = finitePositiveInteger(record2.width);
869
- const height = finitePositiveInteger(record2.height);
866
+ function dimensionsFromRecord(record) {
867
+ const width = finitePositiveInteger(record.width);
868
+ const height = finitePositiveInteger(record.height);
870
869
  if (width && height) return [width, height];
871
- if (Array.isArray(record2.dimensions) && record2.dimensions.length >= 2) {
872
- const dimensionsWidth = finitePositiveInteger(record2.dimensions[0]);
873
- const dimensionsHeight = finitePositiveInteger(record2.dimensions[1]);
870
+ if (Array.isArray(record.dimensions) && record.dimensions.length >= 2) {
871
+ const dimensionsWidth = finitePositiveInteger(record.dimensions[0]);
872
+ const dimensionsHeight = finitePositiveInteger(record.dimensions[1]);
874
873
  if (dimensionsWidth && dimensionsHeight) return [dimensionsWidth, dimensionsHeight];
875
874
  }
876
875
  return null;
@@ -960,11 +959,11 @@ function dimensionsFromImageSource(source) {
960
959
  return bytes ? dimensionsFromImageBytes(bytes) : null;
961
960
  }
962
961
  if (!source || typeof source !== "object") return null;
963
- const record2 = source;
964
- const rawData = record2.data;
965
- const mediaType = record2.mediaType ?? record2.media_type;
962
+ const record = source;
963
+ const rawData = record.data;
964
+ const mediaType = record.mediaType ?? record.media_type;
966
965
  const rawDataDimensions = rawData instanceof Uint8Array ? dimensionsFromImageBytes(rawData) : typeof rawData === "string" && typeof mediaType === "string" && mediaType.toLowerCase().startsWith("image/") ? dimensionsFromImageBytes(base64BytesPrefix(rawData) ?? new Uint8Array()) : null;
967
- return dimensionsFromRecord(record2) ?? rawDataDimensions ?? dimensionsFromImageSource(record2.url) ?? dimensionsFromImageSource(rawData);
966
+ return dimensionsFromRecord(record) ?? rawDataDimensions ?? dimensionsFromImageSource(record.url) ?? dimensionsFromImageSource(rawData);
968
967
  }
969
968
  function highDetailImageTokens(width, height) {
970
969
  let scaledWidth = width;
@@ -1014,19 +1013,19 @@ function estimateNativeImageTokens(input) {
1014
1013
  reason: "dimensions"
1015
1014
  };
1016
1015
  }
1017
- function imageDescriptor(record2) {
1018
- const type = typeof record2.type === "string" ? record2.type : "";
1016
+ function imageDescriptor(record) {
1017
+ const type = typeof record.type === "string" ? record.type : "";
1019
1018
  if (!(/* @__PURE__ */ new Set(["input_image", "image_url", "image", "computer_screenshot"])).has(type)) {
1020
1019
  return null;
1021
1020
  }
1022
- const imageUrl = record2.image_url;
1021
+ const imageUrl = record.image_url;
1023
1022
  const nestedImageUrl = imageUrl && typeof imageUrl === "object" ? imageUrl.url : imageUrl;
1024
- const source = record2.image ?? record2.imageUrl ?? nestedImageUrl ?? record2.data ?? record2.url ?? record2.fileId ?? record2.file_id ?? record2.artifact ?? record2.artifactReference;
1023
+ const source = record.image ?? record.imageUrl ?? nestedImageUrl ?? record.data ?? record.url ?? record.fileId ?? record.file_id ?? record.artifact ?? record.artifactReference;
1025
1024
  const nestedDetail = imageUrl && typeof imageUrl === "object" ? imageUrl.detail : void 0;
1026
- const dimensions = dimensionsFromRecord(record2) ?? (source && typeof source === "object" ? dimensionsFromRecord(source) : null);
1025
+ const dimensions = dimensionsFromRecord(record) ?? (source && typeof source === "object" ? dimensionsFromRecord(source) : null);
1027
1026
  return {
1028
1027
  source,
1029
- detail: typeof record2.detail === "string" ? record2.detail : typeof nestedDetail === "string" ? nestedDetail : "auto",
1028
+ detail: typeof record.detail === "string" ? record.detail : typeof nestedDetail === "string" ? nestedDetail : "auto",
1030
1029
  width: dimensions?.[0] ?? null,
1031
1030
  height: dimensions?.[1] ?? null
1032
1031
  };
@@ -1053,8 +1052,8 @@ function projectNativeImages(value, seen) {
1053
1052
  seen.delete(value);
1054
1053
  return { value: projected2, imageTokens: imageTokens2, imageCount: imageCount2, imageFallbackCount: imageFallbackCount2 };
1055
1054
  }
1056
- const record2 = value;
1057
- const descriptor = imageDescriptor(record2);
1055
+ const record = value;
1056
+ const descriptor = imageDescriptor(record);
1058
1057
  if (descriptor) {
1059
1058
  const estimate = estimateNativeImageTokens(descriptor);
1060
1059
  const projected2 = {};
@@ -1069,7 +1068,7 @@ function projectNativeImages(value, seen) {
1069
1068
  "artifact",
1070
1069
  "artifactReference"
1071
1070
  ]);
1072
- for (const [key, entry] of Object.entries(record2)) {
1071
+ for (const [key, entry] of Object.entries(record)) {
1073
1072
  projected2[key] = payloadKeys.has(key) ? "[native image]" : entry;
1074
1073
  }
1075
1074
  projected2.image_estimate = {
@@ -1090,7 +1089,7 @@ function projectNativeImages(value, seen) {
1090
1089
  let imageCount = 0;
1091
1090
  let imageFallbackCount = 0;
1092
1091
  const projected = {};
1093
- for (const [key, entry] of Object.entries(record2)) {
1092
+ for (const [key, entry] of Object.entries(record)) {
1094
1093
  const result = projectNativeImages(entry, seen);
1095
1094
  projected[key] = result.value;
1096
1095
  imageTokens += result.imageTokens;
@@ -1110,13 +1109,13 @@ function estimateOpaqueEncryptedTokens(encodedLen) {
1110
1109
  }
1111
1110
  function opaqueEncryptedContentLength(item) {
1112
1111
  if (!item || typeof item !== "object") return null;
1113
- const record2 = item;
1114
- const type = typeof record2.type === "string" ? record2.type : "";
1115
- if ((type === "compaction" || type === "context_compaction" || type === "reasoning") && typeof record2.encrypted_content === "string" && record2.encrypted_content.length > 0) {
1116
- return record2.encrypted_content.length;
1112
+ const record = item;
1113
+ const type = typeof record.type === "string" ? record.type : "";
1114
+ if ((type === "compaction" || type === "context_compaction" || type === "reasoning") && typeof record.encrypted_content === "string" && record.encrypted_content.length > 0) {
1115
+ return record.encrypted_content.length;
1117
1116
  }
1118
1117
  if (type === "reasoning") {
1119
- const providerData = record2.providerData && typeof record2.providerData === "object" ? record2.providerData : null;
1118
+ const providerData = record.providerData && typeof record.providerData === "object" ? record.providerData : null;
1120
1119
  const nested = providerData && typeof providerData.encrypted_content === "string" ? providerData.encrypted_content : providerData && typeof providerData.encryptedContent === "string" ? providerData.encryptedContent : null;
1121
1120
  if (nested && nested.length > 0) return nested.length;
1122
1121
  }
@@ -1401,8 +1400,8 @@ function findCompactionNeededError(error, seen = /* @__PURE__ */ new WeakSet())
1401
1400
  return null;
1402
1401
  }
1403
1402
  seen.add(error);
1404
- const record2 = error;
1405
- return findCompactionNeededError(record2.cause, seen) ?? findCompactionNeededError(record2.error, seen);
1403
+ const record = error;
1404
+ return findCompactionNeededError(record.cause, seen) ?? findCompactionNeededError(record.error, seen);
1406
1405
  }
1407
1406
  function buildCompactionPromptInput(items) {
1408
1407
  return [
@@ -1474,9 +1473,9 @@ function remoteCompactionShellOutputIsMinimal(output) {
1474
1473
  if (!Array.isArray(output) || output.length !== 1) return false;
1475
1474
  const result = output[0];
1476
1475
  if (!result || typeof result !== "object" || Array.isArray(result)) return false;
1477
- const record2 = result;
1478
- const outcome = record2.outcome;
1479
- return record2.stdout === "" && record2.stderr === REMOTE_COMPACTION_TOOL_RESULT_OMISSION && outcome !== null && typeof outcome === "object" && !Array.isArray(outcome) && outcome.type === "exit" && outcome.exitCode === null && Object.keys(record2).length === 3 && Object.keys(outcome).length === 2;
1476
+ const record = result;
1477
+ const outcome = record.outcome;
1478
+ return record.stdout === "" && record.stderr === REMOTE_COMPACTION_TOOL_RESULT_OMISSION && outcome !== null && typeof outcome === "object" && !Array.isArray(outcome) && outcome.type === "exit" && outcome.exitCode === null && Object.keys(record).length === 3 && Object.keys(outcome).length === 2;
1480
1479
  }
1481
1480
  function omitOpaqueArtifactsFromPortableCompactionHistory(items) {
1482
1481
  let changed = false;
@@ -1597,8 +1596,8 @@ function buildCompactionReplacementHistory(items, summaryBody, retainedItemToken
1597
1596
  }
1598
1597
  function isRemoteCompactionItem(item) {
1599
1598
  if (!item || typeof item !== "object") return false;
1600
- const record2 = item;
1601
- return record2.type === "compaction" && typeof record2.encrypted_content === "string" && record2.encrypted_content.length > 0;
1599
+ const record = item;
1600
+ return record.type === "compaction" && typeof record.encrypted_content === "string" && record.encrypted_content.length > 0;
1602
1601
  }
1603
1602
  function isRetainedRemoteV2Message(item) {
1604
1603
  if (isCompactionSummary(item) || isAttachmentCatalog(item) || itemType2(item) === "compaction") {
@@ -1690,8 +1689,8 @@ function extractRemoteCompactionV2OutputItem(response) {
1690
1689
  if (!response || typeof response !== "object") {
1691
1690
  throw new EmptyCompactionSummaryError({ stage: "remote_v2_extract", reason: "no_response" });
1692
1691
  }
1693
- const record2 = response;
1694
- const output = Array.isArray(record2.output) ? record2.output : [];
1692
+ const record = response;
1693
+ const output = Array.isArray(record.output) ? record.output : [];
1695
1694
  const compactionItems = output.filter(isRemoteCompactionItem);
1696
1695
  if (compactionItems.length !== 1) {
1697
1696
  throw new EmptyCompactionSummaryError({
@@ -1831,12 +1830,12 @@ function messageText(item) {
1831
1830
  if (Array.isArray(content)) {
1832
1831
  return content.map((part) => {
1833
1832
  if (part && typeof part === "object") {
1834
- const record2 = part;
1835
- if (typeof record2.text === "string") {
1836
- return record2.text;
1833
+ const record = part;
1834
+ if (typeof record.text === "string") {
1835
+ return record.text;
1837
1836
  }
1838
- if (typeof record2.content === "string") {
1839
- return record2.content;
1837
+ if (typeof record.content === "string") {
1838
+ return record.content;
1840
1839
  }
1841
1840
  }
1842
1841
  return "";
@@ -3907,10 +3906,10 @@ function getProviderDataField(providerData, keys) {
3907
3906
  if (!providerData || typeof providerData !== "object" || Array.isArray(providerData)) {
3908
3907
  return void 0;
3909
3908
  }
3910
- const record2 = providerData;
3909
+ const record = providerData;
3911
3910
  for (const key of keys) {
3912
- if (typeof record2[key] !== "undefined") {
3913
- return record2[key];
3911
+ if (typeof record[key] !== "undefined") {
3912
+ return record[key];
3914
3913
  }
3915
3914
  }
3916
3915
  return void 0;
@@ -7544,11 +7543,11 @@ function stripConversationPersistenceMetadata(items) {
7544
7543
  if (Array.isArray(item) || item === null || typeof item !== "object") {
7545
7544
  return [item];
7546
7545
  }
7547
- const record2 = item;
7548
- if (isUnpersistableReasoningItem(record2)) {
7546
+ const record = item;
7547
+ if (isUnpersistableReasoningItem(record)) {
7549
7548
  return [];
7550
7549
  }
7551
- const { providerData: _providerData, provider_data: _provider_data, ...rest } = record2;
7550
+ const { providerData: _providerData, provider_data: _provider_data, ...rest } = record;
7552
7551
  if (rest.type !== "reasoning") {
7553
7552
  delete rest.id;
7554
7553
  }
@@ -7562,11 +7561,11 @@ function stripAssistantReplayMetadata(item) {
7562
7561
  if (Array.isArray(item) || item === null || typeof item !== "object") {
7563
7562
  return item;
7564
7563
  }
7565
- const record2 = item;
7566
- if (record2.type !== "message" || record2.role !== "assistant") {
7564
+ const record = item;
7565
+ if (record.type !== "message" || record.role !== "assistant") {
7567
7566
  return item;
7568
7567
  }
7569
- const { id: _id, providerData, provider_data: _provider_data, ...rest } = record2;
7568
+ const { id: _id, providerData, provider_data: _provider_data, ...rest } = record;
7570
7569
  if (typeof rest.phase === "undefined" && providerData && typeof providerData === "object" && !Array.isArray(providerData) && typeof providerData.phase !== "undefined") {
7571
7570
  rest.phase = providerData.phase;
7572
7571
  }
@@ -9341,10 +9340,10 @@ function azureModelRequestPolicy({
9341
9340
  if (!containsComputerProtocol) return void 0;
9342
9341
  const projectedInput = input.map((item) => {
9343
9342
  if (!item || typeof item !== "object" || Array.isArray(item)) return item;
9344
- const record2 = item;
9345
- if (record2.type === "computer_call") return { ...record2 };
9346
- if (record2.type === "computer_call_output" && record2.output && typeof record2.output === "object" && !Array.isArray(record2.output)) {
9347
- return { ...record2, output: { ...record2.output } };
9343
+ const record = item;
9344
+ if (record.type === "computer_call") return { ...record };
9345
+ if (record.type === "computer_call_output" && record.output && typeof record.output === "object" && !Array.isArray(record.output)) {
9346
+ return { ...record, output: { ...record.output } };
9348
9347
  }
9349
9348
  return item;
9350
9349
  });
@@ -9475,161 +9474,273 @@ function isModelCallFetch(input) {
9475
9474
  // src/replayable-json-body.ts
9476
9475
  import OpenAI6 from "openai";
9477
9476
  import { types as utilTypes } from "util";
9478
-
9479
- // src/model-preparation-diagnostics.ts
9480
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
9481
-
9482
- // src/model-request-capture.ts
9483
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
9484
- var modelRequestCapture = new AsyncLocalStorage2();
9485
- var captureIndices = /* @__PURE__ */ new WeakMap();
9486
- var modelCallLifecycle = new AsyncLocalStorage2();
9487
- function withModelCallLifecycle(lifecycle, fn) {
9488
- return modelCallLifecycle.run(lifecycle, fn);
9489
- }
9490
- async function beforeModelRequest() {
9491
- await modelCallLifecycle.getStore()?.beforeModelRequest?.();
9492
- }
9493
- function modelResponseSettlement(event) {
9494
- if (event.type !== "response_done") return void 0;
9495
- return modelCallLifecycle.getStore()?.onModelResponse?.(event);
9496
- }
9497
- function nextModelContextCaptureIndex(agent) {
9498
- const index = (captureIndices.get(agent) ?? 0) + 1;
9499
- captureIndices.set(agent, index);
9500
- return index;
9501
- }
9502
- function withModelRequestCapture(capture, fn) {
9503
- return capture ? modelRequestCapture.run(capture, fn) : fn();
9504
- }
9505
- function captureProviderRequestBody(provider, input, init) {
9506
- const context = modelRequestCapture.getStore();
9507
- const callback = context?.onProviderRequest;
9508
- if (!callback) return { init, captured: Promise.resolve(), cancel: () => {
9509
- } };
9510
- const index = context.nextProviderRequestIndex?.();
9511
- const observer = (providerId, body2, reason) => callback(providerId, body2, reason, index);
9512
- let cancel = () => {
9513
- };
9514
- let body = init?.body;
9515
- let nextInit = init;
9516
- if (body instanceof ReadableStream) {
9517
- const [sent, inspected] = body.tee();
9518
- nextInit = { ...init, body: sent };
9519
- body = inspected;
9520
- } else if (body == null && input instanceof Request) {
9521
- body = input.clone().body;
9477
+ var TARGET_CHUNK_CHARS = 64 * 1024;
9478
+ var LARGE_STRING_SOURCE_CHARS = 32 * 1024;
9479
+ var STRING_SLICE_CODE_UNITS = 10 * 1024;
9480
+ var REPLAYABLE_REQUEST_BODY_FACTORY = Symbol.for(
9481
+ "opengeni.replayable-request-body-factory"
9482
+ );
9483
+ var ReplayableJsonBody = class {
9484
+ source;
9485
+ constructor(source) {
9486
+ this.source = source;
9522
9487
  }
9523
- const captured = (async () => {
9524
- const limit = 4 * 1024 * 1024;
9525
- let text2;
9526
- if (typeof body === "string") {
9527
- if (Buffer.byteLength(body, "utf8") > limit) {
9528
- await observer(provider, null, "Request exceeds the 4 MiB capture limit.");
9529
- return;
9488
+ async *[Symbol.asyncIterator]() {
9489
+ const encoder = new TextEncoder();
9490
+ for (const chunk of jsonTextChunks(this.source)) {
9491
+ yield encoder.encode(chunk);
9492
+ }
9493
+ }
9494
+ createStream() {
9495
+ const iterator = this[Symbol.asyncIterator]();
9496
+ return new ReadableStream({
9497
+ async pull(controller) {
9498
+ try {
9499
+ const next = await iterator.next();
9500
+ if (next.done) controller.close();
9501
+ else controller.enqueue(next.value);
9502
+ } catch (error) {
9503
+ controller.error(error);
9504
+ }
9505
+ },
9506
+ async cancel(reason) {
9507
+ await iterator.return?.(reason).catch(() => void 0);
9530
9508
  }
9531
- text2 = body;
9532
- } else if (body instanceof ReadableStream) {
9533
- const reader = body.getReader();
9534
- let cancelled = false;
9535
- cancel = () => {
9536
- cancelled = true;
9537
- void reader.cancel().catch(() => void 0);
9538
- };
9539
- const signal = init?.signal ?? (input instanceof Request ? input.signal : void 0);
9540
- signal?.addEventListener("abort", cancel, { once: true });
9541
- if (signal?.aborted) cancel();
9542
- const decoder = new TextDecoder("utf-8", { fatal: true });
9543
- const chunks = [];
9544
- let bytes = 0;
9545
- try {
9546
- while (true) {
9547
- const chunk = await reader.read();
9548
- if (chunk.done) break;
9549
- bytes += chunk.value.byteLength;
9550
- if (bytes > limit) {
9551
- void reader.cancel().catch(() => void 0);
9552
- await observer(provider, null, "Request exceeds the 4 MiB capture limit.");
9553
- return;
9554
- }
9555
- chunks.push(decoder.decode(chunk.value, { stream: true }));
9509
+ });
9510
+ }
9511
+ };
9512
+ var ReplayableJsonOpenAI = class extends OpenAI6 {
9513
+ modelRequestPolicy;
9514
+ constructor(options, hooks = {}) {
9515
+ super(options);
9516
+ this.modelRequestPolicy = hooks.modelRequestPolicy;
9517
+ }
9518
+ post(path, opts) {
9519
+ if (!isModelRequestPath(path) || opts === void 0) {
9520
+ return super.post(path, opts);
9521
+ }
9522
+ const wrapped = Promise.resolve(opts).then((resolved) => {
9523
+ const body = resolved.body;
9524
+ let prepared = resolved;
9525
+ if (this.modelRequestPolicy && isJsonRecordBody(body)) {
9526
+ const policy = this.modelRequestPolicy({ path, body });
9527
+ if (policy?.body || policy?.headers) {
9528
+ prepared = {
9529
+ ...resolved,
9530
+ ...policy.body ? { body: policy.body } : {},
9531
+ ...policy.headers ? { headers: mergePolicyHeaders(resolved.headers, policy.headers) } : {}
9532
+ };
9556
9533
  }
9557
- if (cancelled) return;
9558
- chunks.push(decoder.decode());
9559
- text2 = chunks.join("");
9560
- } catch {
9561
- void reader.cancel().catch(() => void 0);
9562
- if (!cancelled)
9563
- await observer(provider, null, "The provider body could not be read as UTF-8.");
9564
- return;
9565
- } finally {
9566
- signal?.removeEventListener("abort", cancel);
9567
- reader.releaseLock();
9568
- cancel = () => {
9569
- };
9570
9534
  }
9535
+ return wrapJsonRequestOptions(prepared);
9536
+ });
9537
+ return super.post(path, wrapped);
9538
+ }
9539
+ async buildRequest(inputOptions, context) {
9540
+ const replayable = inputOptions.body instanceof ReplayableJsonBody ? inputOptions.body : void 0;
9541
+ const priorStreamingMarker = inputOptions.__metadata?.hasStreamingBody;
9542
+ const built = await super.buildRequest(inputOptions, context);
9543
+ if (!replayable) return built;
9544
+ if (priorStreamingMarker === void 0) {
9545
+ if (inputOptions.__metadata) delete inputOptions.__metadata.hasStreamingBody;
9571
9546
  } else {
9572
- await observer(provider, null, "This transport body cannot be inspected.");
9573
- return;
9547
+ inputOptions.__metadata = {
9548
+ ...inputOptions.__metadata,
9549
+ hasStreamingBody: priorStreamingMarker
9550
+ };
9574
9551
  }
9575
- await observer(provider, text2);
9576
- })().catch(() => void 0);
9577
- return { init: nextInit, captured, cancel: () => cancel() };
9578
- }
9579
- async function notifyModelRequestCapture(request) {
9580
- const capture = modelRequestCapture.getStore();
9581
- if (!capture) return;
9582
- try {
9583
- await capture(snapshotModelRequestPrefix(request));
9584
- } catch {
9552
+ const request = built.req;
9553
+ request[REPLAYABLE_REQUEST_BODY_FACTORY] = () => replayable.createStream();
9554
+ return built;
9585
9555
  }
9556
+ };
9557
+ function isModelRequestPath(path) {
9558
+ const pathname = path.split("?", 1)[0] ?? path;
9559
+ return pathname.endsWith("/responses") || pathname.endsWith("/chat/completions");
9586
9560
  }
9587
- function snapshotModelRequestPrefix(request) {
9561
+ function wrapJsonRequestOptions(options) {
9562
+ const body = options.body;
9563
+ if (!isJsonObjectBody(body) || body instanceof ReplayableJsonBody) return options;
9588
9564
  return {
9589
- ...request,
9590
- tools: structuredClone(request.tools)
9565
+ ...options,
9566
+ body: new ReplayableJsonBody(body),
9567
+ headers: mergePolicyHeaders(options.headers, { "content-type": "application/json" })
9591
9568
  };
9592
9569
  }
9593
- var ModelRequestCaptureModel = class {
9594
- constructor(inner) {
9595
- this.inner = inner;
9570
+ function isJsonObjectBody(value) {
9571
+ if (!value || typeof value !== "object") return false;
9572
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) return false;
9573
+ if (value instanceof Blob || value instanceof FormData || value instanceof URLSearchParams) {
9574
+ return false;
9596
9575
  }
9597
- async getResponse(request) {
9598
- await beforeModelRequest();
9599
- rememberPreparedModelRequest(request);
9600
- void notifyModelRequestCapture(request);
9601
- return this.inner.getResponse(request);
9576
+ if (value instanceof ReadableStream) return false;
9577
+ return !(Symbol.asyncIterator in value) && !(Symbol.iterator in value);
9578
+ }
9579
+ function isJsonRecordBody(value) {
9580
+ return isJsonObjectBody(value) && !Array.isArray(value);
9581
+ }
9582
+ function mergePolicyHeaders(headers, additions) {
9583
+ const replacedNames = new Set(Object.keys(additions).map((name) => name.toLowerCase()));
9584
+ if (headers instanceof Headers) {
9585
+ const merged2 = new Headers(headers);
9586
+ for (const [name, value] of Object.entries(additions)) merged2.set(name, value);
9587
+ return merged2;
9602
9588
  }
9603
- async *getStreamedResponse(request) {
9604
- await beforeModelRequest();
9605
- rememberPreparedModelRequest(request);
9606
- void notifyModelRequestCapture(request);
9607
- for await (const event of this.inner.getStreamedResponse(request)) {
9608
- const settlement = modelResponseSettlement(event);
9609
- void settlement?.catch(() => void 0);
9610
- yield event;
9589
+ if (headers && typeof headers === "object" && "values" in headers && "nulls" in headers && headers.values instanceof Headers && headers.nulls instanceof Set) {
9590
+ const resolved = headers;
9591
+ const rows = [
9592
+ ...resolved.values.entries(),
9593
+ ...[...resolved.nulls].map((name) => [name, null])
9594
+ ];
9595
+ return mergePolicyHeaders(rows, additions);
9596
+ }
9597
+ if (Array.isArray(headers)) {
9598
+ return [
9599
+ ...headers.filter(
9600
+ (row) => !Array.isArray(row) || typeof row[0] !== "string" || !replacedNames.has(row[0].toLowerCase())
9601
+ ),
9602
+ ...Object.entries(additions)
9603
+ ];
9604
+ }
9605
+ const merged = { ...headers ?? {} };
9606
+ for (const name of Object.keys(merged)) {
9607
+ if (replacedNames.has(name.toLowerCase())) delete merged[name];
9608
+ }
9609
+ return { ...merged, ...additions };
9610
+ }
9611
+ function* jsonTextChunks(value) {
9612
+ const fragments = jsonValueFragments(value, "", /* @__PURE__ */ new Set(), 0);
9613
+ if (!fragments) throw new TypeError("Model request body is not JSON serializable");
9614
+ let buffered = "";
9615
+ for (const fragment of fragments) {
9616
+ if (buffered.length > 0 && buffered.length + fragment.length > TARGET_CHUNK_CHARS) {
9617
+ yield buffered;
9618
+ buffered = "";
9611
9619
  }
9620
+ if (fragment.length >= TARGET_CHUNK_CHARS) yield fragment;
9621
+ else buffered += fragment;
9612
9622
  }
9613
- getRetryAdvice(args) {
9614
- return this.inner.getRetryAdvice?.(args);
9623
+ if (buffered.length > 0) yield buffered;
9624
+ }
9625
+ function jsonValueFragments(source, key, ancestors, depth) {
9626
+ if (typeof source === "string" && source.length > LARGE_STRING_SOURCE_CHARS) {
9627
+ return jsonStringFragments(source);
9628
+ }
9629
+ if (depth >= 2 || depth > 0 && !Array.isArray(source)) {
9630
+ return nativeJsonPropertyFragments(source, key);
9631
+ }
9632
+ const value = prepareJsonValue(source, key);
9633
+ if (value === void 0 || typeof value === "function" || typeof value === "symbol") {
9634
+ return null;
9635
+ }
9636
+ if (typeof value === "bigint") {
9637
+ throw new TypeError("Do not know how to serialize a BigInt");
9638
+ }
9639
+ if (typeof value === "string") {
9640
+ return jsonStringFragments(value);
9641
+ }
9642
+ if (value === null || typeof value !== "object") {
9643
+ return [JSON.stringify(value)];
9644
+ }
9645
+ const rawJson = JSON;
9646
+ if (rawJson.isRawJSON?.(value)) return [JSON.stringify(value)];
9647
+ if (ancestors.has(value)) throw new TypeError("cyclic object value");
9648
+ return Array.isArray(value) ? jsonArrayFragments(value, ancestors, depth) : jsonObjectFragments(value, ancestors, depth);
9649
+ }
9650
+ function* jsonArrayFragments(value, ancestors, depth) {
9651
+ ancestors.add(value);
9652
+ try {
9653
+ const length = value.length;
9654
+ yield "[";
9655
+ for (let index = 0; index < length; index += 1) {
9656
+ if (index > 0) yield ",";
9657
+ const child = jsonValueFragments(value[index], String(index), ancestors, depth + 1);
9658
+ if (child) yield* child;
9659
+ else yield "null";
9660
+ }
9661
+ yield "]";
9662
+ } finally {
9663
+ ancestors.delete(value);
9664
+ }
9665
+ }
9666
+ function* jsonObjectFragments(value, ancestors, depth) {
9667
+ ancestors.add(value);
9668
+ try {
9669
+ const keys = Object.keys(value);
9670
+ let emitted = false;
9671
+ yield "{";
9672
+ for (const key of keys) {
9673
+ const child = jsonValueFragments(value[key], key, ancestors, depth + 1);
9674
+ if (!child) continue;
9675
+ if (emitted) yield ",";
9676
+ emitted = true;
9677
+ yield* jsonStringFragments(key);
9678
+ yield ":";
9679
+ yield* child;
9680
+ }
9681
+ yield "}";
9682
+ } finally {
9683
+ ancestors.delete(value);
9684
+ }
9685
+ }
9686
+ function nativeJsonPropertyFragments(source, key) {
9687
+ const holder = /* @__PURE__ */ Object.create(null);
9688
+ holder[key] = source;
9689
+ const serialized = JSON.stringify(holder);
9690
+ if (serialized === "{}") return null;
9691
+ const prefix = `{${JSON.stringify(key)}:`;
9692
+ if (!serialized.startsWith(prefix) || !serialized.endsWith("}")) {
9693
+ throw new TypeError("Model request body is not JSON serializable");
9694
+ }
9695
+ return boundedNativeJsonFragments(serialized.slice(prefix.length, -1));
9696
+ }
9697
+ function* boundedNativeJsonFragments(serialized) {
9698
+ for (let start = 0; start < serialized.length; ) {
9699
+ let end = Math.min(serialized.length, start + TARGET_CHUNK_CHARS);
9700
+ if (end < serialized.length && serialized.charCodeAt(end - 1) >= 55296 && serialized.charCodeAt(end - 1) <= 56319 && serialized.charCodeAt(end) >= 56320 && serialized.charCodeAt(end) <= 57343) {
9701
+ end -= 1;
9702
+ }
9703
+ yield serialized.slice(start, end);
9704
+ start = end;
9705
+ }
9706
+ }
9707
+ function prepareJsonValue(source, key) {
9708
+ let value = source;
9709
+ const sourceType = typeof value;
9710
+ if (value !== null && (sourceType === "object" || sourceType === "function" || sourceType === "bigint")) {
9711
+ const toJSON = value.toJSON;
9712
+ if (typeof toJSON === "function") value = toJSON.call(value, key);
9713
+ }
9714
+ if (value !== null && typeof value === "object") {
9715
+ if (utilTypes.isNumberObject(value)) return Number.prototype.valueOf.call(value);
9716
+ if (utilTypes.isStringObject(value)) return String.prototype.valueOf.call(value);
9717
+ if (utilTypes.isBooleanObject(value)) return Boolean.prototype.valueOf.call(value);
9718
+ if (utilTypes.isBigIntObject(value)) return BigInt.prototype.valueOf.call(value);
9615
9719
  }
9616
- };
9617
- var ModelRequestCaptureProvider = class {
9618
- constructor(inner) {
9619
- this.inner = inner;
9720
+ return value;
9721
+ }
9722
+ function* jsonStringFragments(value) {
9723
+ if (value.length <= LARGE_STRING_SOURCE_CHARS) {
9724
+ yield JSON.stringify(value);
9725
+ return;
9620
9726
  }
9621
- async getModel(modelName) {
9622
- const model = await this.inner.getModel(modelName);
9623
- if (model instanceof ModelRequestCaptureModel) return model;
9624
- return new ModelRequestCaptureModel(model);
9727
+ yield '"';
9728
+ for (let start = 0; start < value.length; ) {
9729
+ let end = Math.min(value.length, start + STRING_SLICE_CODE_UNITS);
9730
+ if (end < value.length && value.charCodeAt(end - 1) >= 55296 && value.charCodeAt(end - 1) <= 56319 && value.charCodeAt(end) >= 56320 && value.charCodeAt(end) <= 57343) {
9731
+ end -= 1;
9732
+ }
9733
+ const encoded = JSON.stringify(value.slice(start, end));
9734
+ yield encoded.slice(1, -1);
9735
+ start = end;
9625
9736
  }
9626
- };
9737
+ yield '"';
9738
+ }
9627
9739
 
9628
9740
  // src/model-preparation-diagnostics.ts
9629
- var modelPreparationObserver = new AsyncLocalStorage3();
9630
- var modelTransportStartedObserver = new AsyncLocalStorage3();
9631
- var modelTransportAdmission = new AsyncLocalStorage3();
9632
- var modelTransportRefusals = /* @__PURE__ */ new WeakMap();
9741
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
9742
+ var modelPreparationObserver = new AsyncLocalStorage2();
9743
+ var modelTransportStartedObserver = new AsyncLocalStorage2();
9633
9744
  var ModelPreparationTraceProcessor = class {
9634
9745
  async onTraceStart(_trace) {
9635
9746
  }
@@ -9670,38 +9781,7 @@ function withModelTransportStartedObserver(observer, callback) {
9670
9781
  return observer ? modelTransportStartedObserver.run(observer, callback) : callback();
9671
9782
  }
9672
9783
  async function recordModelTransportStarted() {
9673
- try {
9674
- await beforeModelRequest();
9675
- await modelTransportStartedObserver.getStore()?.();
9676
- } catch (error) {
9677
- const admission = modelTransportAdmission.getStore();
9678
- if (admission) admission.refusal = { error };
9679
- throw error;
9680
- }
9681
- }
9682
- function sdkModelTransportAdmissionFetch(inner) {
9683
- return async (input, init) => {
9684
- const admission = {};
9685
- return modelTransportAdmission.run(admission, async () => {
9686
- try {
9687
- return await inner(input, init);
9688
- } catch (error) {
9689
- if (!admission.refusal || admission.refusal.error !== error) throw error;
9690
- const response = new Response(null, {
9691
- status: 400,
9692
- headers: { "x-should-retry": "false" }
9693
- });
9694
- modelTransportRefusals.set(response.headers, admission.refusal);
9695
- return response;
9696
- }
9697
- });
9698
- };
9699
- }
9700
- function rethrowModelTransportAdmissionRefusal(headers) {
9701
- const refusal = modelTransportRefusals.get(headers);
9702
- if (!refusal) return;
9703
- modelTransportRefusals.delete(headers);
9704
- throw refusal.error;
9784
+ await modelTransportStartedObserver.getStore()?.();
9705
9785
  }
9706
9786
  function markModelPreparationFirstSandboxOperation(durationSeconds) {
9707
9787
  try {
@@ -9870,296 +9950,154 @@ function withModelPreparationClientDiagnostics(client) {
9870
9950
  }
9871
9951
  });
9872
9952
  }
9873
- function recordModelPreparationManifestInventory(phase, manifest) {
9874
- const startedAt = performance.now();
9875
- let outcome = "completed";
9876
- let count = 0;
9877
- try {
9878
- if (manifest && typeof manifest === "object" && "iterEntries" in manifest && typeof manifest.iterEntries === "function") {
9879
- for (const _entry of manifest.iterEntries()) count += 1;
9880
- }
9881
- } catch {
9882
- outcome = "failed";
9883
- } finally {
9884
- recordModelPreparationMeasurement({
9885
- phase,
9886
- outcome,
9887
- durationSeconds: (performance.now() - startedAt) / 1e3,
9888
- count
9889
- });
9890
- }
9891
- }
9892
-
9893
- // src/replayable-json-body.ts
9894
- var TARGET_CHUNK_CHARS = 64 * 1024;
9895
- var LARGE_STRING_SOURCE_CHARS = 32 * 1024;
9896
- var STRING_SLICE_CODE_UNITS = 10 * 1024;
9897
- var REPLAYABLE_REQUEST_BODY_FACTORY = Symbol.for(
9898
- "opengeni.replayable-request-body-factory"
9899
- );
9900
- var ReplayableJsonBody = class {
9901
- source;
9902
- constructor(source) {
9903
- this.source = source;
9904
- }
9905
- async *[Symbol.asyncIterator]() {
9906
- const encoder = new TextEncoder();
9907
- for (const chunk of jsonTextChunks(this.source)) {
9908
- yield encoder.encode(chunk);
9909
- }
9910
- }
9911
- createStream() {
9912
- const iterator = this[Symbol.asyncIterator]();
9913
- return new ReadableStream({
9914
- async pull(controller) {
9915
- try {
9916
- const next = await iterator.next();
9917
- if (next.done) controller.close();
9918
- else controller.enqueue(next.value);
9919
- } catch (error) {
9920
- controller.error(error);
9921
- }
9922
- },
9923
- async cancel(reason) {
9924
- await iterator.return?.(reason).catch(() => void 0);
9925
- }
9926
- });
9927
- }
9928
- };
9929
- var ReplayableJsonOpenAI = class extends OpenAI6 {
9930
- modelRequestPolicy;
9931
- constructor(options, hooks = {}) {
9932
- super({
9933
- ...options,
9934
- fetch: sdkModelTransportAdmissionFetch(options?.fetch ?? globalThis.fetch)
9935
- });
9936
- this.modelRequestPolicy = hooks.modelRequestPolicy;
9937
- }
9938
- makeStatusError(status, error, message, headers) {
9939
- rethrowModelTransportAdmissionRefusal(headers);
9940
- return super.makeStatusError(status, error, message, headers);
9941
- }
9942
- post(path, opts) {
9943
- if (!isModelRequestPath(path) || opts === void 0) {
9944
- return super.post(path, opts);
9945
- }
9946
- const wrapped = Promise.resolve(opts).then((resolved) => {
9947
- const body = resolved.body;
9948
- let prepared = resolved;
9949
- if (this.modelRequestPolicy && isJsonRecordBody(body)) {
9950
- const policy = this.modelRequestPolicy({ path, body });
9951
- if (policy?.body || policy?.headers) {
9952
- prepared = {
9953
- ...resolved,
9954
- ...policy.body ? { body: policy.body } : {},
9955
- ...policy.headers ? { headers: mergePolicyHeaders(resolved.headers, policy.headers) } : {}
9956
- };
9957
- }
9958
- }
9959
- return wrapJsonRequestOptions(prepared);
9960
- });
9961
- return super.post(path, wrapped);
9962
- }
9963
- async buildRequest(inputOptions, context) {
9964
- const replayable = inputOptions.body instanceof ReplayableJsonBody ? inputOptions.body : void 0;
9965
- const priorStreamingMarker = inputOptions.__metadata?.hasStreamingBody;
9966
- const built = await super.buildRequest(inputOptions, context);
9967
- if (!replayable) return built;
9968
- if (priorStreamingMarker === void 0) {
9969
- if (inputOptions.__metadata) delete inputOptions.__metadata.hasStreamingBody;
9970
- } else {
9971
- inputOptions.__metadata = {
9972
- ...inputOptions.__metadata,
9973
- hasStreamingBody: priorStreamingMarker
9974
- };
9975
- }
9976
- const request = built.req;
9977
- request[REPLAYABLE_REQUEST_BODY_FACTORY] = () => replayable.createStream();
9978
- return built;
9979
- }
9980
- };
9981
- function isModelRequestPath(path) {
9982
- const pathname = path.split("?", 1)[0] ?? path;
9983
- return pathname.endsWith("/responses") || pathname.endsWith("/chat/completions");
9984
- }
9985
- function wrapJsonRequestOptions(options) {
9986
- const body = options.body;
9987
- if (!isJsonObjectBody(body) || body instanceof ReplayableJsonBody) return options;
9988
- return {
9989
- ...options,
9990
- body: new ReplayableJsonBody(body),
9991
- headers: mergePolicyHeaders(options.headers, { "content-type": "application/json" })
9992
- };
9993
- }
9994
- function isJsonObjectBody(value) {
9995
- if (!value || typeof value !== "object") return false;
9996
- if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) return false;
9997
- if (value instanceof Blob || value instanceof FormData || value instanceof URLSearchParams) {
9998
- return false;
9999
- }
10000
- if (value instanceof ReadableStream) return false;
10001
- return !(Symbol.asyncIterator in value) && !(Symbol.iterator in value);
10002
- }
10003
- function isJsonRecordBody(value) {
10004
- return isJsonObjectBody(value) && !Array.isArray(value);
10005
- }
10006
- function mergePolicyHeaders(headers, additions) {
10007
- const replacedNames = new Set(Object.keys(additions).map((name) => name.toLowerCase()));
10008
- if (headers instanceof Headers) {
10009
- const merged2 = new Headers(headers);
10010
- for (const [name, value] of Object.entries(additions)) merged2.set(name, value);
10011
- return merged2;
10012
- }
10013
- if (headers && typeof headers === "object" && "values" in headers && "nulls" in headers && headers.values instanceof Headers && headers.nulls instanceof Set) {
10014
- const resolved = headers;
10015
- const rows = [
10016
- ...resolved.values.entries(),
10017
- ...[...resolved.nulls].map((name) => [name, null])
10018
- ];
10019
- return mergePolicyHeaders(rows, additions);
10020
- }
10021
- if (Array.isArray(headers)) {
10022
- return [
10023
- ...headers.filter(
10024
- (row) => !Array.isArray(row) || typeof row[0] !== "string" || !replacedNames.has(row[0].toLowerCase())
10025
- ),
10026
- ...Object.entries(additions)
10027
- ];
10028
- }
10029
- const merged = { ...headers ?? {} };
10030
- for (const name of Object.keys(merged)) {
10031
- if (replacedNames.has(name.toLowerCase())) delete merged[name];
10032
- }
10033
- return { ...merged, ...additions };
10034
- }
10035
- function* jsonTextChunks(value) {
10036
- const fragments = jsonValueFragments(value, "", /* @__PURE__ */ new Set(), 0);
10037
- if (!fragments) throw new TypeError("Model request body is not JSON serializable");
10038
- let buffered = "";
10039
- for (const fragment of fragments) {
10040
- if (buffered.length > 0 && buffered.length + fragment.length > TARGET_CHUNK_CHARS) {
10041
- yield buffered;
10042
- buffered = "";
10043
- }
10044
- if (fragment.length >= TARGET_CHUNK_CHARS) yield fragment;
10045
- else buffered += fragment;
10046
- }
10047
- if (buffered.length > 0) yield buffered;
10048
- }
10049
- function jsonValueFragments(source, key, ancestors, depth) {
10050
- if (typeof source === "string" && source.length > LARGE_STRING_SOURCE_CHARS) {
10051
- return jsonStringFragments(source);
10052
- }
10053
- if (depth >= 2 || depth > 0 && !Array.isArray(source)) {
10054
- return nativeJsonPropertyFragments(source, key);
10055
- }
10056
- const value = prepareJsonValue(source, key);
10057
- if (value === void 0 || typeof value === "function" || typeof value === "symbol") {
10058
- return null;
10059
- }
10060
- if (typeof value === "bigint") {
10061
- throw new TypeError("Do not know how to serialize a BigInt");
10062
- }
10063
- if (typeof value === "string") {
10064
- return jsonStringFragments(value);
10065
- }
10066
- if (value === null || typeof value !== "object") {
10067
- return [JSON.stringify(value)];
10068
- }
10069
- const rawJson = JSON;
10070
- if (rawJson.isRawJSON?.(value)) return [JSON.stringify(value)];
10071
- if (ancestors.has(value)) throw new TypeError("cyclic object value");
10072
- return Array.isArray(value) ? jsonArrayFragments(value, ancestors, depth) : jsonObjectFragments(value, ancestors, depth);
10073
- }
10074
- function* jsonArrayFragments(value, ancestors, depth) {
10075
- ancestors.add(value);
10076
- try {
10077
- const length = value.length;
10078
- yield "[";
10079
- for (let index = 0; index < length; index += 1) {
10080
- if (index > 0) yield ",";
10081
- const child = jsonValueFragments(value[index], String(index), ancestors, depth + 1);
10082
- if (child) yield* child;
10083
- else yield "null";
10084
- }
10085
- yield "]";
10086
- } finally {
10087
- ancestors.delete(value);
10088
- }
10089
- }
10090
- function* jsonObjectFragments(value, ancestors, depth) {
10091
- ancestors.add(value);
9953
+ function recordModelPreparationManifestInventory(phase, manifest) {
9954
+ const startedAt = performance.now();
9955
+ let outcome = "completed";
9956
+ let count = 0;
10092
9957
  try {
10093
- const keys = Object.keys(value);
10094
- let emitted = false;
10095
- yield "{";
10096
- for (const key of keys) {
10097
- const child = jsonValueFragments(value[key], key, ancestors, depth + 1);
10098
- if (!child) continue;
10099
- if (emitted) yield ",";
10100
- emitted = true;
10101
- yield* jsonStringFragments(key);
10102
- yield ":";
10103
- yield* child;
9958
+ if (manifest && typeof manifest === "object" && "iterEntries" in manifest && typeof manifest.iterEntries === "function") {
9959
+ for (const _entry of manifest.iterEntries()) count += 1;
10104
9960
  }
10105
- yield "}";
9961
+ } catch {
9962
+ outcome = "failed";
10106
9963
  } finally {
10107
- ancestors.delete(value);
9964
+ recordModelPreparationMeasurement({
9965
+ phase,
9966
+ outcome,
9967
+ durationSeconds: (performance.now() - startedAt) / 1e3,
9968
+ count
9969
+ });
10108
9970
  }
10109
9971
  }
10110
- function nativeJsonPropertyFragments(source, key) {
10111
- const holder = /* @__PURE__ */ Object.create(null);
10112
- holder[key] = source;
10113
- const serialized = JSON.stringify(holder);
10114
- if (serialized === "{}") return null;
10115
- const prefix = `{${JSON.stringify(key)}:`;
10116
- if (!serialized.startsWith(prefix) || !serialized.endsWith("}")) {
10117
- throw new TypeError("Model request body is not JSON serializable");
10118
- }
10119
- return boundedNativeJsonFragments(serialized.slice(prefix.length, -1));
9972
+
9973
+ // src/model-request-capture.ts
9974
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
9975
+ var modelRequestCapture = new AsyncLocalStorage3();
9976
+ var captureIndices = /* @__PURE__ */ new WeakMap();
9977
+ function nextModelContextCaptureIndex(agent) {
9978
+ const index = (captureIndices.get(agent) ?? 0) + 1;
9979
+ captureIndices.set(agent, index);
9980
+ return index;
10120
9981
  }
10121
- function* boundedNativeJsonFragments(serialized) {
10122
- for (let start = 0; start < serialized.length; ) {
10123
- let end = Math.min(serialized.length, start + TARGET_CHUNK_CHARS);
10124
- if (end < serialized.length && serialized.charCodeAt(end - 1) >= 55296 && serialized.charCodeAt(end - 1) <= 56319 && serialized.charCodeAt(end) >= 56320 && serialized.charCodeAt(end) <= 57343) {
10125
- end -= 1;
9982
+ function withModelRequestCapture(capture, fn) {
9983
+ return capture ? modelRequestCapture.run(capture, fn) : fn();
9984
+ }
9985
+ function captureProviderRequestBody(provider, input, init) {
9986
+ const context = modelRequestCapture.getStore();
9987
+ const callback = context?.onProviderRequest;
9988
+ if (!callback) return { init, captured: Promise.resolve(), cancel: () => {
9989
+ } };
9990
+ const index = context.nextProviderRequestIndex?.();
9991
+ const observer = (providerId, body2, reason) => callback(providerId, body2, reason, index);
9992
+ let cancel = () => {
9993
+ };
9994
+ let body = init?.body;
9995
+ let nextInit = init;
9996
+ if (body instanceof ReadableStream) {
9997
+ const [sent, inspected] = body.tee();
9998
+ nextInit = { ...init, body: sent };
9999
+ body = inspected;
10000
+ } else if (body == null && input instanceof Request) {
10001
+ body = input.clone().body;
10002
+ }
10003
+ const captured = (async () => {
10004
+ const limit = 4 * 1024 * 1024;
10005
+ let text2;
10006
+ if (typeof body === "string") {
10007
+ if (Buffer.byteLength(body, "utf8") > limit) {
10008
+ await observer(provider, null, "Request exceeds the 4 MiB capture limit.");
10009
+ return;
10010
+ }
10011
+ text2 = body;
10012
+ } else if (body instanceof ReadableStream) {
10013
+ const reader = body.getReader();
10014
+ let cancelled = false;
10015
+ cancel = () => {
10016
+ cancelled = true;
10017
+ void reader.cancel().catch(() => void 0);
10018
+ };
10019
+ const signal = init?.signal ?? (input instanceof Request ? input.signal : void 0);
10020
+ signal?.addEventListener("abort", cancel, { once: true });
10021
+ if (signal?.aborted) cancel();
10022
+ const decoder = new TextDecoder("utf-8", { fatal: true });
10023
+ const chunks = [];
10024
+ let bytes = 0;
10025
+ try {
10026
+ while (true) {
10027
+ const chunk = await reader.read();
10028
+ if (chunk.done) break;
10029
+ bytes += chunk.value.byteLength;
10030
+ if (bytes > limit) {
10031
+ void reader.cancel().catch(() => void 0);
10032
+ await observer(provider, null, "Request exceeds the 4 MiB capture limit.");
10033
+ return;
10034
+ }
10035
+ chunks.push(decoder.decode(chunk.value, { stream: true }));
10036
+ }
10037
+ if (cancelled) return;
10038
+ chunks.push(decoder.decode());
10039
+ text2 = chunks.join("");
10040
+ } catch {
10041
+ void reader.cancel().catch(() => void 0);
10042
+ if (!cancelled)
10043
+ await observer(provider, null, "The provider body could not be read as UTF-8.");
10044
+ return;
10045
+ } finally {
10046
+ signal?.removeEventListener("abort", cancel);
10047
+ reader.releaseLock();
10048
+ cancel = () => {
10049
+ };
10050
+ }
10051
+ } else {
10052
+ await observer(provider, null, "This transport body cannot be inspected.");
10053
+ return;
10126
10054
  }
10127
- yield serialized.slice(start, end);
10128
- start = end;
10055
+ await observer(provider, text2);
10056
+ })().catch(() => void 0);
10057
+ return { init: nextInit, captured, cancel: () => cancel() };
10058
+ }
10059
+ async function notifyModelRequestCapture(request) {
10060
+ const capture = modelRequestCapture.getStore();
10061
+ if (!capture) return;
10062
+ try {
10063
+ await capture(snapshotModelRequestPrefix(request));
10064
+ } catch {
10129
10065
  }
10130
10066
  }
10131
- function prepareJsonValue(source, key) {
10132
- let value = source;
10133
- const sourceType = typeof value;
10134
- if (value !== null && (sourceType === "object" || sourceType === "function" || sourceType === "bigint")) {
10135
- const toJSON = value.toJSON;
10136
- if (typeof toJSON === "function") value = toJSON.call(value, key);
10067
+ function snapshotModelRequestPrefix(request) {
10068
+ return {
10069
+ ...request,
10070
+ tools: structuredClone(request.tools)
10071
+ };
10072
+ }
10073
+ var ModelRequestCaptureModel = class {
10074
+ constructor(inner) {
10075
+ this.inner = inner;
10137
10076
  }
10138
- if (value !== null && typeof value === "object") {
10139
- if (utilTypes.isNumberObject(value)) return Number.prototype.valueOf.call(value);
10140
- if (utilTypes.isStringObject(value)) return String.prototype.valueOf.call(value);
10141
- if (utilTypes.isBooleanObject(value)) return Boolean.prototype.valueOf.call(value);
10142
- if (utilTypes.isBigIntObject(value)) return BigInt.prototype.valueOf.call(value);
10077
+ async getResponse(request) {
10078
+ rememberPreparedModelRequest(request);
10079
+ void notifyModelRequestCapture(request);
10080
+ return this.inner.getResponse(request);
10143
10081
  }
10144
- return value;
10145
- }
10146
- function* jsonStringFragments(value) {
10147
- if (value.length <= LARGE_STRING_SOURCE_CHARS) {
10148
- yield JSON.stringify(value);
10149
- return;
10082
+ async *getStreamedResponse(request) {
10083
+ rememberPreparedModelRequest(request);
10084
+ void notifyModelRequestCapture(request);
10085
+ yield* this.inner.getStreamedResponse(request);
10150
10086
  }
10151
- yield '"';
10152
- for (let start = 0; start < value.length; ) {
10153
- let end = Math.min(value.length, start + STRING_SLICE_CODE_UNITS);
10154
- if (end < value.length && value.charCodeAt(end - 1) >= 55296 && value.charCodeAt(end - 1) <= 56319 && value.charCodeAt(end) >= 56320 && value.charCodeAt(end) <= 57343) {
10155
- end -= 1;
10156
- }
10157
- const encoded = JSON.stringify(value.slice(start, end));
10158
- yield encoded.slice(1, -1);
10159
- start = end;
10087
+ getRetryAdvice(args) {
10088
+ return this.inner.getRetryAdvice?.(args);
10160
10089
  }
10161
- yield '"';
10162
- }
10090
+ };
10091
+ var ModelRequestCaptureProvider = class {
10092
+ constructor(inner) {
10093
+ this.inner = inner;
10094
+ }
10095
+ async getModel(modelName) {
10096
+ const model = await this.inner.getModel(modelName);
10097
+ if (model instanceof ModelRequestCaptureModel) return model;
10098
+ return new ModelRequestCaptureModel(model);
10099
+ }
10100
+ };
10163
10101
 
10164
10102
  // src/provider-quota.ts
10165
10103
  import { APIError } from "openai";
@@ -10313,12 +10251,12 @@ function errorTexts(value, out, seen) {
10313
10251
  }
10314
10252
  if (!value || typeof value !== "object" || seen.has(value)) return;
10315
10253
  seen.add(value);
10316
- const record2 = value;
10254
+ const record = value;
10317
10255
  for (const key of ["message", "code", "type", "name", "param"]) {
10318
- const field = record2[key];
10256
+ const field = record[key];
10319
10257
  if (typeof field === "string" && field.length > 0) out.push(field);
10320
10258
  }
10321
- for (const key of ["error", "cause", "response", "data"]) errorTexts(record2[key], out, seen);
10259
+ for (const key of ["error", "cause", "response", "data"]) errorTexts(record[key], out, seen);
10322
10260
  }
10323
10261
  function headerValue(headers, name) {
10324
10262
  if (!headers || typeof headers !== "object") return null;
@@ -10411,19 +10349,12 @@ function withoutQuotaExhaustedRetries(inner) {
10411
10349
  // src/claude-subscription-usage.ts
10412
10350
  import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
10413
10351
  var observers = new AsyncLocalStorage4();
10414
- function withClaudeUsageObserver(observer, run2, prepare) {
10415
- return observers.run({ observe: observer, ...prepare ? { prepare } : {} }, run2);
10416
- }
10417
- async function prepareClaudeSubscriptionRequest(providerId, input, init) {
10418
- const prepare = observers.getStore()?.prepare;
10419
- if (!prepare) return init;
10420
- const headers = new Headers(input instanceof Request ? input.headers : void 0);
10421
- new Headers(init?.headers).forEach((value, key) => headers.set(key, value));
10422
- return { ...init, headers: await prepare(providerId, headers) };
10352
+ function withClaudeUsageObserver(observer, run2) {
10353
+ return observers.run(observer, run2);
10423
10354
  }
10424
10355
  function observeClaudeUsageResponse(providerId, response) {
10425
10356
  try {
10426
- observers.getStore()?.observe(providerId, response);
10357
+ observers.getStore()?.(providerId, response);
10427
10358
  } catch {
10428
10359
  }
10429
10360
  }
@@ -10696,7 +10627,6 @@ function instrumentedModelFetch(provider, inner) {
10696
10627
  if (!isModelCallFetch(input)) {
10697
10628
  return await inner(input, init);
10698
10629
  }
10699
- init = await prepareClaudeSubscriptionRequest(provider, input, init);
10700
10630
  await recordModelTransportStarted();
10701
10631
  const capture = captureProviderRequestBody(provider, input, init);
10702
10632
  const started = performance.now();
@@ -10763,7 +10693,7 @@ var RunMcpCredentials = class {
10763
10693
  #closed = false;
10764
10694
  #onAbort = () => this.close();
10765
10695
  constructor(targets, options = {}) {
10766
- this.#targets = targets.filter((target) => !target.connectionRef).map(({ id, url }) => ({ id, url }));
10696
+ this.#targets = targets.map(({ id, url }) => ({ id, url }));
10767
10697
  this.#signal = options.signal;
10768
10698
  this.#now = options.now ?? Date.now;
10769
10699
  this.#signal?.addEventListener("abort", this.#onAbort, { once: true });
@@ -10840,11 +10770,11 @@ var RunMcpCredentials = class {
10840
10770
  replace(material) {
10841
10771
  this.prepare(material)();
10842
10772
  }
10843
- /** Refuse credentials for native, omitted, local, or rewritten server routes. */
10773
+ /** Refuse credentials for omitted, local, or rewritten server routes. */
10844
10774
  assertRemoteTargets(targets) {
10845
10775
  this.#remoteTargets = this.#targets.filter(
10846
10776
  (original) => targets.some(
10847
- (target) => !target.connectionRef && target.id === original.id && normalizedUrl(target.url) !== null && normalizedUrl(target.url) === normalizedUrl(original.url)
10777
+ (target) => target.id === original.id && normalizedUrl(target.url) !== null && normalizedUrl(target.url) === normalizedUrl(original.url)
10848
10778
  )
10849
10779
  );
10850
10780
  this.#dropExcluded();
@@ -10887,10 +10817,6 @@ var RunMcpCredentials = class {
10887
10817
  /** Called at the literal fetch boundary, including POST, SSE GET and DELETE. */
10888
10818
  requestInit(target, input, init) {
10889
10819
  this.#assertOpen();
10890
- if (target.connectionRef) {
10891
- this.excludeLocalTarget(target.id);
10892
- return init;
10893
- }
10894
10820
  this.assertAvailable(target.id);
10895
10821
  const entry = this.#entries.get(target.id);
10896
10822
  if (!entry) return init;
@@ -12090,7 +12016,6 @@ var LazyToolModel = class {
12090
12016
  this.runtime = runtime;
12091
12017
  }
12092
12018
  async getResponse(request) {
12093
- await beforeModelRequest();
12094
12019
  const prepared = prepareLazyToolRequest(request, this.runtime);
12095
12020
  rememberPreparedModelRequest(prepared);
12096
12021
  void notifyModelRequestCapture(prepared);
@@ -12101,7 +12026,6 @@ var LazyToolModel = class {
12101
12026
  return this.runtime.transport === "generic_dispatch" ? transformGenericDispatchResponse(response, this.runtime) : response;
12102
12027
  }
12103
12028
  async *getStreamedResponse(request) {
12104
- await beforeModelRequest();
12105
12029
  const prepared = prepareLazyToolRequest(request, this.runtime);
12106
12030
  rememberPreparedModelRequest(prepared);
12107
12031
  void notifyModelRequestCapture(prepared);
@@ -12111,18 +12035,19 @@ var LazyToolModel = class {
12111
12035
  await this.runtime.ensurePrepared();
12112
12036
  }
12113
12037
  }
12114
- const delivered = this.runtime.transport === "generic_dispatch" && event.type === "response_done" ? {
12115
- ...event,
12116
- response: {
12117
- ...event.response,
12118
- output: event.response.output.flatMap(
12119
- (item) => transformGenericDispatchCall(item, this.runtime)
12120
- )
12121
- }
12122
- } : event;
12123
- const settlement = modelResponseSettlement(delivered);
12124
- void settlement?.catch(() => void 0);
12125
- yield delivered;
12038
+ if (this.runtime.transport === "generic_dispatch" && event.type === "response_done") {
12039
+ yield {
12040
+ ...event,
12041
+ response: {
12042
+ ...event.response,
12043
+ output: event.response.output.flatMap(
12044
+ (item) => transformGenericDispatchCall(item, this.runtime)
12045
+ )
12046
+ }
12047
+ };
12048
+ } else {
12049
+ yield event;
12050
+ }
12126
12051
  }
12127
12052
  }
12128
12053
  getRetryAdvice(args) {
@@ -13015,12 +12940,6 @@ var InputWaitYield = class {
13015
12940
  this.closeAdmission();
13016
12941
  await this.drain(this.scope, signal);
13017
12942
  }
13018
- /** A settled stream may need one final-reply handoff before attempt closure.
13019
- * Drain already-admitted receipts without reopening that stream's admission.
13020
- */
13021
- async drainForHandoff(signal = this.scope.signal) {
13022
- await this.drain(this.scope, signal);
13023
- }
13024
12943
  endStream(scope) {
13025
12944
  scope.phase = "settled";
13026
12945
  scope.ended = true;
@@ -13179,7 +13098,6 @@ function withRetainableSessionImageOutputHook(tools, hook) {
13179
13098
 
13180
13099
  // src/model-provider-routing.ts
13181
13100
  import { configuredProviders, resolveModelProvider } from "@opengeni/config";
13182
- import { APIError as APIError2 } from "openai";
13183
13101
  import { CODEX_MODEL_ID_PREFIX } from "@opengeni/codex";
13184
13102
  import { XAI_SUBSCRIPTION_MODEL_ID_PREFIX } from "@opengeni/xai-subscription";
13185
13103
 
@@ -13243,99 +13161,6 @@ var AppendOnlyOpenAIResponsesModel = class extends OpenAIResponsesModel {
13243
13161
  }
13244
13162
  };
13245
13163
 
13246
- // src/responses-terminal-error.ts
13247
- var DIAGNOSTIC_MAX_BYTES = 4 * 1024;
13248
- var FIELD_MAX_BYTES = 256;
13249
- var TRUNCATION_MARKER = "\u2026 [truncated]";
13250
- function boundedField(value, maxBytes) {
13251
- if (typeof value !== "string") return void 0;
13252
- const bytes = new TextEncoder().encode(value);
13253
- if (bytes.byteLength <= maxBytes) return value;
13254
- let end = maxBytes - new TextEncoder().encode(TRUNCATION_MARKER).byteLength;
13255
- while (end > 0 && (bytes[end] & 192) === 128) end -= 1;
13256
- return `${new TextDecoder().decode(bytes.subarray(0, end))}${TRUNCATION_MARKER}`;
13257
- }
13258
- function record(value) {
13259
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
13260
- }
13261
- var SAFETY_CODES = /* @__PURE__ */ new Set([
13262
- "content_policy_violation",
13263
- "content_filter",
13264
- "contentpolicyviolation",
13265
- "contentfilter",
13266
- "responsibleaipolicyviolation",
13267
- "safety_violation",
13268
- "bio_policy",
13269
- "cyber_policy"
13270
- ]);
13271
- var REQUEST_CODES = /* @__PURE__ */ new Set([
13272
- "invalid_request",
13273
- "invalid_request_error",
13274
- "invalidrequest",
13275
- "invalid_prompt",
13276
- "context_length_exceeded",
13277
- "invalid_argument"
13278
- ]);
13279
- var RATE_CODES = /* @__PURE__ */ new Set([
13280
- "rate_limit_exceeded",
13281
- "rate_limit_error",
13282
- "rate_limited",
13283
- "ratelimitexceeded",
13284
- "too_many_requests",
13285
- "429"
13286
- ]);
13287
- var UNAVAILABLE_CODES = /* @__PURE__ */ new Set([
13288
- "server_error",
13289
- "internal_server_error",
13290
- "service_unavailable",
13291
- "overloaded",
13292
- "overloaded_error",
13293
- "model_overloaded",
13294
- "engine_overloaded",
13295
- "server_overloaded"
13296
- ]);
13297
- var ResponsesStreamingTerminalError = class extends Error {
13298
- constructor(eventType, source, headers) {
13299
- super(`Responses request terminated unsuccessfully (${eventType}).`);
13300
- this.eventType = eventType;
13301
- this.name = "ResponsesStreamingTerminalError";
13302
- const error = record(source);
13303
- this.code = boundedField(error?.code, FIELD_MAX_BYTES);
13304
- this.type = boundedField(error?.type, FIELD_MAX_BYTES);
13305
- this.detail = boundedField(error?.message ?? source, DIAGNOSTIC_MAX_BYTES) ?? this.message;
13306
- this.headers = new Headers();
13307
- const retryAfter = boundedField(headers?.get("retry-after"), FIELD_MAX_BYTES);
13308
- if (retryAfter !== void 0) this.headers.set("retry-after", retryAfter);
13309
- const directSeconds = Number(error?.retry_after_seconds ?? error?.retryAfterSeconds);
13310
- const header = this.headers.get("retry-after");
13311
- const headerSeconds = header ? Number(header) : Number.NaN;
13312
- const headerDate = header && !Number.isFinite(headerSeconds) ? Date.parse(header) : Number.NaN;
13313
- const seconds = Number.isFinite(directSeconds) ? directSeconds : Number.isFinite(headerSeconds) ? headerSeconds : Number.isFinite(headerDate) ? Math.max(0, (headerDate - Date.now()) / 1e3) : Number.NaN;
13314
- this.retryAfterSeconds = Number.isFinite(seconds) && seconds > 0 ? seconds : void 0;
13315
- const codes = [this.code, this.type].map((value) => value?.toLowerCase());
13316
- const matches = (allowed) => codes.some((value) => value !== void 0 && allowed.has(value));
13317
- const recoveryCode = codes[0] || codes[1];
13318
- this.category = matches(SAFETY_CODES) || /\bthis request was blocked by our safety systems\b/i.test(this.detail) ? "safety" : matches(REQUEST_CODES) ? "request" : recoveryCode !== void 0 && RATE_CODES.has(recoveryCode) ? "rate_limit" : recoveryCode !== void 0 && UNAVAILABLE_CODES.has(recoveryCode) ? "unavailable" : "unknown";
13319
- }
13320
- code;
13321
- type;
13322
- detail;
13323
- headers;
13324
- retryAfterSeconds;
13325
- category;
13326
- };
13327
- function responsesStreamingTerminalError(event, headers) {
13328
- const value = record(event);
13329
- if (value?.type !== "response.failed" && value?.type !== "response.error" && value?.type !== "error") {
13330
- return void 0;
13331
- }
13332
- return new ResponsesStreamingTerminalError(
13333
- value.type,
13334
- value.error ?? record(value.response)?.error ?? value,
13335
- headers
13336
- );
13337
- }
13338
-
13339
13164
  // src/model-provider-routing.ts
13340
13165
  function isUnknownFinishReason(value) {
13341
13166
  return typeof value === "string" && value.trim().toLowerCase() === "unknown";
@@ -13378,58 +13203,6 @@ var OpenGeniResponsesModel = class extends AppendOnlyOpenAIResponsesModel {
13378
13203
  super(client, model);
13379
13204
  this.provider = provider;
13380
13205
  }
13381
- async _fetchResponse(request, stream) {
13382
- if (!stream || !this.ownsResponsesTerminalClassification()) {
13383
- return await super._fetchResponse(request, stream);
13384
- }
13385
- const built = this._buildResponsesCreateRequest(request, true);
13386
- const internal = request._internal;
13387
- const pending = this._client.responses.create(
13388
- built.requestData,
13389
- {
13390
- headers: built.sdkRequestHeaders,
13391
- signal: built.signal,
13392
- ...built.transportExtraQuery ? { query: built.transportExtraQuery } : {},
13393
- ...internal?.runnerManagedRetry === true ? { maxRetries: 0 } : {}
13394
- }
13395
- );
13396
- if (typeof pending.withResponse !== "function") {
13397
- return this.classifiedResponseStream(await pending, new Headers(), null);
13398
- }
13399
- const receipt = await pending.withResponse();
13400
- return this.classifiedResponseStream(
13401
- receipt.data,
13402
- receipt.response.headers,
13403
- receipt.request_id
13404
- );
13405
- }
13406
- async *classifiedResponseStream(stream, headers, requestId) {
13407
- try {
13408
- for await (const event of stream) {
13409
- const failure = responsesStreamingTerminalError(event, headers);
13410
- if (failure) throw failure;
13411
- const eventType = event.type;
13412
- if (requestId && (eventType === "response.completed" || eventType === "response.done") && "response" in event && event.response && !("_request_id" in event.response)) {
13413
- try {
13414
- Object.defineProperty(event.response, "_request_id", {
13415
- value: requestId,
13416
- enumerable: false
13417
- });
13418
- } catch {
13419
- }
13420
- }
13421
- yield event;
13422
- }
13423
- } catch (error) {
13424
- if (error instanceof APIError2 && error.status === void 0 && error.error) {
13425
- throw new ResponsesStreamingTerminalError("response.error", error.error, headers);
13426
- }
13427
- throw error;
13428
- }
13429
- }
13430
- ownsResponsesTerminalClassification() {
13431
- return this.provider.kind !== "codex-subscription" && this.provider.kind !== "xai-subscription";
13432
- }
13433
13206
  _buildResponsesCreateRequest(request, stream) {
13434
13207
  const startedAt = performance.now();
13435
13208
  let outcome = "completed";
@@ -13924,7 +13697,7 @@ import { existsSync, readdirSync } from "fs";
13924
13697
  // ../sdk/package.json
13925
13698
  var package_default = {
13926
13699
  name: "@opengeni/sdk",
13927
- version: "7.4.0-canary.36855269964001",
13700
+ version: "7.4.0",
13928
13701
  description: "Framework-agnostic TypeScript SDK for the OpenGeni API: typed client, session lifecycle, SSE event streaming with reconnect + replay-by-sequence, and proxy re-streaming helpers.",
13929
13702
  license: "Apache-2.0",
13930
13703
  repository: {
@@ -13946,10 +13719,6 @@ var package_default = {
13946
13719
  module: "./src/index.ts",
13947
13720
  types: "./src/index.ts",
13948
13721
  exports: {
13949
- "./allowance-refusal": {
13950
- types: "./src/allowance-refusal.ts",
13951
- default: "./src/allowance-refusal.ts"
13952
- },
13953
13722
  ".": {
13954
13723
  types: "./src/index.ts",
13955
13724
  default: "./src/index.ts"
@@ -13978,10 +13747,6 @@ var package_default = {
13978
13747
  types: "./src/knowledge.ts",
13979
13748
  default: "./src/knowledge.ts"
13980
13749
  },
13981
- "./usage-allowances": {
13982
- types: "./src/usage-allowances.ts",
13983
- default: "./src/usage-allowances.ts"
13984
- },
13985
13750
  "./workspace-integrations": {
13986
13751
  types: "./src/workspace-integrations.ts",
13987
13752
  default: "./src/workspace-integrations.ts"
@@ -14054,10 +13819,6 @@ var package_default = {
14054
13819
  types: "./src/chat/index.ts",
14055
13820
  default: "./src/chat/index.ts"
14056
13821
  },
14057
- "./session-proxy": {
14058
- types: "./src/session-proxy.ts",
14059
- default: "./src/session-proxy.ts"
14060
- },
14061
13822
  "./next": {
14062
13823
  types: "./src/adapters/next.ts",
14063
13824
  default: "./src/adapters/next.ts"
@@ -14104,7 +13865,7 @@ var package_default = {
14104
13865
  // ../react/package.json
14105
13866
  var package_default2 = {
14106
13867
  name: "@opengeni/react",
14107
- version: "7.4.0-canary.36855269964001",
13868
+ version: "7.4.0",
14108
13869
  description: "React hooks and styled components for OpenGeni: live session streaming, chat composer, message timeline, session status, and fleet views \u2014 token-themed (CSS variables), dark-first, built on Tailwind v4 + Radix + Motion.",
14109
13870
  license: "Apache-2.0",
14110
13871
  repository: {
@@ -14162,10 +13923,6 @@ var package_default2 = {
14162
13923
  types: "./src/accounts.tsx",
14163
13924
  default: "./src/accounts.tsx"
14164
13925
  },
14165
- "./usage": {
14166
- types: "./src/usage.ts",
14167
- default: "./src/usage.ts"
14168
- },
14169
13926
  "./machines": {
14170
13927
  types: "./src/machines.ts",
14171
13928
  default: "./src/machines.ts"
@@ -14365,7 +14122,7 @@ var package_default2 = {
14365
14122
  // ../codemode/package.json
14366
14123
  var package_default3 = {
14367
14124
  name: "@opengeni/codemode",
14368
- version: "0.6.5-canary.36855269964001",
14125
+ version: "0.6.5",
14369
14126
  description: "Attempt-frozen programmatic tool catalog and execution authority for OpenGeni.",
14370
14127
  license: "Apache-2.0",
14371
14128
  repository: {
@@ -14415,7 +14172,7 @@ var package_default3 = {
14415
14172
  // ../ogtool/package.json
14416
14173
  var package_default4 = {
14417
14174
  name: "@opengeni/ogtool",
14418
- version: "0.3.47-canary.36855269964001",
14175
+ version: "0.3.47",
14419
14176
  description: "Codemode CLI and typed client entrypoint for an OpenGeni execution attempt.",
14420
14177
  license: "Apache-2.0",
14421
14178
  repository: {
@@ -14799,13 +14556,13 @@ function contextTextEstimate(value) {
14799
14556
  const containsNonText = (part) => {
14800
14557
  if (Array.isArray(part)) return part.some(containsNonText);
14801
14558
  if (!part || typeof part !== "object") return false;
14802
- const record2 = part;
14803
- if (typeof record2.encrypted_content === "string") return true;
14559
+ const record = part;
14560
+ if (typeof record.encrypted_content === "string") return true;
14804
14561
  if (["input_image", "image_url", "input_audio", "input_file", "compaction"].includes(
14805
- String(record2.type)
14562
+ String(record.type)
14806
14563
  ))
14807
14564
  return true;
14808
- return Object.values(record2).some(containsNonText);
14565
+ return Object.values(record).some(containsNonText);
14809
14566
  };
14810
14567
  return containsNonText(value) ? null : estimateSerializedValueTokens(value);
14811
14568
  }
@@ -15083,14 +14840,14 @@ function countedTool(input) {
15083
14840
  };
15084
14841
  }
15085
14842
  function serializedToolToModelContextTool(tool2, visibility) {
15086
- const record2 = tool2;
15087
- const schema = record2.parameters !== void 0 ? record2.parameters : record2.providerData !== void 0 ? record2.providerData : void 0;
14843
+ const record = tool2;
14844
+ const schema = record.parameters !== void 0 ? record.parameters : record.providerData !== void 0 ? record.providerData : void 0;
15088
14845
  return countedTool({
15089
- name: typeof record2.name === "string" && record2.name.length > 0 ? record2.name : tool2.type,
14846
+ name: typeof record.name === "string" && record.name.length > 0 ? record.name : tool2.type,
15090
14847
  type: tool2.type,
15091
14848
  visibility,
15092
- ...typeof record2.description === "string" ? { description: record2.description } : {},
15093
- ...typeof record2.namespace === "string" ? { namespace: record2.namespace } : {},
14849
+ ...typeof record.description === "string" ? { description: record.description } : {},
14850
+ ...typeof record.namespace === "string" ? { namespace: record.namespace } : {},
15094
14851
  ...schema !== void 0 ? { schema } : {}
15095
14852
  });
15096
14853
  }
@@ -15141,15 +14898,15 @@ function skillsFromGovernanceLayer(content) {
15141
14898
  if (Array.isArray(parsed)) {
15142
14899
  for (const entry of parsed) {
15143
14900
  if (!entry || typeof entry !== "object") continue;
15144
- const record2 = entry;
15145
- const name = typeof record2.title === "string" ? record2.title : typeof record2.stableKey === "string" ? record2.stableKey : null;
15146
- const description = typeof record2.description === "string" ? record2.description : "";
14901
+ const record = entry;
14902
+ const name = typeof record.title === "string" ? record.title : typeof record.stableKey === "string" ? record.stableKey : null;
14903
+ const description = typeof record.description === "string" ? record.description : "";
15147
14904
  if (!name) continue;
15148
14905
  skills.push({
15149
14906
  kind: "preference_descriptor",
15150
14907
  name,
15151
14908
  description,
15152
- source: typeof record2.scope === "string" ? record2.scope : void 0
14909
+ source: typeof record.scope === "string" ? record.scope : void 0
15153
14910
  });
15154
14911
  }
15155
14912
  }
@@ -15740,14 +15497,14 @@ function modelInputItemType(value) {
15740
15497
  }
15741
15498
  function modelInputFileMediaType(value) {
15742
15499
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
15743
- const record2 = value;
15500
+ const record = value;
15744
15501
  for (const field of ["contentType", "content_type", "mediaType", "media_type", "mimeType"]) {
15745
- const candidate = record2[field];
15502
+ const candidate = record[field];
15746
15503
  if (typeof candidate === "string" && candidate.trim()) {
15747
15504
  return candidate.toLowerCase().split(";", 1)[0].trim();
15748
15505
  }
15749
15506
  }
15750
- const fileValue = record2.file;
15507
+ const fileValue = record.file;
15751
15508
  if (typeof fileValue === "string") {
15752
15509
  const match = /^data:([^;,]+)[;,]/i.exec(fileValue);
15753
15510
  if (match?.[1]) return match[1].toLowerCase();
@@ -15911,21 +15668,21 @@ var CLIENT_TOOL_CALL_ITEM_TYPES = /* @__PURE__ */ new Set([
15911
15668
  ]);
15912
15669
  function isClientToolWork(item) {
15913
15670
  if (!item || typeof item !== "object") return false;
15914
- const record2 = item;
15915
- if (record2.type === "tool_search_call") {
15916
- return (record2.execution ?? record2.providerData?.execution) !== "server";
15671
+ const record = item;
15672
+ if (record.type === "tool_search_call") {
15673
+ return (record.execution ?? record.providerData?.execution) !== "server";
15917
15674
  }
15918
- return CLIENT_TOOL_CALL_ITEM_TYPES.has(String(record2.type));
15675
+ return CLIENT_TOOL_CALL_ITEM_TYPES.has(String(record.type));
15919
15676
  }
15920
15677
  function isAssistantMessageItem(item) {
15921
15678
  if (!item || typeof item !== "object") return false;
15922
- const record2 = item;
15923
- return record2.type === "message" && (record2.role === void 0 || record2.role === "assistant");
15679
+ const record = item;
15680
+ return record.type === "message" && (record.role === void 0 || record.role === "assistant");
15924
15681
  }
15925
15682
  function declaredAssistantMessagePhase(item) {
15926
15683
  if (!item || typeof item !== "object") return void 0;
15927
- const record2 = item;
15928
- const phase = record2.phase ?? record2.providerData?.phase;
15684
+ const record = item;
15685
+ const phase = record.phase ?? record.providerData?.phase;
15929
15686
  return phase === "commentary" || phase === "final_answer" ? phase : void 0;
15930
15687
  }
15931
15688
  function providerMessageId(item) {
@@ -16073,38 +15830,38 @@ function imageDataByteLength(data) {
16073
15830
  return data.every((value) => typeof value === "number") ? data.length : null;
16074
15831
  }
16075
15832
  if (!data || typeof data !== "object") return null;
16076
- const record2 = data;
16077
- if (record2.type === "Buffer" && Array.isArray(record2.data)) {
16078
- return record2.data.every((value) => typeof value === "number") ? record2.data.length : null;
15833
+ const record = data;
15834
+ if (record.type === "Buffer" && Array.isArray(record.data)) {
15835
+ return record.data.every((value) => typeof value === "number") ? record.data.length : null;
16079
15836
  }
16080
- const keys = Object.keys(record2);
16081
- return keys.length > 0 && keys.every((key) => /^\d+$/.test(key) && typeof record2[key] === "number") ? keys.length : null;
15837
+ const keys = Object.keys(record);
15838
+ return keys.length > 0 && keys.every((key) => /^\d+$/.test(key) && typeof record[key] === "number") ? keys.length : null;
16082
15839
  }
16083
15840
  function toolOutputMediaPreview(value) {
16084
15841
  if (typeof value === "string") {
16085
15842
  return sessionEventMediaPreviewFromDataUrl(value);
16086
15843
  }
16087
15844
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
16088
- const record2 = value;
16089
- if (record2.type === "input_image") {
16090
- const source = record2.image ?? record2.image_url ?? record2.imageUrl;
15845
+ const record = value;
15846
+ if (record.type === "input_image") {
15847
+ const source = record.image ?? record.image_url ?? record.imageUrl;
16091
15848
  const url = typeof source === "string" ? source : source && typeof source === "object" ? source.url : null;
16092
15849
  if (typeof url !== "string" || url.length === 0) return null;
16093
15850
  return sessionEventMediaPreviewFromDataUrl(url) ?? sessionEventMediaPreview("image/*", null);
16094
15851
  }
16095
- if ((record2.type === "image" || record2.type === "audio") && typeof record2.data === "string") {
16096
- const mediaType2 = typeof record2.mimeType === "string" && record2.mimeType.length > 0 ? record2.mimeType : record2.type === "audio" ? "audio/*" : "image/png";
16097
- return sessionEventMediaPreviewFromDataUrl(record2.data) ?? sessionEventMediaPreview(mediaType2, base64DecodedByteLength(record2.data));
15852
+ if ((record.type === "image" || record.type === "audio") && typeof record.data === "string") {
15853
+ const mediaType2 = typeof record.mimeType === "string" && record.mimeType.length > 0 ? record.mimeType : record.type === "audio" ? "audio/*" : "image/png";
15854
+ return sessionEventMediaPreviewFromDataUrl(record.data) ?? sessionEventMediaPreview(mediaType2, base64DecodedByteLength(record.data));
16098
15855
  }
16099
- if (record2.type === "resource" && record2.resource && typeof record2.resource === "object") {
16100
- const resource = record2.resource;
15856
+ if (record.type === "resource" && record.resource && typeof record.resource === "object") {
15857
+ const resource = record.resource;
16101
15858
  if (typeof resource.blob === "string") {
16102
15859
  const mediaType2 = typeof resource.mimeType === "string" && resource.mimeType.length > 0 ? resource.mimeType : "application/octet-stream";
16103
15860
  return sessionEventMediaPreviewFromDataUrl(resource.blob) ?? sessionEventMediaPreview(mediaType2, base64DecodedByteLength(resource.blob));
16104
15861
  }
16105
15862
  }
16106
- if (record2.type !== "image" || !record2.image || typeof record2.image !== "object") return null;
16107
- const image = record2.image;
15863
+ if (record.type !== "image" || !record.image || typeof record.image !== "object") return null;
15864
+ const image = record.image;
16108
15865
  const mediaType = typeof image.mediaType === "string" && image.mediaType.length > 0 ? image.mediaType : "image/png";
16109
15866
  if (typeof image.url === "string" && image.url.length > 0) {
16110
15867
  return sessionEventMediaPreviewFromDataUrl(image.url) ?? sessionEventMediaPreview(mediaType, null);
@@ -16128,11 +15885,11 @@ function normalizeToolOutputForEvent(output) {
16128
15885
  return normalized;
16129
15886
  }
16130
15887
  if (output && typeof output === "object") {
16131
- const record2 = output;
16132
- if (Array.isArray(record2.content)) {
15888
+ const record = output;
15889
+ if (Array.isArray(record.content)) {
16133
15890
  return {
16134
- ...record2,
16135
- content: record2.content.map((el) => toolOutputMediaPreview(el) ?? el)
15891
+ ...record,
15892
+ content: record.content.map((el) => toolOutputMediaPreview(el) ?? el)
16136
15893
  };
16137
15894
  }
16138
15895
  }
@@ -16322,9 +16079,9 @@ function gatewayBillingFromResponse(response) {
16322
16079
  if (!response || typeof response !== "object" || Array.isArray(response)) {
16323
16080
  return null;
16324
16081
  }
16325
- const record2 = response;
16326
- const providerData = record2.providerData && typeof record2.providerData === "object" && !Array.isArray(record2.providerData) ? record2.providerData : null;
16327
- const metadataCandidate = record2.provider_metadata ?? record2.providerMetadata ?? providerData?.provider_metadata ?? providerData?.providerMetadata;
16082
+ const record = response;
16083
+ const providerData = record.providerData && typeof record.providerData === "object" && !Array.isArray(record.providerData) ? record.providerData : null;
16084
+ const metadataCandidate = record.provider_metadata ?? record.providerMetadata ?? providerData?.provider_metadata ?? providerData?.providerMetadata;
16328
16085
  if (!metadataCandidate || typeof metadataCandidate !== "object" || Array.isArray(metadataCandidate)) {
16329
16086
  return null;
16330
16087
  }
@@ -16367,12 +16124,12 @@ function modelResponseServiceTierFromResponse(response) {
16367
16124
  if (!response || typeof response !== "object") {
16368
16125
  return null;
16369
16126
  }
16370
- const record2 = response;
16371
- const direct = record2.service_tier ?? record2.serviceTier;
16127
+ const record = response;
16128
+ const direct = record.service_tier ?? record.serviceTier;
16372
16129
  if (typeof direct === "string" && direct.length > 0) {
16373
16130
  return direct;
16374
16131
  }
16375
- const providerData = record2.providerData && typeof record2.providerData === "object" ? record2.providerData : null;
16132
+ const providerData = record.providerData && typeof record.providerData === "object" ? record.providerData : null;
16376
16133
  const nested = providerData?.service_tier ?? providerData?.serviceTier;
16377
16134
  return typeof nested === "string" && nested.length > 0 ? nested : null;
16378
16135
  }
@@ -16396,10 +16153,10 @@ function usageFromResponse(response) {
16396
16153
  if (!raw || typeof raw !== "object") {
16397
16154
  return null;
16398
16155
  }
16399
- const record2 = raw;
16156
+ const record = raw;
16400
16157
  const usage = {
16401
16158
  ...numberProp(
16402
- record2,
16159
+ record,
16403
16160
  "inputTokens",
16404
16161
  "inputTokens",
16405
16162
  "input_tokens",
@@ -16407,17 +16164,17 @@ function usageFromResponse(response) {
16407
16164
  "prompt_tokens"
16408
16165
  ),
16409
16166
  ...numberProp(
16410
- record2,
16167
+ record,
16411
16168
  "outputTokens",
16412
16169
  "outputTokens",
16413
16170
  "output_tokens",
16414
16171
  "completionTokens",
16415
16172
  "completion_tokens"
16416
16173
  ),
16417
- ...numberProp(record2, "totalTokens", "totalTokens", "total_tokens"),
16418
- ...inputTokenDetailsProp(record2),
16419
- ...outputTokenDetailsProp(record2),
16420
- ...requestUsageEntriesProp(record2)
16174
+ ...numberProp(record, "totalTokens", "totalTokens", "total_tokens"),
16175
+ ...inputTokenDetailsProp(record),
16176
+ ...outputTokenDetailsProp(record),
16177
+ ...requestUsageEntriesProp(record)
16421
16178
  };
16422
16179
  return Object.keys(usage).length > 0 ? usage : null;
16423
16180
  }
@@ -17292,8 +17049,7 @@ function createInteractionAttemptToolDefinitions(input) {
17292
17049
  options.output,
17293
17050
  raw,
17294
17051
  context,
17295
- options.execute,
17296
- options.readOnly
17052
+ options.execute
17297
17053
  )
17298
17054
  });
17299
17055
  };
@@ -18250,7 +18006,7 @@ function readBrowserObservation(observation, input) {
18250
18006
  maxNodeBytes: BROWSER_AGENT_MAX_NODE_BYTES
18251
18007
  };
18252
18008
  }
18253
- async function safeInteractionExecution(inputSchema, outputSchema, raw, context, execute, readOnly) {
18009
+ async function safeInteractionExecution(inputSchema, outputSchema, raw, context, execute) {
18254
18010
  try {
18255
18011
  const value = inputSchema.parse(raw);
18256
18012
  const executed = await execute(value, context);
@@ -18269,12 +18025,11 @@ async function safeInteractionExecution(inputSchema, outputSchema, raw, context,
18269
18025
  if (error instanceof external_exports.ZodError) {
18270
18026
  return interactionErrorResult("invalid_arguments", "Interaction tool arguments are invalid.");
18271
18027
  }
18272
- if (error instanceof OpenGeniApiError && !error.outcomeUnknown && (error.status < 500 || readOnly)) {
18028
+ if (error instanceof OpenGeniApiError && !error.outcomeUnknown && error.status < 500) {
18273
18029
  return interactionErrorResult(
18274
18030
  error.code ?? `http_${error.status}`,
18275
18031
  boundedErrorMessage(error.message),
18276
- error.retryable,
18277
- error.correlationId
18032
+ error.retryable
18278
18033
  );
18279
18034
  }
18280
18035
  throw error;
@@ -18290,8 +18045,8 @@ function browserToolImageContent(data, mimeType) {
18290
18045
  }
18291
18046
  return { type: "image", data: Buffer.from(data).toString("base64"), mimeType };
18292
18047
  }
18293
- function interactionErrorResult(code, message, retryable = false, requestId) {
18294
- const error = { code, message, retryable, ...requestId ? { requestId } : {} };
18048
+ function interactionErrorResult(code, message, retryable = false) {
18049
+ const error = { code, message, retryable };
18295
18050
  return {
18296
18051
  isError: true,
18297
18052
  content: [{ type: "text", text: JSON.stringify({ error }) }],
@@ -18359,21 +18114,21 @@ function extractOpenSuffixFromRunState(state) {
18359
18114
  if (!state || typeof state !== "object") {
18360
18115
  return [];
18361
18116
  }
18362
- const record2 = state;
18117
+ const record = state;
18363
18118
  const fromGenerated = extractOpenSuffixMembers(
18364
- protocolItemsFromGeneratedItems(record2.generatedItems ?? record2._generatedItems)
18119
+ protocolItemsFromGeneratedItems(record.generatedItems ?? record._generatedItems)
18365
18120
  );
18366
18121
  if (fromGenerated.length > 0) {
18367
18122
  return fromGenerated;
18368
18123
  }
18369
- if (Array.isArray(record2.history)) {
18370
- const fromHistory = extractOpenSuffixMembers(record2.history);
18124
+ if (Array.isArray(record.history)) {
18125
+ const fromHistory = extractOpenSuffixMembers(record.history);
18371
18126
  if (fromHistory.length > 0) {
18372
18127
  return fromHistory;
18373
18128
  }
18374
18129
  }
18375
- if (typeof record2.toString === "function") {
18376
- const serialized = record2.toString();
18130
+ if (typeof record.toString === "function") {
18131
+ const serialized = record.toString();
18377
18132
  if (serialized !== "[object Object]") {
18378
18133
  return extractOpenSuffixFromSerializedRunState(serialized);
18379
18134
  }
@@ -18519,13 +18274,6 @@ var CHAT_INCOMPATIBLE_ITEM_TYPES = /* @__PURE__ */ new Set([
18519
18274
  function isChatIncompatibleHostedToolCall(item) {
18520
18275
  return item.type === "hosted_tool_call" && item.name !== "file_search_call";
18521
18276
  }
18522
- function chatSystemContent(content) {
18523
- if (!Array.isArray(content) || !content.every(
18524
- (part) => part !== null && typeof part === "object" && (part.type === "input_text" || part.type === "output_text" || part.type === "text") && typeof part.text === "string"
18525
- ))
18526
- return content;
18527
- return content.map((part) => part.text).join("\n");
18528
- }
18529
18277
  function projectHistoryForProvider(items, providerApi) {
18530
18278
  if (providerApi === "responses") {
18531
18279
  if (!items.some((item) => item.type === "message" && item.role === "developer")) return items;
@@ -18552,12 +18300,9 @@ function projectHistoryForProvider(items, providerApi) {
18552
18300
  }
18553
18301
  let changed = false;
18554
18302
  const projected = items.map((item) => {
18555
- if (item.type === "message" && (item.role === "developer" || item.role === "system")) {
18556
- const content = chatSystemContent(item.content);
18557
- if (item.role === "developer" || content !== item.content) {
18558
- changed = true;
18559
- return { ...item, role: "system", content };
18560
- }
18303
+ if (item.type === "message" && item.role === "developer") {
18304
+ changed = true;
18305
+ return { ...item, role: "system" };
18561
18306
  }
18562
18307
  const resultId = item.type === "function_call_result" ? callId2(item) : null;
18563
18308
  if (CHAT_INCOMPATIBLE_ITEM_TYPES.has(String(item.type ?? "")) || isChatIncompatibleHostedToolCall(item) || isChatIncompatibleCall(item) || resultId !== null && incompatibleCallIds.has(resultId)) {
@@ -18816,10 +18561,10 @@ function totalCoversKnownComponents(total, inputTokens, outputTokens) {
18816
18561
  function rejectInconsistentRequestTotals(requestEntries, rejectedFields) {
18817
18562
  let inconsistent = false;
18818
18563
  for (const [index, entry] of requestEntries.entries()) {
18819
- const record2 = entry;
18820
- const selectedInput = firstPresentEntry(record2, ["inputTokens", "input_tokens"]);
18821
- const selectedOutput = firstPresentEntry(record2, ["outputTokens", "output_tokens"]);
18822
- const selectedTotal = firstPresentEntry(record2, ["totalTokens", "total_tokens"]);
18564
+ const record = entry;
18565
+ const selectedInput = firstPresentEntry(record, ["inputTokens", "input_tokens"]);
18566
+ const selectedOutput = firstPresentEntry(record, ["outputTokens", "output_tokens"]);
18567
+ const selectedTotal = firstPresentEntry(record, ["totalTokens", "total_tokens"]);
18823
18568
  if (!selectedInput || !selectedOutput || !selectedTotal) continue;
18824
18569
  const inputTokens = modelUsageTokenCountOrNull(selectedInput.value);
18825
18570
  const outputTokens = modelUsageTokenCountOrNull(selectedOutput.value);
@@ -18899,10 +18644,10 @@ function detailRecords(details, path, rejectedFields) {
18899
18644
  }
18900
18645
  return { records, complete };
18901
18646
  }
18902
- function firstPresentEntry(record2, keys) {
18647
+ function firstPresentEntry(record, keys) {
18903
18648
  for (const key of keys) {
18904
- if (Object.prototype.hasOwnProperty.call(record2, key) && record2[key] !== void 0) {
18905
- return { key, value: record2[key] };
18649
+ if (Object.prototype.hasOwnProperty.call(record, key) && record[key] !== void 0) {
18650
+ return { key, value: record[key] };
18906
18651
  }
18907
18652
  }
18908
18653
  return null;
@@ -19301,12 +19046,12 @@ function functionToolNamespaceFields(tool2) {
19301
19046
  namespaceDescription = value;
19302
19047
  }
19303
19048
  }
19304
- const record2 = tool2;
19305
- if (!namespace && typeof record2.namespace === "string" && record2.namespace.length > 0) {
19306
- namespace = record2.namespace;
19049
+ const record = tool2;
19050
+ if (!namespace && typeof record.namespace === "string" && record.namespace.length > 0) {
19051
+ namespace = record.namespace;
19307
19052
  }
19308
- if (!namespaceDescription && typeof record2.namespaceDescription === "string" && record2.namespaceDescription.length > 0) {
19309
- namespaceDescription = record2.namespaceDescription;
19053
+ if (!namespaceDescription && typeof record.namespaceDescription === "string" && record.namespaceDescription.length > 0) {
19054
+ namespaceDescription = record.namespaceDescription;
19310
19055
  }
19311
19056
  return {
19312
19057
  ...namespace ? { namespace } : {},
@@ -19317,19 +19062,19 @@ function serializeToolForRemoteCompaction(tool2) {
19317
19062
  if (!tool2 || typeof tool2 !== "object" || typeof tool2.type !== "string") {
19318
19063
  return null;
19319
19064
  }
19320
- const record2 = tool2;
19321
- const name = typeof record2.name === "string" ? record2.name : "";
19065
+ const record = tool2;
19066
+ const name = typeof record.name === "string" ? record.name : "";
19322
19067
  if (tool2.type === "function") {
19323
- const { namespace, namespaceDescription } = functionToolNamespaceFields(record2);
19068
+ const { namespace, namespaceDescription } = functionToolNamespaceFields(record);
19324
19069
  return {
19325
19070
  type: "function",
19326
19071
  name,
19327
- description: typeof record2.description === "string" ? record2.description : "",
19328
- parameters: record2.parameters,
19072
+ description: typeof record.description === "string" ? record.description : "",
19073
+ parameters: record.parameters,
19329
19074
  // Pass through like SDK serializeTool — do not coerce undefined → false
19330
19075
  // (Responses wire would gain an explicit `"strict": false` and bust cache).
19331
- strict: record2.strict,
19332
- ...typeof record2.deferLoading === "boolean" ? { deferLoading: record2.deferLoading } : {},
19076
+ strict: record.strict,
19077
+ ...typeof record.deferLoading === "boolean" ? { deferLoading: record.deferLoading } : {},
19333
19078
  ...namespace ? {
19334
19079
  namespace,
19335
19080
  ...namespaceDescription ? { namespaceDescription } : {}
@@ -19340,7 +19085,7 @@ function serializeToolForRemoteCompaction(tool2) {
19340
19085
  return {
19341
19086
  type: "hosted_tool",
19342
19087
  name,
19343
- providerData: record2.providerData
19088
+ providerData: record.providerData
19344
19089
  };
19345
19090
  }
19346
19091
  if (tool2.type === "apply_patch") {
@@ -19350,11 +19095,11 @@ function serializeToolForRemoteCompaction(tool2) {
19350
19095
  return {
19351
19096
  type: "shell",
19352
19097
  name,
19353
- environment: record2.environment
19098
+ environment: record.environment
19354
19099
  };
19355
19100
  }
19356
19101
  if (tool2.type === "computer") {
19357
- const computer = record2.computer && typeof record2.computer === "object" ? record2.computer : null;
19102
+ const computer = record.computer && typeof record.computer === "object" ? record.computer : null;
19358
19103
  if (computer && typeof computer.environment === "string" && Array.isArray(computer.dimensions) && computer.dimensions.length === 2 && computer.dimensions.every((value) => typeof value === "number")) {
19359
19104
  return {
19360
19105
  type: "computer",
@@ -19423,8 +19168,8 @@ async function requestRemoteCompactionV2(settings, input, options) {
19423
19168
  }
19424
19169
  function isFailedCompactionProviderResponse(response) {
19425
19170
  if (!response || typeof response !== "object") return false;
19426
- const record2 = response;
19427
- return record2.status === "failed" || record2.status === "incomplete" || record2.error !== null && record2.error !== void 0;
19171
+ const record = response;
19172
+ return record.status === "failed" || record.status === "incomplete" || record.error !== null && record.error !== void 0;
19428
19173
  }
19429
19174
  function compactionProviderFailureDiagnostics(error) {
19430
19175
  let current = error;
@@ -19444,44 +19189,44 @@ function compactionProviderFailureDiagnostics(error) {
19444
19189
  for (let depth = 0; depth < 6 && current && typeof current === "object"; depth += 1) {
19445
19190
  if (seen.has(current)) break;
19446
19191
  seen.add(current);
19447
- const record2 = current;
19448
- rejectionReason ??= compactionRejectionReason(record2);
19192
+ const record = current;
19193
+ rejectionReason ??= compactionRejectionReason(record);
19449
19194
  if (!errorName && current instanceof Error) {
19450
19195
  errorName = boundCompactionDiagnosticField(current.name);
19451
19196
  }
19452
- if (param === null && typeof record2.param === "string" && record2.param.length > 0) {
19453
- param = boundCompactionDiagnosticField(record2.param);
19197
+ if (param === null && typeof record.param === "string" && record.param.length > 0) {
19198
+ param = boundCompactionDiagnosticField(record.param);
19454
19199
  }
19455
- if (httpStatus === null && typeof record2.status === "number" && Number.isFinite(record2.status)) {
19456
- httpStatus = record2.status;
19200
+ if (httpStatus === null && typeof record.status === "number" && Number.isFinite(record.status)) {
19201
+ httpStatus = record.status;
19457
19202
  }
19458
- if (responseStatus === null && typeof record2.status === "string") {
19459
- responseStatus = boundCompactionDiagnosticField(record2.status);
19203
+ if (responseStatus === null && typeof record.status === "string") {
19204
+ responseStatus = boundCompactionDiagnosticField(record.status);
19460
19205
  }
19461
- const directResponseStatus = record2.response_status ?? record2.responseStatus;
19206
+ const directResponseStatus = record.response_status ?? record.responseStatus;
19462
19207
  if (responseStatus === null && typeof directResponseStatus === "string") {
19463
19208
  responseStatus = boundCompactionDiagnosticField(directResponseStatus);
19464
19209
  }
19465
- const directResponseId = record2.response_id ?? record2.responseId ?? record2.id;
19210
+ const directResponseId = record.response_id ?? record.responseId ?? record.id;
19466
19211
  if (responseId === null && typeof directResponseId === "string") {
19467
19212
  responseId = boundCompactionDiagnosticField(directResponseId);
19468
19213
  }
19469
- if (code === null && typeof record2.code === "string") {
19470
- code = boundCompactionDiagnosticField(record2.code);
19214
+ if (code === null && typeof record.code === "string") {
19215
+ code = boundCompactionDiagnosticField(record.code);
19471
19216
  }
19472
- if (type === null && typeof record2.type === "string") {
19473
- type = boundCompactionDiagnosticField(record2.type);
19217
+ if (type === null && typeof record.type === "string") {
19218
+ type = boundCompactionDiagnosticField(record.type);
19474
19219
  }
19475
- const directEventType = record2.event_type ?? record2.eventType;
19220
+ const directEventType = record.event_type ?? record.eventType;
19476
19221
  if (eventType === null && typeof directEventType === "string") {
19477
19222
  eventType = boundCompactionDiagnosticField(directEventType);
19478
19223
  }
19479
19224
  if (requestId === null) {
19480
- const directRequestId = record2.request_id ?? record2.requestId ?? record2.requestID ?? record2._request_id;
19225
+ const directRequestId = record.request_id ?? record.requestId ?? record.requestID ?? record._request_id;
19481
19226
  if (typeof directRequestId === "string") {
19482
19227
  requestId = boundCompactionDiagnosticField(directRequestId);
19483
19228
  }
19484
- const headers = record2.headers;
19229
+ const headers = record.headers;
19485
19230
  if (!requestId && headers && typeof headers === "object") {
19486
19231
  const get = headers.get;
19487
19232
  if (typeof get === "function") {
@@ -19492,7 +19237,7 @@ function compactionProviderFailureDiagnostics(error) {
19492
19237
  }
19493
19238
  }
19494
19239
  }
19495
- const nestedError = record2.error;
19240
+ const nestedError = record.error;
19496
19241
  if (nestedError && typeof nestedError === "object" && !seen.has(nestedError)) {
19497
19242
  const nested = nestedError;
19498
19243
  rejectionReason ??= compactionRejectionReason(nested);
@@ -19518,7 +19263,7 @@ function compactionProviderFailureDiagnostics(error) {
19518
19263
  eventType = boundCompactionDiagnosticField(nestedEventType);
19519
19264
  }
19520
19265
  }
19521
- current = record2.cause;
19266
+ current = record.cause;
19522
19267
  }
19523
19268
  return {
19524
19269
  errorName,
@@ -19533,9 +19278,9 @@ function compactionProviderFailureDiagnostics(error) {
19533
19278
  ...rejectionReason ? { rejectionReason } : {}
19534
19279
  };
19535
19280
  }
19536
- function compactionRejectionReason(record2) {
19537
- return typeof record2.message === "string" && record2.message.length <= 1024 && /^Item '[A-Za-z0-9_-]+' of type '[a-z_]+' was provided without its required 'reasoning' item: '[A-Za-z0-9_-]+'\.$/.test(
19538
- record2.message
19281
+ function compactionRejectionReason(record) {
19282
+ return typeof record.message === "string" && record.message.length <= 1024 && /^Item '[A-Za-z0-9_-]+' of type '[a-z_]+' was provided without its required 'reasoning' item: '[A-Za-z0-9_-]+'\.$/.test(
19283
+ record.message
19539
19284
  ) ? "missing_required_reasoning_item" : null;
19540
19285
  }
19541
19286
  var COMPACTION_DIAGNOSTIC_FIELD_MAX_BYTES = 256;
@@ -19558,8 +19303,8 @@ function compactionResponseDiagnostics(response, extractedText = extractResponse
19558
19303
  extractedTextLength: extractedText.length
19559
19304
  };
19560
19305
  }
19561
- const record2 = response;
19562
- const output = Array.isArray(record2.output) ? record2.output : [];
19306
+ const record = response;
19307
+ const output = Array.isArray(record.output) ? record.output : [];
19563
19308
  const outputItems = output.slice(0, 50).map((item) => {
19564
19309
  if (!item || typeof item !== "object") return { type: typeof item };
19565
19310
  const value = item;
@@ -19574,12 +19319,12 @@ function compactionResponseDiagnostics(response, extractedText = extractResponse
19574
19319
  contentPartCount: content.length
19575
19320
  };
19576
19321
  });
19577
- const choices = Array.isArray(record2.choices) ? record2.choices : [];
19322
+ const choices = Array.isArray(record.choices) ? record.choices : [];
19578
19323
  const usage = modelResponseUsageFromResponse(response)?.usage;
19579
- const incomplete = record2.incomplete_details && typeof record2.incomplete_details === "object" ? record2.incomplete_details : null;
19324
+ const incomplete = record.incomplete_details && typeof record.incomplete_details === "object" ? record.incomplete_details : null;
19580
19325
  return {
19581
- responseId: typeof record2.id === "string" ? record2.id : null,
19582
- status: typeof record2.status === "string" ? record2.status : null,
19326
+ responseId: typeof record.id === "string" ? record.id : null,
19327
+ status: typeof record.status === "string" ? record.status : null,
19583
19328
  outputItemCount: output.length,
19584
19329
  outputItems,
19585
19330
  choiceCount: choices.length,
@@ -19708,7 +19453,6 @@ function workspaceEnvironmentInstructions(environment) {
19708
19453
  function coreInstructions(workspaceEnvironment, rig) {
19709
19454
  return [
19710
19455
  "If the session has a goal, you own it: keep working until you call opengeni__goal_complete with concrete evidence or opengeni__goal_pause with a rationale; revise it with opengeni__goal_update; create one with opengeni__goal_set when given a long-running objective. Resume a paused goal with opengeni__goal_resume when the user asks you to continue, regardless of who paused it, or when the blocker you paused for has cleared. A question alone is not such a request: answer it and leave the goal paused.",
19711
- "Goal completion records short ledger proof, not the user-facing deliverable. After goal_complete succeeds, finish the same turn with the requested answer, or a concise summary and retained artifact link. Never use evidence as the final reply. A later child result after completion is context to integrate, not a reason to stay silent or restart the completed goal.",
19712
19456
  'Choose durable storage by purpose, including requests to "remember this" or keep something "for future sessions". Knowledge is retrieval-only information, not standing behavior. Use instruction_policy_get then instruction_policy_save for short always-on workspace rules, such as "Keep replies concise; expand when asked." Use Skills for reusable procedures and context-specific or personal behavioral preferences; make the Skill description state when it applies so the prompt index can guide skill_read. Do not save behavioral preferences as Knowledge by rephrasing them as facts like "the user prefers concise replies". Preserve the intended scope: do not turn a personal preference into a workspace-wide rule; use an authorized personal Skill when appropriate, or explain the unavailable scope. Split mixed requests into a short rule and detailed Skill steps without duplicating them in Knowledge.',
19713
19457
  "Before changing workspace instructions, read the current instruction and exact baseline, preserve unrelated rules, append new rules, and use only a localized exact anchored edit for updates or removals. Agents cannot replace the complete instruction; whole-policy rewrites belong in the manual workspace editor. Do not bypass a destination's Agent learning setting, review, scope, limits, or unavailable tools by saving to another destination. Report the actual destination and receipt: active, pending review, or not saved. Do not promise future behavior from a Knowledge save.",
19714
19458
  "Use knowledge_search and knowledge_get when retained information is relevant. For questions about what the workspace knows, ground the answer in authorized Knowledge and attached sources. Missing internal facts remain unknown; do not infer a person's role or cite unrelated public search results as evidence. Keep any relevant external research clearly separate from workspace records. Default retrieval returns published information. Before retaining or correcting anything, also search view=needs_review for existing pending entries and collections; read those with knowledge_get view=needs_review. Pending means unapproved: you may inspect and improve it, but do not present it as accepted knowledge or activate behavioral guidance from it. Reuse the existing entryId and current version instead of creating another proposal each run. Save durable facts, decisions, requirements, incidents, fixes and outcomes autonomously with knowledge_save only when they help a plausible future task. Do not retain routine approvals, acknowledgments, temporary task instructions, status chatter or raw screenshots merely because they occurred. Before saving, use knowledge_prepare_save when available to fetch the authorized collection map with descriptions and parent IDs plus related published and pending entries; otherwise search both views and browse collections. Skip unchanged duplicates, improve the existing entry when appropriate, and create a new entry only for distinct useful information. Read the current entry before correcting it and preserve uncertainty, conflicting evidence and existing relationships. When a user supplies or confirms a durable fact, use knowledge_retain_message to retain the actual message and cite its returned entryId/revisionId in the finding evidence. Preserve existing source evidence and relationships when correcting an entry; do not replace them with empty arrays merely because the user confirmed a new value. Explicit confirmation can supersede a conflicting pending proposal, but explain that outcome to the user. Preserve uncertainty and exact supporting evidence; the fact label is not a verification claim. Chat attachments retain their original files for the conversation without automatically publishing OCR or source text into Knowledge. Inspect an image visually in the current task; save only a useful supported observation, requirement or incident when warranted. Use knowledge_retain_file purpose=evidence only when a selected finding needs the original as supporting evidence, or purpose=reference when deliberately retaining a reusable source document. Supporting sources remain accessible through evidence links and explicit includeEvidence searches, but do not fill ordinary Knowledge discovery. An upload alone is not a reason to save Knowledge. A source entry contains retained original text; a finding states a useful conclusion and cites the exact source revision. Do not create both when they would simply repeat the same text. Reuse collections for customers, products, systems or subjects across sources, and link one entry to multiple collections instead of copying it. Technical incidents belong with the affected system and should include cause, fix and outcome when known. Reorganize references when useful; do not erase source evidence or revision history. Private tasks author personal Knowledge; shared tasks author workspace Knowledge. Automatic publishes immediately, Review first keeps a pending proposal without pausing your task, and Off prevents authoring while permitting retrieval. Never bypass review by making a new entry, switching tools, or asking for another approval. Reuse the same operationId and exact request after an uncertain save, including recovery. Use task_note_save for temporary coordination in this task tree. Conversation history is separate. Workspace instructions are concise standing rules; Skills are reusable procedures with their own Agent learning settings. Do not save the same content in multiple authorities.",
@@ -20701,10 +20445,6 @@ function buildAgentCapabilitiesFromComposition(settings, skillComposition, optio
20701
20445
  // readiness proof, which reaches bounded same-turn recovery.
20702
20446
  execCommandErrorFunction: (_context, error) => {
20703
20447
  if (isModalTaskExecStartPreDispatchUnavailableError(error)) throw error;
20704
- if (isRoutingMutationOutcomeUnknownError(error)) {
20705
- if (toolCancellation) throw error;
20706
- return renderRoutingMutationOutcomeUnknownToolResult(error);
20707
- }
20708
20448
  const details = error instanceof Error ? error.toString() : String(error);
20709
20449
  return `An error occurred while running the tool. Please try again. Error: ${details}`;
20710
20450
  },
@@ -20933,7 +20673,7 @@ async function prepareAgentTools(settings, tools, options = {}) {
20933
20673
  options = { ...options, sessionAttachedRemoteMcpTargets: identityTargets };
20934
20674
  options.runMcpCredentials?.assertRemoteTargets(
20935
20675
  settings.mcpServers.filter(
20936
- (config) => tools.some((tool2) => tool2.id === config.id) && !config.connectionRef && !localRegistry.has(config.id) && !isFirstPartyMcpServer(settings, config) && !isCodexAppsMcpServer(config)
20676
+ (config) => tools.some((tool2) => tool2.id === config.id) && !localRegistry.has(config.id) && !isFirstPartyMcpServer(settings, config) && !isCodexAppsMcpServer(config)
20937
20677
  )
20938
20678
  );
20939
20679
  const aggregateToolBudget = new McpAggregateToolListBudget();
@@ -21404,7 +21144,7 @@ function selectedSessionRemoteMcpTargets(settings, attachments, tools, localServ
21404
21144
  );
21405
21145
  if (configs.length !== 1) return [];
21406
21146
  const config = configs[0];
21407
- if (config.connectionRef || isFirstPartyMcpServer(settings, config) || isCodexAppsMcpServer(config) || BUILT_IN_MCP_BRIDGE_ADAPTERS.some(
21147
+ if (isFirstPartyMcpServer(settings, config) || isCodexAppsMcpServer(config) || BUILT_IN_MCP_BRIDGE_ADAPTERS.some(
21408
21148
  (adapter) => adapter.matches({
21409
21149
  url: config.url,
21410
21150
  ...config.connectionRef ? { connectionRef: config.connectionRef } : {}
@@ -22393,20 +22133,20 @@ function inspectMcpTransportError(error, seen = /* @__PURE__ */ new WeakSet()) {
22393
22133
  }
22394
22134
  seen.add(current.value);
22395
22135
  inspectedNodes += 1;
22396
- const record2 = current.value;
22136
+ const record = current.value;
22397
22137
  let httpStatusValues;
22398
22138
  let statusValues;
22399
22139
  let code;
22400
22140
  let failureKind;
22401
22141
  let message;
22402
22142
  try {
22403
- const status = record2.status;
22404
- const statusCode = record2.statusCode;
22405
- code = record2.code;
22143
+ const status = record.status;
22144
+ const statusCode = record.statusCode;
22145
+ code = record.code;
22406
22146
  httpStatusValues = [status, statusCode];
22407
22147
  statusValues = [...httpStatusValues, code];
22408
- failureKind = record2.mcpTransportFailureKind;
22409
- message = record2.message;
22148
+ failureKind = record.mcpTransportFailureKind;
22149
+ message = record.message;
22410
22150
  if (current.value instanceof Error && Object.getPrototypeOf(current.value) !== Error.prototype) {
22411
22151
  hasTypedError = true;
22412
22152
  }
@@ -22441,7 +22181,7 @@ function inspectMcpTransportError(error, seen = /* @__PURE__ */ new WeakSet()) {
22441
22181
  for (const key of MCP_TRANSPORT_ERROR_NESTED_KEYS) {
22442
22182
  let nested;
22443
22183
  try {
22444
- nested = record2[key];
22184
+ nested = record[key];
22445
22185
  } catch {
22446
22186
  complete = false;
22447
22187
  continue;
@@ -23592,15 +23332,9 @@ async function runAgentStream(agent, input, settings, overrides = {}) {
23592
23332
  const scope = gate?.beginStream(overrides.signal);
23593
23333
  try {
23594
23334
  if (scope) agent.toolUseBehavior = scope.toolUseBehavior;
23595
- const stream = await withModelCallLifecycle(
23596
- {
23597
- ...overrides.beforeModelRequest ? { beforeModelRequest: overrides.beforeModelRequest } : {},
23598
- ...overrides.onModelResponse ? { onModelResponse: overrides.onModelResponse } : {}
23599
- },
23600
- () => withPreparedCompactionRequest(
23601
- agent,
23602
- () => runAgentStreamInternal(agent, input, settings, overrides, scope)
23603
- )
23335
+ const stream = await withPreparedCompactionRequest(
23336
+ agent,
23337
+ () => runAgentStreamInternal(agent, input, settings, overrides, scope)
23604
23338
  );
23605
23339
  if (scope) {
23606
23340
  const finish = () => scope.endStream(stream.cancelled);
@@ -26543,7 +26277,6 @@ export {
26543
26277
  normalizeVercelGatewayRequestBody,
26544
26278
  modelRequestPolicyForProvider,
26545
26279
  vercelGatewayRoutingFetch,
26546
- beforeModelRequest,
26547
26280
  markModelPreparationFirstSandboxOperation,
26548
26281
  recordModelPreparationMeasurement,
26549
26282
  PROVIDER_QUOTA_EXHAUSTED_CODE,
@@ -26584,7 +26317,6 @@ export {
26584
26317
  wrapAttemptToolDefinitions,
26585
26318
  InputWaitYield,
26586
26319
  withRetainableSessionImageOutputHook,
26587
- ResponsesStreamingTerminalError,
26588
26320
  OpenGeniChatCompletionsModel,
26589
26321
  OpenGeniResponsesModel,
26590
26322
  buildModelInstance,
@@ -26751,4 +26483,4 @@ export {
26751
26483
  runAzureCliLoginHook,
26752
26484
  renderSessionGoalContext2 as renderSessionGoalContext
26753
26485
  };
26754
- //# sourceMappingURL=chunk-PEEYZDLS.js.map
26486
+ //# sourceMappingURL=chunk-22M75RJF.js.map