@opentiny/next-sdk 0.2.5 → 0.2.6-beta.1

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.
@@ -3087,7 +3087,7 @@
3087
3087
  if (hasRequiredUtils$2) return utils$2;
3088
3088
  hasRequiredUtils$2 = 1;
3089
3089
  const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
3090
- const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
3090
+ const isIPv42 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
3091
3091
  function stringArrayToHexStripped(input) {
3092
3092
  let acc = "";
3093
3093
  let code2 = 0;
@@ -3310,7 +3310,7 @@
3310
3310
  }
3311
3311
  if (component.host !== void 0) {
3312
3312
  let host = unescape(component.host);
3313
- if (!isIPv4(host)) {
3313
+ if (!isIPv42(host)) {
3314
3314
  const ipV6res = normalizeIPv6(host);
3315
3315
  if (ipV6res.isIPV6 === true) {
3316
3316
  host = `[${ipV6res.escapedHost}]`;
@@ -3331,7 +3331,7 @@
3331
3331
  recomposeAuthority,
3332
3332
  normalizeComponentEncoding,
3333
3333
  removeDotSegments,
3334
- isIPv4,
3334
+ isIPv4: isIPv42,
3335
3335
  isUUID,
3336
3336
  normalizeIPv6,
3337
3337
  stringArrayToHexStripped
@@ -3552,7 +3552,7 @@
3552
3552
  function requireFastUri() {
3553
3553
  if (hasRequiredFastUri) return fastUri.exports;
3554
3554
  hasRequiredFastUri = 1;
3555
- const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = requireUtils$2();
3555
+ const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4: isIPv42, nonSimpleDomain } = requireUtils$2();
3556
3556
  const { SCHEMES, getSchemeHandler } = requireSchemes();
3557
3557
  function normalize(uri2, options) {
3558
3558
  if (typeof uri2 === "string") {
@@ -3733,7 +3733,7 @@
3733
3733
  parsed.port = matches[5];
3734
3734
  }
3735
3735
  if (parsed.host) {
3736
- const ipv4result = isIPv4(parsed.host);
3736
+ const ipv4result = isIPv42(parsed.host);
3737
3737
  if (ipv4result === false) {
3738
3738
  const ipv6result = normalizeIPv6(parsed.host);
3739
3739
  parsed.host = ipv6result.host.toLowerCase();
@@ -28053,25 +28053,30 @@ Error message: ${getErrorMessage$2(cause)}`,
28053
28053
  }
28054
28054
  function createToolNameMapping({
28055
28055
  tools = [],
28056
- providerToolNames
28056
+ providerToolNames,
28057
+ resolveProviderToolName
28057
28058
  }) {
28059
+ var _a22;
28058
28060
  const customToolNameToProviderToolName = {};
28059
28061
  const providerToolNameToCustomToolName = {};
28060
28062
  for (const tool2 of tools) {
28061
- if (tool2.type === "provider" && tool2.id in providerToolNames) {
28062
- const providerToolName = providerToolNames[tool2.id];
28063
+ if (tool2.type === "provider") {
28064
+ const providerToolName = (_a22 = resolveProviderToolName == null ? void 0 : resolveProviderToolName(tool2)) != null ? _a22 : tool2.id in providerToolNames ? providerToolNames[tool2.id] : void 0;
28065
+ if (providerToolName == null) {
28066
+ continue;
28067
+ }
28063
28068
  customToolNameToProviderToolName[tool2.name] = providerToolName;
28064
28069
  providerToolNameToCustomToolName[providerToolName] = tool2.name;
28065
28070
  }
28066
28071
  }
28067
28072
  return {
28068
28073
  toProviderToolName: (customToolName) => {
28069
- var _a22;
28070
- return (_a22 = customToolNameToProviderToolName[customToolName]) != null ? _a22 : customToolName;
28074
+ var _a32;
28075
+ return (_a32 = customToolNameToProviderToolName[customToolName]) != null ? _a32 : customToolName;
28071
28076
  },
28072
28077
  toCustomToolName: (providerToolName) => {
28073
- var _a22;
28074
- return (_a22 = providerToolNameToCustomToolName[providerToolName]) != null ? _a22 : providerToolName;
28078
+ var _a32;
28079
+ return (_a32 = providerToolNameToCustomToolName[providerToolName]) != null ? _a32 : providerToolName;
28075
28080
  }
28076
28081
  };
28077
28082
  }
@@ -28264,8 +28269,103 @@ Error message: ${getErrorMessage$2(cause)}`,
28264
28269
  }
28265
28270
  return result;
28266
28271
  }
28272
+ function validateDownloadUrl(url2) {
28273
+ let parsed;
28274
+ try {
28275
+ parsed = new URL(url2);
28276
+ } catch (e) {
28277
+ throw new DownloadError({
28278
+ url: url2,
28279
+ message: `Invalid URL: ${url2}`
28280
+ });
28281
+ }
28282
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
28283
+ throw new DownloadError({
28284
+ url: url2,
28285
+ message: `URL scheme must be http or https, got ${parsed.protocol}`
28286
+ });
28287
+ }
28288
+ const hostname2 = parsed.hostname;
28289
+ if (!hostname2) {
28290
+ throw new DownloadError({
28291
+ url: url2,
28292
+ message: `URL must have a hostname`
28293
+ });
28294
+ }
28295
+ if (hostname2 === "localhost" || hostname2.endsWith(".local") || hostname2.endsWith(".localhost")) {
28296
+ throw new DownloadError({
28297
+ url: url2,
28298
+ message: `URL with hostname ${hostname2} is not allowed`
28299
+ });
28300
+ }
28301
+ if (hostname2.startsWith("[") && hostname2.endsWith("]")) {
28302
+ const ipv62 = hostname2.slice(1, -1);
28303
+ if (isPrivateIPv6(ipv62)) {
28304
+ throw new DownloadError({
28305
+ url: url2,
28306
+ message: `URL with IPv6 address ${hostname2} is not allowed`
28307
+ });
28308
+ }
28309
+ return;
28310
+ }
28311
+ if (isIPv4(hostname2)) {
28312
+ if (isPrivateIPv4(hostname2)) {
28313
+ throw new DownloadError({
28314
+ url: url2,
28315
+ message: `URL with IP address ${hostname2} is not allowed`
28316
+ });
28317
+ }
28318
+ return;
28319
+ }
28320
+ }
28321
+ function isIPv4(hostname2) {
28322
+ const parts = hostname2.split(".");
28323
+ if (parts.length !== 4) return false;
28324
+ return parts.every((part) => {
28325
+ const num = Number(part);
28326
+ return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;
28327
+ });
28328
+ }
28329
+ function isPrivateIPv4(ip) {
28330
+ const parts = ip.split(".").map(Number);
28331
+ const [a, b] = parts;
28332
+ if (a === 0) return true;
28333
+ if (a === 10) return true;
28334
+ if (a === 127) return true;
28335
+ if (a === 169 && b === 254) return true;
28336
+ if (a === 172 && b >= 16 && b <= 31) return true;
28337
+ if (a === 192 && b === 168) return true;
28338
+ return false;
28339
+ }
28340
+ function isPrivateIPv6(ip) {
28341
+ const normalized = ip.toLowerCase();
28342
+ if (normalized === "::1") return true;
28343
+ if (normalized === "::") return true;
28344
+ if (normalized.startsWith("::ffff:")) {
28345
+ const mappedPart = normalized.slice(7);
28346
+ if (isIPv4(mappedPart)) {
28347
+ return isPrivateIPv4(mappedPart);
28348
+ }
28349
+ const hexParts = mappedPart.split(":");
28350
+ if (hexParts.length === 2) {
28351
+ const high = parseInt(hexParts[0], 16);
28352
+ const low = parseInt(hexParts[1], 16);
28353
+ if (!isNaN(high) && !isNaN(low)) {
28354
+ const a = high >> 8 & 255;
28355
+ const b = high & 255;
28356
+ const c = low >> 8 & 255;
28357
+ const d = low & 255;
28358
+ return isPrivateIPv4(`${a}.${b}.${c}.${d}`);
28359
+ }
28360
+ }
28361
+ }
28362
+ if (normalized.startsWith("fc") || normalized.startsWith("fd")) return true;
28363
+ if (normalized.startsWith("fe80")) return true;
28364
+ return false;
28365
+ }
28267
28366
  async function downloadBlob(url2, options) {
28268
28367
  var _a22, _b22;
28368
+ validateDownloadUrl(url2);
28269
28369
  try {
28270
28370
  const response = await fetch(url2, {
28271
28371
  signal: options == null ? void 0 : options.abortSignal
@@ -28431,7 +28531,7 @@ Error message: ${getErrorMessage$2(cause)}`,
28431
28531
  );
28432
28532
  return Object.fromEntries(normalizedHeaders.entries());
28433
28533
  }
28434
- var VERSION$7 = "4.0.15";
28534
+ var VERSION$7 = "4.0.19";
28435
28535
  var getOriginalFetch = () => globalThis.fetch;
28436
28536
  var getFromApi = async ({
28437
28537
  url: url2,
@@ -28574,8 +28674,8 @@ Error message: ${getErrorMessage$2(cause)}`,
28574
28674
  "x-m4a": "m4a"
28575
28675
  }[subtype]) != null ? _a22 : subtype;
28576
28676
  }
28577
- var suspectProtoRx$1 = /"__proto__"\s*:/;
28578
- var suspectConstructorRx$1 = /"constructor"\s*:/;
28677
+ var suspectProtoRx$1 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
28678
+ var suspectConstructorRx$1 = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
28579
28679
  function _parse$1(text2) {
28580
28680
  const obj = JSON.parse(text2);
28581
28681
  if (obj === null || typeof obj !== "object") {
@@ -28595,7 +28695,7 @@ Error message: ${getErrorMessage$2(cause)}`,
28595
28695
  if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
28596
28696
  throw new SyntaxError("Object contains forbidden prototype property");
28597
28697
  }
28598
- if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
28698
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
28599
28699
  throw new SyntaxError("Object contains forbidden prototype property");
28600
28700
  }
28601
28701
  for (const key in node) {
@@ -30082,6 +30182,33 @@ Error message: ${getErrorMessage$2(cause)}`,
30082
30182
  function dynamicTool(tool2) {
30083
30183
  return { ...tool2, type: "dynamic" };
30084
30184
  }
30185
+ function createProviderToolFactory({
30186
+ id: id2,
30187
+ inputSchema
30188
+ }) {
30189
+ return ({
30190
+ execute,
30191
+ outputSchema: outputSchema2,
30192
+ needsApproval,
30193
+ toModelOutput,
30194
+ onInputStart,
30195
+ onInputDelta,
30196
+ onInputAvailable,
30197
+ ...args
30198
+ }) => tool({
30199
+ type: "provider",
30200
+ id: id2,
30201
+ args,
30202
+ inputSchema,
30203
+ outputSchema: outputSchema2,
30204
+ execute,
30205
+ needsApproval,
30206
+ toModelOutput,
30207
+ onInputStart,
30208
+ onInputDelta,
30209
+ onInputAvailable
30210
+ });
30211
+ }
30085
30212
  function createProviderToolFactoryWithOutputSchema({
30086
30213
  id: id2,
30087
30214
  inputSchema,
@@ -31552,7 +31679,7 @@ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the toke
31552
31679
  var _a92;
31553
31680
  return (_a92 = indexBrowserExports.getContext().headers) == null ? void 0 : _a92["x-vercel-id"];
31554
31681
  }
31555
- var VERSION$6 = "3.0.55";
31682
+ var VERSION$6 = "3.0.66";
31556
31683
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
31557
31684
  function createGatewayProvider(options = {}) {
31558
31685
  var _a92, _b9;
@@ -33074,6 +33201,19 @@ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the toke
33074
33201
  }
33075
33202
  };
33076
33203
  _a19 = symbol19;
33204
+ function asArray(value) {
33205
+ return value === void 0 ? [] : Array.isArray(value) ? value : [value];
33206
+ }
33207
+ async function notify(options) {
33208
+ for (const callback of asArray(options.callbacks)) {
33209
+ if (callback == null)
33210
+ continue;
33211
+ try {
33212
+ await callback(options.event);
33213
+ } catch (_ignored) {
33214
+ }
33215
+ }
33216
+ }
33077
33217
  function formatWarning({
33078
33218
  warning,
33079
33219
  provider,
@@ -33374,7 +33514,7 @@ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the toke
33374
33514
  }
33375
33515
  return void 0;
33376
33516
  }
33377
- var VERSION$4 = "6.0.99";
33517
+ var VERSION$4 = "6.0.116";
33378
33518
  var download = async ({
33379
33519
  url: url2,
33380
33520
  maxBytes,
@@ -33382,6 +33522,7 @@ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the toke
33382
33522
  }) => {
33383
33523
  var _a21;
33384
33524
  const urlText = url2.toString();
33525
+ validateDownloadUrl(urlText);
33385
33526
  try {
33386
33527
  const response = await fetch(urlText, {
33387
33528
  headers: withUserAgentSuffix$1(
@@ -33482,9 +33623,6 @@ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the toke
33482
33623
  }
33483
33624
  return convertUint8ArrayToBase64$1(content);
33484
33625
  }
33485
- function asArray(value) {
33486
- return value === void 0 ? [] : Array.isArray(value) ? value : [value];
33487
- }
33488
33626
  async function convertToLanguageModelPrompt({
33489
33627
  prompt,
33490
33628
  supportedUrls,
@@ -34490,6 +34628,44 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
34490
34628
  }))
34491
34629
  );
34492
34630
  }
34631
+ function getGlobalTelemetryIntegrations() {
34632
+ var _a21;
34633
+ return (_a21 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a21 : [];
34634
+ }
34635
+ function getGlobalTelemetryIntegration() {
34636
+ const globalIntegrations = getGlobalTelemetryIntegrations();
34637
+ return (integrations) => {
34638
+ const localIntegrations = asArray(integrations);
34639
+ const allIntegrations = [...globalIntegrations, ...localIntegrations];
34640
+ function createTelemetryComposite(getListenerFromIntegration) {
34641
+ const listeners = allIntegrations.map(getListenerFromIntegration).filter(Boolean);
34642
+ return async (event) => {
34643
+ for (const listener of listeners) {
34644
+ try {
34645
+ await listener(event);
34646
+ } catch (_ignored) {
34647
+ }
34648
+ }
34649
+ };
34650
+ }
34651
+ return {
34652
+ onStart: createTelemetryComposite((integration) => integration.onStart),
34653
+ onStepStart: createTelemetryComposite(
34654
+ (integration) => integration.onStepStart
34655
+ ),
34656
+ onToolCallStart: createTelemetryComposite(
34657
+ (integration) => integration.onToolCallStart
34658
+ ),
34659
+ onToolCallFinish: createTelemetryComposite(
34660
+ (integration) => integration.onToolCallFinish
34661
+ ),
34662
+ onStepFinish: createTelemetryComposite(
34663
+ (integration) => integration.onStepFinish
34664
+ ),
34665
+ onFinish: createTelemetryComposite((integration) => integration.onFinish)
34666
+ };
34667
+ };
34668
+ }
34493
34669
  function asLanguageModelUsage(usage) {
34494
34670
  return {
34495
34671
  inputTokens: usage.inputTokens.total,
@@ -34851,10 +35027,7 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
34851
35027
  tracer,
34852
35028
  fn: async (span) => {
34853
35029
  let output;
34854
- try {
34855
- await (onToolCallStart == null ? void 0 : onToolCallStart(baseCallbackEvent));
34856
- } catch (_ignored) {
34857
- }
35030
+ await notify({ event: baseCallbackEvent, callbacks: onToolCallStart });
34858
35031
  const startTime = now();
34859
35032
  try {
34860
35033
  const stream = executeTool({
@@ -34881,15 +35054,15 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
34881
35054
  }
34882
35055
  } catch (error) {
34883
35056
  const durationMs2 = now() - startTime;
34884
- try {
34885
- await (onToolCallFinish == null ? void 0 : onToolCallFinish({
35057
+ await notify({
35058
+ event: {
34886
35059
  ...baseCallbackEvent,
34887
35060
  success: false,
34888
35061
  error,
34889
35062
  durationMs: durationMs2
34890
- }));
34891
- } catch (_ignored) {
34892
- }
35063
+ },
35064
+ callbacks: onToolCallFinish
35065
+ });
34893
35066
  recordErrorOnSpan(span, error);
34894
35067
  return {
34895
35068
  type: "tool-error",
@@ -34902,15 +35075,15 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
34902
35075
  };
34903
35076
  }
34904
35077
  const durationMs = now() - startTime;
34905
- try {
34906
- await (onToolCallFinish == null ? void 0 : onToolCallFinish({
35078
+ await notify({
35079
+ event: {
34907
35080
  ...baseCallbackEvent,
34908
35081
  success: true,
34909
35082
  output,
34910
35083
  durationMs
34911
- }));
34912
- } catch (_ignored) {
34913
- }
35084
+ },
35085
+ callbacks: onToolCallFinish
35086
+ });
34914
35087
  try {
34915
35088
  span.setAttributes(
34916
35089
  await selectTelemetryAttributes({
@@ -36043,6 +36216,7 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
36043
36216
  ...settings
36044
36217
  }) {
36045
36218
  const model = resolveLanguageModel(modelArg);
36219
+ const createGlobalTelemetry = getGlobalTelemetryIntegration();
36046
36220
  const stopConditions = asArray(stopWhen);
36047
36221
  const totalTimeoutMs = getTotalTimeoutMs(timeout);
36048
36222
  const stepTimeoutMs = getStepTimeoutMs(timeout);
@@ -36073,8 +36247,9 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
36073
36247
  prompt,
36074
36248
  messages
36075
36249
  });
36076
- try {
36077
- await (onStart == null ? void 0 : onStart({
36250
+ const globalTelemetry = createGlobalTelemetry(telemetry == null ? void 0 : telemetry.integrations);
36251
+ await notify({
36252
+ event: {
36078
36253
  model: modelInfo,
36079
36254
  system,
36080
36255
  prompt,
@@ -36101,9 +36276,12 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
36101
36276
  functionId: telemetry == null ? void 0 : telemetry.functionId,
36102
36277
  metadata: telemetry == null ? void 0 : telemetry.metadata,
36103
36278
  experimental_context
36104
- }));
36105
- } catch (_ignored) {
36106
- }
36279
+ },
36280
+ callbacks: [
36281
+ onStart,
36282
+ globalTelemetry.onStart
36283
+ ]
36284
+ });
36107
36285
  const tracer = getTracer(telemetry);
36108
36286
  try {
36109
36287
  return await recordSpan({
@@ -36147,8 +36325,14 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
36147
36325
  experimental_context,
36148
36326
  stepNumber: 0,
36149
36327
  model: modelInfo,
36150
- onToolCallStart,
36151
- onToolCallFinish
36328
+ onToolCallStart: [
36329
+ onToolCallStart,
36330
+ globalTelemetry.onToolCallStart
36331
+ ],
36332
+ onToolCallFinish: [
36333
+ onToolCallFinish,
36334
+ globalTelemetry.onToolCallFinish
36335
+ ]
36152
36336
  });
36153
36337
  const toolContent = [];
36154
36338
  for (const output2 of toolOutputs) {
@@ -36157,7 +36341,7 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
36157
36341
  input: output2.input,
36158
36342
  tool: tools == null ? void 0 : tools[output2.toolName],
36159
36343
  output: output2.type === "tool-result" ? output2.output : output2.error,
36160
- errorMode: output2.type === "tool-error" ? "json" : "none"
36344
+ errorMode: output2.type === "tool-error" ? "text" : "none"
36161
36345
  });
36162
36346
  toolContent.push({
36163
36347
  type: "tool-result",
@@ -36253,8 +36437,8 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
36253
36437
  providerOptions,
36254
36438
  prepareStepResult == null ? void 0 : prepareStepResult.providerOptions
36255
36439
  );
36256
- try {
36257
- await (onStepStart == null ? void 0 : onStepStart({
36440
+ await notify({
36441
+ event: {
36258
36442
  stepNumber: steps.length,
36259
36443
  model: stepModelInfo,
36260
36444
  system: stepSystem,
@@ -36273,9 +36457,12 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
36273
36457
  functionId: telemetry == null ? void 0 : telemetry.functionId,
36274
36458
  metadata: telemetry == null ? void 0 : telemetry.metadata,
36275
36459
  experimental_context
36276
- }));
36277
- } catch (_ignored) {
36278
- }
36460
+ },
36461
+ callbacks: [
36462
+ onStepStart,
36463
+ globalTelemetry.onStepStart
36464
+ ]
36465
+ });
36279
36466
  currentModelResponse = await retry(
36280
36467
  () => {
36281
36468
  var _a22;
@@ -36452,8 +36639,14 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
36452
36639
  experimental_context,
36453
36640
  stepNumber: steps.length,
36454
36641
  model: stepModelInfo,
36455
- onToolCallStart,
36456
- onToolCallFinish
36642
+ onToolCallStart: [
36643
+ onToolCallStart,
36644
+ globalTelemetry.onToolCallStart
36645
+ ],
36646
+ onToolCallFinish: [
36647
+ onToolCallFinish,
36648
+ globalTelemetry.onToolCallFinish
36649
+ ]
36457
36650
  })
36458
36651
  );
36459
36652
  }
@@ -36520,7 +36713,10 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
36520
36713
  model: stepModelInfo.modelId
36521
36714
  });
36522
36715
  steps.push(currentStepResult);
36523
- await (onStepFinish == null ? void 0 : onStepFinish(currentStepResult));
36716
+ await notify({
36717
+ event: currentStepResult,
36718
+ callbacks: [onStepFinish, globalTelemetry.onStepFinish]
36719
+ });
36524
36720
  } finally {
36525
36721
  if (stepTimeoutId != null) {
36526
36722
  clearTimeout(stepTimeoutId);
@@ -36572,34 +36768,40 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
36572
36768
  cachedInputTokens: void 0
36573
36769
  }
36574
36770
  );
36575
- await (onFinish == null ? void 0 : onFinish({
36576
- stepNumber: lastStep.stepNumber,
36577
- model: lastStep.model,
36578
- functionId: lastStep.functionId,
36579
- metadata: lastStep.metadata,
36580
- experimental_context: lastStep.experimental_context,
36581
- finishReason: lastStep.finishReason,
36582
- rawFinishReason: lastStep.rawFinishReason,
36583
- usage: lastStep.usage,
36584
- content: lastStep.content,
36585
- text: lastStep.text,
36586
- reasoningText: lastStep.reasoningText,
36587
- reasoning: lastStep.reasoning,
36588
- files: lastStep.files,
36589
- sources: lastStep.sources,
36590
- toolCalls: lastStep.toolCalls,
36591
- staticToolCalls: lastStep.staticToolCalls,
36592
- dynamicToolCalls: lastStep.dynamicToolCalls,
36593
- toolResults: lastStep.toolResults,
36594
- staticToolResults: lastStep.staticToolResults,
36595
- dynamicToolResults: lastStep.dynamicToolResults,
36596
- request: lastStep.request,
36597
- response: lastStep.response,
36598
- warnings: lastStep.warnings,
36599
- providerMetadata: lastStep.providerMetadata,
36600
- steps,
36601
- totalUsage
36602
- }));
36771
+ await notify({
36772
+ event: {
36773
+ stepNumber: lastStep.stepNumber,
36774
+ model: lastStep.model,
36775
+ functionId: lastStep.functionId,
36776
+ metadata: lastStep.metadata,
36777
+ experimental_context: lastStep.experimental_context,
36778
+ finishReason: lastStep.finishReason,
36779
+ rawFinishReason: lastStep.rawFinishReason,
36780
+ usage: lastStep.usage,
36781
+ content: lastStep.content,
36782
+ text: lastStep.text,
36783
+ reasoningText: lastStep.reasoningText,
36784
+ reasoning: lastStep.reasoning,
36785
+ files: lastStep.files,
36786
+ sources: lastStep.sources,
36787
+ toolCalls: lastStep.toolCalls,
36788
+ staticToolCalls: lastStep.staticToolCalls,
36789
+ dynamicToolCalls: lastStep.dynamicToolCalls,
36790
+ toolResults: lastStep.toolResults,
36791
+ staticToolResults: lastStep.staticToolResults,
36792
+ dynamicToolResults: lastStep.dynamicToolResults,
36793
+ request: lastStep.request,
36794
+ response: lastStep.response,
36795
+ warnings: lastStep.warnings,
36796
+ providerMetadata: lastStep.providerMetadata,
36797
+ steps,
36798
+ totalUsage
36799
+ },
36800
+ callbacks: [
36801
+ onFinish,
36802
+ globalTelemetry.onFinish
36803
+ ]
36804
+ });
36603
36805
  let resolvedOutput;
36604
36806
  if (lastStep.finishReason === "stop") {
36605
36807
  const outputSpecification = output != null ? output : text();
@@ -37217,7 +37419,8 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
37217
37419
  state.message.parts.push({
37218
37420
  type: "file",
37219
37421
  mediaType: chunk.mediaType,
37220
- url: chunk.url
37422
+ url: chunk.url,
37423
+ ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}
37221
37424
  });
37222
37425
  write();
37223
37426
  break;
@@ -37342,7 +37545,9 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
37342
37545
  break;
37343
37546
  }
37344
37547
  case "tool-input-error": {
37345
- if (chunk.dynamic) {
37548
+ const existingPart = state.message.parts.filter(isToolUIPart).find((p) => p.toolCallId === chunk.toolCallId);
37549
+ const isDynamic = existingPart != null ? existingPart.type === "dynamic-tool" : !!chunk.dynamic;
37550
+ if (isDynamic) {
37346
37551
  updateDynamicToolPart({
37347
37552
  toolCallId: chunk.toolCallId,
37348
37553
  toolName: chunk.toolName,
@@ -37872,7 +38077,8 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
37872
38077
  file: new DefaultGeneratedFileWithType({
37873
38078
  data: chunk.data,
37874
38079
  mediaType: chunk.mediaType
37875
- })
38080
+ }),
38081
+ ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}
37876
38082
  });
37877
38083
  break;
37878
38084
  }
@@ -38260,6 +38466,8 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
38260
38466
  this.outputSpecification = output;
38261
38467
  this.includeRawChunks = includeRawChunks;
38262
38468
  this.tools = tools;
38469
+ const createGlobalTelemetry = getGlobalTelemetryIntegration();
38470
+ const globalTelemetry = createGlobalTelemetry(telemetry == null ? void 0 : telemetry.integrations);
38263
38471
  let stepFinish;
38264
38472
  let recordedContent = [];
38265
38473
  const recordedResponseMessages = [];
@@ -38361,7 +38569,11 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
38361
38569
  delete activeReasoningContent[part.id];
38362
38570
  }
38363
38571
  if (part.type === "file") {
38364
- recordedContent.push({ type: "file", file: part.file });
38572
+ recordedContent.push({
38573
+ type: "file",
38574
+ file: part.file,
38575
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
38576
+ });
38365
38577
  }
38366
38578
  if (part.type === "source") {
38367
38579
  recordedContent.push(part);
@@ -38407,7 +38619,10 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
38407
38619
  },
38408
38620
  providerMetadata: part.providerMetadata
38409
38621
  });
38410
- await (onStepFinish == null ? void 0 : onStepFinish(currentStepResult));
38622
+ await notify({
38623
+ event: currentStepResult,
38624
+ callbacks: [onStepFinish, globalTelemetry.onStepFinish]
38625
+ });
38411
38626
  logWarnings({
38412
38627
  warnings: recordedWarnings,
38413
38628
  provider: modelInfo.provider,
@@ -38442,34 +38657,40 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
38442
38657
  self2._totalUsage.resolve(totalUsage);
38443
38658
  self2._steps.resolve(recordedSteps);
38444
38659
  const finalStep = recordedSteps[recordedSteps.length - 1];
38445
- await (onFinish == null ? void 0 : onFinish({
38446
- stepNumber: finalStep.stepNumber,
38447
- model: finalStep.model,
38448
- functionId: finalStep.functionId,
38449
- metadata: finalStep.metadata,
38450
- experimental_context: finalStep.experimental_context,
38451
- finishReason: finalStep.finishReason,
38452
- rawFinishReason: finalStep.rawFinishReason,
38453
- totalUsage,
38454
- usage: finalStep.usage,
38455
- content: finalStep.content,
38456
- text: finalStep.text,
38457
- reasoningText: finalStep.reasoningText,
38458
- reasoning: finalStep.reasoning,
38459
- files: finalStep.files,
38460
- sources: finalStep.sources,
38461
- toolCalls: finalStep.toolCalls,
38462
- staticToolCalls: finalStep.staticToolCalls,
38463
- dynamicToolCalls: finalStep.dynamicToolCalls,
38464
- toolResults: finalStep.toolResults,
38465
- staticToolResults: finalStep.staticToolResults,
38466
- dynamicToolResults: finalStep.dynamicToolResults,
38467
- request: finalStep.request,
38468
- response: finalStep.response,
38469
- warnings: finalStep.warnings,
38470
- providerMetadata: finalStep.providerMetadata,
38471
- steps: recordedSteps
38472
- }));
38660
+ await notify({
38661
+ event: {
38662
+ stepNumber: finalStep.stepNumber,
38663
+ model: finalStep.model,
38664
+ functionId: finalStep.functionId,
38665
+ metadata: finalStep.metadata,
38666
+ experimental_context: finalStep.experimental_context,
38667
+ finishReason: finalStep.finishReason,
38668
+ rawFinishReason: finalStep.rawFinishReason,
38669
+ totalUsage,
38670
+ usage: finalStep.usage,
38671
+ content: finalStep.content,
38672
+ text: finalStep.text,
38673
+ reasoningText: finalStep.reasoningText,
38674
+ reasoning: finalStep.reasoning,
38675
+ files: finalStep.files,
38676
+ sources: finalStep.sources,
38677
+ toolCalls: finalStep.toolCalls,
38678
+ staticToolCalls: finalStep.staticToolCalls,
38679
+ dynamicToolCalls: finalStep.dynamicToolCalls,
38680
+ toolResults: finalStep.toolResults,
38681
+ staticToolResults: finalStep.staticToolResults,
38682
+ dynamicToolResults: finalStep.dynamicToolResults,
38683
+ request: finalStep.request,
38684
+ response: finalStep.response,
38685
+ warnings: finalStep.warnings,
38686
+ providerMetadata: finalStep.providerMetadata,
38687
+ steps: recordedSteps
38688
+ },
38689
+ callbacks: [
38690
+ onFinish,
38691
+ globalTelemetry.onFinish
38692
+ ]
38693
+ });
38473
38694
  rootSpan.setAttributes(
38474
38695
  await selectTelemetryAttributes({
38475
38696
  telemetry,
@@ -38597,8 +38818,8 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
38597
38818
  prompt,
38598
38819
  messages
38599
38820
  });
38600
- try {
38601
- await (onStart == null ? void 0 : onStart({
38821
+ await notify({
38822
+ event: {
38602
38823
  model: modelInfo,
38603
38824
  system,
38604
38825
  prompt,
@@ -38624,9 +38845,12 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
38624
38845
  include,
38625
38846
  ...callbackTelemetryProps,
38626
38847
  experimental_context
38627
- }));
38628
- } catch (_ignored) {
38629
- }
38848
+ },
38849
+ callbacks: [
38850
+ onStart,
38851
+ globalTelemetry.onStart
38852
+ ]
38853
+ });
38630
38854
  const initialMessages = initialPrompt.messages;
38631
38855
  const initialResponseMessages = [];
38632
38856
  const { approvedToolApprovals, deniedToolApprovals } = collectToolApprovals({ messages: initialMessages });
@@ -38675,8 +38899,14 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
38675
38899
  experimental_context,
38676
38900
  stepNumber: recordedSteps.length,
38677
38901
  model: modelInfo,
38678
- onToolCallStart,
38679
- onToolCallFinish,
38902
+ onToolCallStart: [
38903
+ onToolCallStart,
38904
+ globalTelemetry.onToolCallStart
38905
+ ],
38906
+ onToolCallFinish: [
38907
+ onToolCallFinish,
38908
+ globalTelemetry.onToolCallFinish
38909
+ ],
38680
38910
  onPreliminaryToolResult: (result2) => {
38681
38911
  toolExecutionStepStreamController == null ? void 0 : toolExecutionStepStreamController.enqueue(result2);
38682
38912
  }
@@ -38713,7 +38943,7 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
38713
38943
  input: output2.input,
38714
38944
  tool: tools == null ? void 0 : tools[output2.toolName],
38715
38945
  output: output2.type === "tool-result" ? output2.output : output2.error,
38716
- errorMode: output2.type === "tool-error" ? "json" : "none"
38946
+ errorMode: output2.type === "tool-error" ? "text" : "none"
38717
38947
  })
38718
38948
  });
38719
38949
  }
@@ -38807,8 +39037,8 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
38807
39037
  providerOptions,
38808
39038
  prepareStepResult == null ? void 0 : prepareStepResult.providerOptions
38809
39039
  );
38810
- try {
38811
- await (onStepStart == null ? void 0 : onStepStart({
39040
+ await notify({
39041
+ event: {
38812
39042
  stepNumber: recordedSteps.length,
38813
39043
  model: stepModelInfo,
38814
39044
  system: stepSystem,
@@ -38826,9 +39056,12 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
38826
39056
  include,
38827
39057
  ...callbackTelemetryProps,
38828
39058
  experimental_context
38829
- }));
38830
- } catch (_ignored) {
38831
- }
39059
+ },
39060
+ callbacks: [
39061
+ onStepStart,
39062
+ globalTelemetry.onStepStart
39063
+ ]
39064
+ });
38832
39065
  const {
38833
39066
  result: { stream: stream2, response, request },
38834
39067
  doStreamSpan,
@@ -38903,8 +39136,14 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
38903
39136
  generateId: generateId2,
38904
39137
  stepNumber: recordedSteps.length,
38905
39138
  model: stepModelInfo,
38906
- onToolCallStart,
38907
- onToolCallFinish
39139
+ onToolCallStart: [
39140
+ onToolCallStart,
39141
+ globalTelemetry.onToolCallStart
39142
+ ],
39143
+ onToolCallFinish: [
39144
+ onToolCallFinish,
39145
+ globalTelemetry.onToolCallFinish
39146
+ ]
38908
39147
  });
38909
39148
  const stepRequest = ((_i = include == null ? void 0 : include.requestBody) != null ? _i : true) ? request != null ? request : {} : { ...request, body: void 0 };
38910
39149
  const stepToolCalls = [];
@@ -39486,7 +39725,8 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
39486
39725
  controller.enqueue({
39487
39726
  type: "file",
39488
39727
  mediaType: part.file.mediaType,
39489
- url: `data:${part.file.mediaType};base64,${part.file.base64}`
39728
+ url: `data:${part.file.mediaType};base64,${part.file.base64}`,
39729
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
39490
39730
  });
39491
39731
  break;
39492
39732
  }
@@ -41808,7 +42048,7 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
41808
42048
  function getOpenAILanguageModelCapabilities(modelId) {
41809
42049
  const supportsFlexProcessing = modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat");
41810
42050
  const supportsPriorityProcessing = modelId.startsWith("gpt-4") || modelId.startsWith("gpt-5-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-nano") && !modelId.startsWith("gpt-5-chat") || modelId.startsWith("o3") || modelId.startsWith("o4-mini");
41811
- const isReasoningModel = modelId.startsWith("o1") || modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("codex-mini") || modelId.startsWith("computer-use-preview") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat");
42051
+ const isReasoningModel = modelId.startsWith("o1") || modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat");
41812
42052
  const supportsNonReasoningParameters = modelId.startsWith("gpt-5.1") || modelId.startsWith("gpt-5.2");
41813
42053
  const systemMessageMode = isReasoningModel ? "developer" : "system";
41814
42054
  return {
@@ -42743,7 +42983,7 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
42743
42983
  for (const toolCallDelta of delta.tool_calls) {
42744
42984
  const index = toolCallDelta.index;
42745
42985
  if (toolCalls[index] == null) {
42746
- if (toolCallDelta.type !== "function") {
42986
+ if (toolCallDelta.type != null && toolCallDelta.type !== "function") {
42747
42987
  throw new InvalidResponseDataError$1({
42748
42988
  data: toolCallDelta,
42749
42989
  message: `Expected 'function' type.`
@@ -43437,6 +43677,7 @@ ${user}:`]
43437
43677
  "chatgpt-image-latest": 10
43438
43678
  };
43439
43679
  var defaultResponseFormatPrefixes = [
43680
+ "chatgpt-image-",
43440
43681
  "gpt-image-1-mini",
43441
43682
  "gpt-image-1.5",
43442
43683
  "gpt-image-1"
@@ -43714,6 +43955,30 @@ ${user}:`]
43714
43955
  var codeInterpreter = (args = {}) => {
43715
43956
  return codeInterpreterToolFactory(args);
43716
43957
  };
43958
+ var customArgsSchema = lazySchema(
43959
+ () => zodSchema(
43960
+ object$2({
43961
+ name: string(),
43962
+ description: string().optional(),
43963
+ format: union([
43964
+ object$2({
43965
+ type: literal("grammar"),
43966
+ syntax: _enum(["regex", "lark"]),
43967
+ definition: string()
43968
+ }),
43969
+ object$2({
43970
+ type: literal("text")
43971
+ })
43972
+ ]).optional()
43973
+ })
43974
+ )
43975
+ );
43976
+ var customInputSchema = lazySchema(() => zodSchema(string()));
43977
+ var customToolFactory = createProviderToolFactory({
43978
+ id: "openai.custom",
43979
+ inputSchema: customInputSchema
43980
+ });
43981
+ var customTool = (args) => customToolFactory(args);
43717
43982
  var comparisonFilterSchema = object$2({
43718
43983
  key: string(),
43719
43984
  type: _enum(["eq", "ne", "gt", "gte", "lt", "lte", "in", "nin"]),
@@ -44066,6 +44331,16 @@ ${user}:`]
44066
44331
  *
44067
44332
  */
44068
44333
  applyPatch,
44334
+ /**
44335
+ * Custom tools let callers constrain model output to a grammar (regex or
44336
+ * Lark syntax). The model returns a `custom_tool_call` output item whose
44337
+ * `input` field is a string matching the specified grammar.
44338
+ *
44339
+ * @param name - The name of the custom tool.
44340
+ * @param description - An optional description of the tool.
44341
+ * @param format - The output format constraint (grammar type, syntax, and definition).
44342
+ */
44343
+ customTool,
44069
44344
  /**
44070
44345
  * The Code Interpreter tool allows models to write and run Python code in a
44071
44346
  * sandboxed environment to solve complex problems in domains like data analysis,
@@ -44106,7 +44381,7 @@ ${user}:`]
44106
44381
  * Local shell is a tool that allows agents to run shell commands locally
44107
44382
  * on a machine you or the user provides.
44108
44383
  *
44109
- * Supported models: `gpt-5-codex` and `codex-mini-latest`
44384
+ * Supported models: `gpt-5-codex`
44110
44385
  */
44111
44386
  localShell,
44112
44387
  /**
@@ -44204,7 +44479,8 @@ ${user}:`]
44204
44479
  hasConversation = false,
44205
44480
  hasLocalShellTool = false,
44206
44481
  hasShellTool = false,
44207
- hasApplyPatchTool = false
44482
+ hasApplyPatchTool = false,
44483
+ customProviderToolNames
44208
44484
  }) {
44209
44485
  var _a10, _b9, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
44210
44486
  const input = [];
@@ -44287,7 +44563,9 @@ ${user}:`]
44287
44563
  for (const part of content) {
44288
44564
  switch (part.type) {
44289
44565
  case "text": {
44290
- const id2 = (_b9 = (_a10 = part.providerOptions) == null ? void 0 : _a10[providerOptionsName]) == null ? void 0 : _b9.itemId;
44566
+ const providerOpts = (_a10 = part.providerOptions) == null ? void 0 : _a10[providerOptionsName];
44567
+ const id2 = providerOpts == null ? void 0 : providerOpts.itemId;
44568
+ const phase = providerOpts == null ? void 0 : providerOpts.phase;
44291
44569
  if (hasConversation && id2 != null) {
44292
44570
  break;
44293
44571
  }
@@ -44298,12 +44576,13 @@ ${user}:`]
44298
44576
  input.push({
44299
44577
  role: "assistant",
44300
44578
  content: [{ type: "output_text", text: part.text }],
44301
- id: id2
44579
+ id: id2,
44580
+ ...phase != null && { phase }
44302
44581
  });
44303
44582
  break;
44304
44583
  }
44305
44584
  case "tool-call": {
44306
- const id2 = (_g = (_d = (_c = part.providerOptions) == null ? void 0 : _c[providerOptionsName]) == null ? void 0 : _d.itemId) != null ? _g : (_f = (_e = part.providerMetadata) == null ? void 0 : _e[providerOptionsName]) == null ? void 0 : _f.itemId;
44585
+ const id2 = (_f = (_c = (_b9 = part.providerOptions) == null ? void 0 : _b9[providerOptionsName]) == null ? void 0 : _c.itemId) != null ? _f : (_e = (_d = part.providerMetadata) == null ? void 0 : _d[providerOptionsName]) == null ? void 0 : _e.itemId;
44307
44586
  if (hasConversation && id2 != null) {
44308
44587
  break;
44309
44588
  }
@@ -44372,6 +44651,16 @@ ${user}:`]
44372
44651
  });
44373
44652
  break;
44374
44653
  }
44654
+ if (customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) {
44655
+ input.push({
44656
+ type: "custom_tool_call",
44657
+ call_id: part.toolCallId,
44658
+ name: resolvedToolName,
44659
+ input: typeof part.input === "string" ? part.input : JSON.stringify(part.input),
44660
+ id: id2
44661
+ });
44662
+ break;
44663
+ }
44375
44664
  input.push({
44376
44665
  type: "function_call",
44377
44666
  call_id: part.toolCallId,
@@ -44414,7 +44703,7 @@ ${user}:`]
44414
44703
  break;
44415
44704
  }
44416
44705
  if (store) {
44417
- const itemId = (_j = (_i = (_h = part.providerOptions) == null ? void 0 : _h[providerOptionsName]) == null ? void 0 : _i.itemId) != null ? _j : part.toolCallId;
44706
+ const itemId = (_i = (_h = (_g = part.providerOptions) == null ? void 0 : _g[providerOptionsName]) == null ? void 0 : _h.itemId) != null ? _i : part.toolCallId;
44418
44707
  input.push({ type: "item_reference", id: itemId });
44419
44708
  } else {
44420
44709
  warnings.push({
@@ -44474,10 +44763,26 @@ ${user}:`]
44474
44763
  }
44475
44764
  }
44476
44765
  } else {
44477
- warnings.push({
44478
- type: "other",
44479
- message: `Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(part)}.`
44480
- });
44766
+ const encryptedContent = providerOptions == null ? void 0 : providerOptions.reasoningEncryptedContent;
44767
+ if (encryptedContent != null) {
44768
+ const summaryParts = [];
44769
+ if (part.text.length > 0) {
44770
+ summaryParts.push({
44771
+ type: "summary_text",
44772
+ text: part.text
44773
+ });
44774
+ }
44775
+ input.push({
44776
+ type: "reasoning",
44777
+ encrypted_content: encryptedContent,
44778
+ summary: summaryParts
44779
+ });
44780
+ } else {
44781
+ warnings.push({
44782
+ type: "other",
44783
+ message: `Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(part)}.`
44784
+ });
44785
+ }
44481
44786
  }
44482
44787
  break;
44483
44788
  }
@@ -44508,7 +44813,7 @@ ${user}:`]
44508
44813
  }
44509
44814
  const output = part.output;
44510
44815
  if (output.type === "execution-denied") {
44511
- const approvalId = (_l = (_k = output.providerOptions) == null ? void 0 : _k.openai) == null ? void 0 : _l.approvalId;
44816
+ const approvalId = (_k = (_j = output.providerOptions) == null ? void 0 : _j.openai) == null ? void 0 : _k.approvalId;
44512
44817
  if (approvalId) {
44513
44818
  continue;
44514
44819
  }
@@ -44560,6 +44865,61 @@ ${user}:`]
44560
44865
  });
44561
44866
  continue;
44562
44867
  }
44868
+ if (customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) {
44869
+ let outputValue;
44870
+ switch (output.type) {
44871
+ case "text":
44872
+ case "error-text":
44873
+ outputValue = output.value;
44874
+ break;
44875
+ case "execution-denied":
44876
+ outputValue = (_l = output.reason) != null ? _l : "Tool execution denied.";
44877
+ break;
44878
+ case "json":
44879
+ case "error-json":
44880
+ outputValue = JSON.stringify(output.value);
44881
+ break;
44882
+ case "content":
44883
+ outputValue = output.value.map((item) => {
44884
+ var _a22;
44885
+ switch (item.type) {
44886
+ case "text":
44887
+ return { type: "input_text", text: item.text };
44888
+ case "image-data":
44889
+ return {
44890
+ type: "input_image",
44891
+ image_url: `data:${item.mediaType};base64,${item.data}`
44892
+ };
44893
+ case "image-url":
44894
+ return {
44895
+ type: "input_image",
44896
+ image_url: item.url
44897
+ };
44898
+ case "file-data":
44899
+ return {
44900
+ type: "input_file",
44901
+ filename: (_a22 = item.filename) != null ? _a22 : "data",
44902
+ file_data: `data:${item.mediaType};base64,${item.data}`
44903
+ };
44904
+ default:
44905
+ warnings.push({
44906
+ type: "other",
44907
+ message: `unsupported custom tool content part type: ${item.type}`
44908
+ });
44909
+ return void 0;
44910
+ }
44911
+ }).filter(isNonNullable);
44912
+ break;
44913
+ default:
44914
+ outputValue = "";
44915
+ }
44916
+ input.push({
44917
+ type: "custom_tool_call_output",
44918
+ call_id: part.toolCallId,
44919
+ output: outputValue
44920
+ });
44921
+ continue;
44922
+ }
44563
44923
  let contentValue;
44564
44924
  switch (output.type) {
44565
44925
  case "text":
@@ -44694,7 +45054,8 @@ ${user}:`]
44694
45054
  item: discriminatedUnion("type", [
44695
45055
  object$2({
44696
45056
  type: literal("message"),
44697
- id: string()
45057
+ id: string(),
45058
+ phase: _enum(["commentary", "final_answer"]).nullish()
44698
45059
  }),
44699
45060
  object$2({
44700
45061
  type: literal("reasoning"),
@@ -44775,6 +45136,13 @@ ${user}:`]
44775
45136
  })
44776
45137
  ])
44777
45138
  }),
45139
+ object$2({
45140
+ type: literal("custom_tool_call"),
45141
+ id: string(),
45142
+ call_id: string(),
45143
+ name: string(),
45144
+ input: string()
45145
+ }),
44778
45146
  object$2({
44779
45147
  type: literal("shell_call"),
44780
45148
  id: string(),
@@ -44811,7 +45179,8 @@ ${user}:`]
44811
45179
  item: discriminatedUnion("type", [
44812
45180
  object$2({
44813
45181
  type: literal("message"),
44814
- id: string()
45182
+ id: string(),
45183
+ phase: _enum(["commentary", "final_answer"]).nullish()
44815
45184
  }),
44816
45185
  object$2({
44817
45186
  type: literal("reasoning"),
@@ -44826,6 +45195,14 @@ ${user}:`]
44826
45195
  arguments: string(),
44827
45196
  status: literal("completed")
44828
45197
  }),
45198
+ object$2({
45199
+ type: literal("custom_tool_call"),
45200
+ id: string(),
45201
+ call_id: string(),
45202
+ name: string(),
45203
+ input: string(),
45204
+ status: literal("completed")
45205
+ }),
44829
45206
  object$2({
44830
45207
  type: literal("code_interpreter_call"),
44831
45208
  id: string(),
@@ -45009,6 +45386,12 @@ ${user}:`]
45009
45386
  output_index: number$1(),
45010
45387
  delta: string()
45011
45388
  }),
45389
+ object$2({
45390
+ type: literal("response.custom_tool_call_input.delta"),
45391
+ item_id: string(),
45392
+ output_index: number$1(),
45393
+ delta: string()
45394
+ }),
45012
45395
  object$2({
45013
45396
  type: literal("response.image_generation_call.partial_image"),
45014
45397
  item_id: string(),
@@ -45123,6 +45506,7 @@ ${user}:`]
45123
45506
  type: literal("message"),
45124
45507
  role: literal("assistant"),
45125
45508
  id: string(),
45509
+ phase: _enum(["commentary", "final_answer"]).nullish(),
45126
45510
  content: array$1(
45127
45511
  object$2({
45128
45512
  type: literal("output_text"),
@@ -45255,6 +45639,13 @@ ${user}:`]
45255
45639
  arguments: string(),
45256
45640
  id: string()
45257
45641
  }),
45642
+ object$2({
45643
+ type: literal("custom_tool_call"),
45644
+ call_id: string(),
45645
+ name: string(),
45646
+ input: string(),
45647
+ id: string()
45648
+ }),
45258
45649
  object$2({
45259
45650
  type: literal("computer_call"),
45260
45651
  id: string(),
@@ -45538,14 +45929,18 @@ ${user}:`]
45538
45929
  );
45539
45930
  async function prepareResponsesTools({
45540
45931
  tools,
45541
- toolChoice
45932
+ toolChoice,
45933
+ toolNameMapping,
45934
+ customProviderToolNames
45542
45935
  }) {
45936
+ var _a10;
45543
45937
  tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
45544
45938
  const toolWarnings = [];
45545
45939
  if (tools == null) {
45546
45940
  return { tools: void 0, toolChoice: void 0, toolWarnings };
45547
45941
  }
45548
45942
  const openaiTools2 = [];
45943
+ const resolvedCustomProviderToolNames = customProviderToolNames != null ? customProviderToolNames : /* @__PURE__ */ new Set();
45549
45944
  for (const tool2 of tools) {
45550
45945
  switch (tool2.type) {
45551
45946
  case "function":
@@ -45687,6 +46082,20 @@ ${user}:`]
45687
46082
  });
45688
46083
  break;
45689
46084
  }
46085
+ case "openai.custom": {
46086
+ const args = await validateTypes$1({
46087
+ value: tool2.args,
46088
+ schema: customArgsSchema
46089
+ });
46090
+ openaiTools2.push({
46091
+ type: "custom",
46092
+ name: args.name,
46093
+ description: args.description,
46094
+ format: args.format
46095
+ });
46096
+ resolvedCustomProviderToolNames.add(args.name);
46097
+ break;
46098
+ }
45690
46099
  }
45691
46100
  break;
45692
46101
  }
@@ -45707,12 +46116,14 @@ ${user}:`]
45707
46116
  case "none":
45708
46117
  case "required":
45709
46118
  return { tools: openaiTools2, toolChoice: type2, toolWarnings };
45710
- case "tool":
46119
+ case "tool": {
46120
+ const resolvedToolName = (_a10 = toolNameMapping == null ? void 0 : toolNameMapping.toProviderToolName(toolChoice.toolName)) != null ? _a10 : toolChoice.toolName;
45711
46121
  return {
45712
46122
  tools: openaiTools2,
45713
- toolChoice: toolChoice.toolName === "code_interpreter" || toolChoice.toolName === "file_search" || toolChoice.toolName === "image_generation" || toolChoice.toolName === "web_search_preview" || toolChoice.toolName === "web_search" || toolChoice.toolName === "mcp" || toolChoice.toolName === "apply_patch" ? { type: toolChoice.toolName } : { type: "function", name: toolChoice.toolName },
46123
+ toolChoice: resolvedToolName === "code_interpreter" || resolvedToolName === "file_search" || resolvedToolName === "image_generation" || resolvedToolName === "web_search_preview" || resolvedToolName === "web_search" || resolvedToolName === "mcp" || resolvedToolName === "apply_patch" ? { type: resolvedToolName } : resolvedCustomProviderToolNames.has(resolvedToolName) ? { type: "custom", name: resolvedToolName } : { type: "function", name: resolvedToolName },
45714
46124
  toolWarnings
45715
46125
  };
46126
+ }
45716
46127
  default: {
45717
46128
  const _exhaustiveCheck = type2;
45718
46129
  throw new UnsupportedFunctionalityError$1({
@@ -45861,7 +46272,19 @@ ${user}:`]
45861
46272
  "openai.web_search_preview": "web_search_preview",
45862
46273
  "openai.mcp": "mcp",
45863
46274
  "openai.apply_patch": "apply_patch"
45864
- }
46275
+ },
46276
+ resolveProviderToolName: (tool2) => tool2.id === "openai.custom" ? tool2.args.name : void 0
46277
+ });
46278
+ const customProviderToolNames = /* @__PURE__ */ new Set();
46279
+ const {
46280
+ tools: openaiTools2,
46281
+ toolChoice: openaiToolChoice,
46282
+ toolWarnings
46283
+ } = await prepareResponsesTools({
46284
+ tools,
46285
+ toolChoice,
46286
+ toolNameMapping,
46287
+ customProviderToolNames
45865
46288
  });
45866
46289
  const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({
45867
46290
  prompt,
@@ -45873,7 +46296,8 @@ ${user}:`]
45873
46296
  hasConversation: (openaiOptions == null ? void 0 : openaiOptions.conversation) != null,
45874
46297
  hasLocalShellTool: hasOpenAITool("openai.local_shell"),
45875
46298
  hasShellTool: hasOpenAITool("openai.shell"),
45876
- hasApplyPatchTool: hasOpenAITool("openai.apply_patch")
46299
+ hasApplyPatchTool: hasOpenAITool("openai.apply_patch"),
46300
+ customProviderToolNames: customProviderToolNames.size > 0 ? customProviderToolNames : void 0
45877
46301
  });
45878
46302
  warnings.push(...inputWarnings);
45879
46303
  const strictJsonSchema = (_d = openaiOptions == null ? void 0 : openaiOptions.strictJsonSchema) != null ? _d : true;
@@ -46006,14 +46430,6 @@ ${user}:`]
46006
46430
  });
46007
46431
  delete baseArgs.service_tier;
46008
46432
  }
46009
- const {
46010
- tools: openaiTools2,
46011
- toolChoice: openaiToolChoice,
46012
- toolWarnings
46013
- } = await prepareResponsesTools({
46014
- tools,
46015
- toolChoice
46016
- });
46017
46433
  const shellToolEnvType = (_i = (_h = (_g = tools == null ? void 0 : tools.find(
46018
46434
  (tool2) => tool2.type === "provider" && tool2.id === "openai.shell"
46019
46435
  )) == null ? void 0 : _g.args) == null ? void 0 : _h.environment) == null ? void 0 : _i.type;
@@ -46174,6 +46590,7 @@ ${user}:`]
46174
46590
  }
46175
46591
  const providerMetadata2 = {
46176
46592
  itemId: part.id,
46593
+ ...part.phase != null && { phase: part.phase },
46177
46594
  ...contentPart.annotations.length > 0 && {
46178
46595
  annotations: contentPart.annotations
46179
46596
  }
@@ -46262,6 +46679,22 @@ ${user}:`]
46262
46679
  });
46263
46680
  break;
46264
46681
  }
46682
+ case "custom_tool_call": {
46683
+ hasFunctionCall = true;
46684
+ const toolName = toolNameMapping.toCustomToolName(part.name);
46685
+ content.push({
46686
+ type: "tool-call",
46687
+ toolCallId: part.call_id,
46688
+ toolName,
46689
+ input: JSON.stringify(part.input),
46690
+ providerMetadata: {
46691
+ [providerOptionsName]: {
46692
+ itemId: part.id
46693
+ }
46694
+ }
46695
+ });
46696
+ break;
46697
+ }
46265
46698
  case "web_search_call": {
46266
46699
  content.push({
46267
46700
  type: "tool-call",
@@ -46488,6 +46921,7 @@ ${user}:`]
46488
46921
  let responseId = null;
46489
46922
  const ongoingToolCalls = {};
46490
46923
  const ongoingAnnotations = [];
46924
+ let activeMessagePhase;
46491
46925
  let hasFunctionCall = false;
46492
46926
  const activeReasoning = {};
46493
46927
  let serviceTier;
@@ -46498,7 +46932,7 @@ ${user}:`]
46498
46932
  controller.enqueue({ type: "stream-start", warnings });
46499
46933
  },
46500
46934
  transform(chunk, controller) {
46501
- var _a10, _b9, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D;
46935
+ var _a10, _b9, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F;
46502
46936
  if (options.includeRawChunks) {
46503
46937
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
46504
46938
  }
@@ -46519,6 +46953,19 @@ ${user}:`]
46519
46953
  id: value.item.call_id,
46520
46954
  toolName: value.item.name
46521
46955
  });
46956
+ } else if (value.item.type === "custom_tool_call") {
46957
+ const toolName = toolNameMapping.toCustomToolName(
46958
+ value.item.name
46959
+ );
46960
+ ongoingToolCalls[value.output_index] = {
46961
+ toolName,
46962
+ toolCallId: value.item.call_id
46963
+ };
46964
+ controller.enqueue({
46965
+ type: "tool-input-start",
46966
+ id: value.item.call_id,
46967
+ toolName
46968
+ });
46522
46969
  } else if (value.item.type === "web_search_call") {
46523
46970
  ongoingToolCalls[value.output_index] = {
46524
46971
  toolName: toolNameMapping.toCustomToolName(
@@ -46639,12 +47086,16 @@ ${user}:`]
46639
47086
  } else if (value.item.type === "shell_call_output") ;
46640
47087
  else if (value.item.type === "message") {
46641
47088
  ongoingAnnotations.splice(0, ongoingAnnotations.length);
47089
+ activeMessagePhase = (_a10 = value.item.phase) != null ? _a10 : void 0;
46642
47090
  controller.enqueue({
46643
47091
  type: "text-start",
46644
47092
  id: value.item.id,
46645
47093
  providerMetadata: {
46646
47094
  [providerOptionsName]: {
46647
- itemId: value.item.id
47095
+ itemId: value.item.id,
47096
+ ...value.item.phase != null && {
47097
+ phase: value.item.phase
47098
+ }
46648
47099
  }
46649
47100
  }
46650
47101
  });
@@ -46659,19 +47110,22 @@ ${user}:`]
46659
47110
  providerMetadata: {
46660
47111
  [providerOptionsName]: {
46661
47112
  itemId: value.item.id,
46662
- reasoningEncryptedContent: (_a10 = value.item.encrypted_content) != null ? _a10 : null
47113
+ reasoningEncryptedContent: (_b9 = value.item.encrypted_content) != null ? _b9 : null
46663
47114
  }
46664
47115
  }
46665
47116
  });
46666
47117
  }
46667
47118
  } else if (isResponseOutputItemDoneChunk(value)) {
46668
47119
  if (value.item.type === "message") {
47120
+ const phase = (_c = value.item.phase) != null ? _c : activeMessagePhase;
47121
+ activeMessagePhase = void 0;
46669
47122
  controller.enqueue({
46670
47123
  type: "text-end",
46671
47124
  id: value.item.id,
46672
47125
  providerMetadata: {
46673
47126
  [providerOptionsName]: {
46674
47127
  itemId: value.item.id,
47128
+ ...phase != null && { phase },
46675
47129
  ...ongoingAnnotations.length > 0 && {
46676
47130
  annotations: ongoingAnnotations
46677
47131
  }
@@ -46696,6 +47150,27 @@ ${user}:`]
46696
47150
  }
46697
47151
  }
46698
47152
  });
47153
+ } else if (value.item.type === "custom_tool_call") {
47154
+ ongoingToolCalls[value.output_index] = void 0;
47155
+ hasFunctionCall = true;
47156
+ const toolName = toolNameMapping.toCustomToolName(
47157
+ value.item.name
47158
+ );
47159
+ controller.enqueue({
47160
+ type: "tool-input-end",
47161
+ id: value.item.call_id
47162
+ });
47163
+ controller.enqueue({
47164
+ type: "tool-call",
47165
+ toolCallId: value.item.call_id,
47166
+ toolName,
47167
+ input: JSON.stringify(value.item.input),
47168
+ providerMetadata: {
47169
+ [providerOptionsName]: {
47170
+ itemId: value.item.id
47171
+ }
47172
+ }
47173
+ });
46699
47174
  } else if (value.item.type === "web_search_call") {
46700
47175
  ongoingToolCalls[value.output_index] = void 0;
46701
47176
  controller.enqueue({
@@ -46736,13 +47211,13 @@ ${user}:`]
46736
47211
  toolName: toolNameMapping.toCustomToolName("file_search"),
46737
47212
  result: {
46738
47213
  queries: value.item.queries,
46739
- results: (_c = (_b9 = value.item.results) == null ? void 0 : _b9.map((result) => ({
47214
+ results: (_e = (_d = value.item.results) == null ? void 0 : _d.map((result) => ({
46740
47215
  attributes: result.attributes,
46741
47216
  fileId: result.file_id,
46742
47217
  filename: result.filename,
46743
47218
  score: result.score,
46744
47219
  text: result.text
46745
- }))) != null ? _c : null
47220
+ }))) != null ? _e : null
46746
47221
  }
46747
47222
  });
46748
47223
  } else if (value.item.type === "code_interpreter_call") {
@@ -46766,10 +47241,10 @@ ${user}:`]
46766
47241
  });
46767
47242
  } else if (value.item.type === "mcp_call") {
46768
47243
  ongoingToolCalls[value.output_index] = void 0;
46769
- const approvalRequestId = (_d = value.item.approval_request_id) != null ? _d : void 0;
46770
- const aliasedToolCallId = approvalRequestId != null ? (_f = (_e = approvalRequestIdToDummyToolCallIdFromStream.get(
47244
+ const approvalRequestId = (_f = value.item.approval_request_id) != null ? _f : void 0;
47245
+ const aliasedToolCallId = approvalRequestId != null ? (_h = (_g = approvalRequestIdToDummyToolCallIdFromStream.get(
46771
47246
  approvalRequestId
46772
- )) != null ? _e : approvalRequestIdToDummyToolCallIdFromPrompt[approvalRequestId]) != null ? _f : value.item.id : value.item.id;
47247
+ )) != null ? _g : approvalRequestIdToDummyToolCallIdFromPrompt[approvalRequestId]) != null ? _h : value.item.id : value.item.id;
46773
47248
  const toolName = `mcp.${value.item.name}`;
46774
47249
  controller.enqueue({
46775
47250
  type: "tool-call",
@@ -46839,8 +47314,8 @@ ${user}:`]
46839
47314
  ongoingToolCalls[value.output_index] = void 0;
46840
47315
  } else if (value.item.type === "mcp_approval_request") {
46841
47316
  ongoingToolCalls[value.output_index] = void 0;
46842
- const dummyToolCallId = (_i = (_h = (_g = self2.config).generateId) == null ? void 0 : _h.call(_g)) != null ? _i : generateId$1();
46843
- const approvalRequestId = (_j = value.item.approval_request_id) != null ? _j : value.item.id;
47317
+ const dummyToolCallId = (_k = (_j = (_i = self2.config).generateId) == null ? void 0 : _j.call(_i)) != null ? _k : generateId$1();
47318
+ const approvalRequestId = (_l = value.item.approval_request_id) != null ? _l : value.item.id;
46844
47319
  approvalRequestIdToDummyToolCallIdFromStream.set(
46845
47320
  approvalRequestId,
46846
47321
  dummyToolCallId
@@ -46929,7 +47404,7 @@ ${user}:`]
46929
47404
  providerMetadata: {
46930
47405
  [providerOptionsName]: {
46931
47406
  itemId: value.item.id,
46932
- reasoningEncryptedContent: (_k = value.item.encrypted_content) != null ? _k : null
47407
+ reasoningEncryptedContent: (_m = value.item.encrypted_content) != null ? _m : null
46933
47408
  }
46934
47409
  }
46935
47410
  });
@@ -46945,6 +47420,15 @@ ${user}:`]
46945
47420
  delta: value.delta
46946
47421
  });
46947
47422
  }
47423
+ } else if (isResponseCustomToolCallInputDeltaChunk(value)) {
47424
+ const toolCall = ongoingToolCalls[value.output_index];
47425
+ if (toolCall != null) {
47426
+ controller.enqueue({
47427
+ type: "tool-input-delta",
47428
+ id: toolCall.toolCallId,
47429
+ delta: value.delta
47430
+ });
47431
+ }
46948
47432
  } else if (isResponseApplyPatchCallOperationDiffDeltaChunk(value)) {
46949
47433
  const toolCall = ongoingToolCalls[value.output_index];
46950
47434
  if (toolCall == null ? void 0 : toolCall.applyPatch) {
@@ -47033,7 +47517,7 @@ ${user}:`]
47033
47517
  id: value.item_id,
47034
47518
  delta: value.delta
47035
47519
  });
47036
- if (((_m = (_l = options.providerOptions) == null ? void 0 : _l[providerOptionsName]) == null ? void 0 : _m.logprobs) && value.logprobs) {
47520
+ if (((_o = (_n = options.providerOptions) == null ? void 0 : _n[providerOptionsName]) == null ? void 0 : _o.logprobs) && value.logprobs) {
47037
47521
  logprobs.push(value.logprobs);
47038
47522
  }
47039
47523
  } else if (value.type === "response.reasoning_summary_part.added") {
@@ -47062,7 +47546,7 @@ ${user}:`]
47062
47546
  providerMetadata: {
47063
47547
  [providerOptionsName]: {
47064
47548
  itemId: value.item_id,
47065
- reasoningEncryptedContent: (_o = (_n = activeReasoning[value.item_id]) == null ? void 0 : _n.encryptedContent) != null ? _o : null
47549
+ reasoningEncryptedContent: (_q = (_p = activeReasoning[value.item_id]) == null ? void 0 : _p.encryptedContent) != null ? _q : null
47066
47550
  }
47067
47551
  }
47068
47552
  });
@@ -47096,10 +47580,10 @@ ${user}:`]
47096
47580
  } else if (isResponseFinishedChunk(value)) {
47097
47581
  finishReason = {
47098
47582
  unified: mapOpenAIResponseFinishReason({
47099
- finishReason: (_p = value.response.incomplete_details) == null ? void 0 : _p.reason,
47583
+ finishReason: (_r = value.response.incomplete_details) == null ? void 0 : _r.reason,
47100
47584
  hasFunctionCall
47101
47585
  }),
47102
- raw: (_r = (_q = value.response.incomplete_details) == null ? void 0 : _q.reason) != null ? _r : void 0
47586
+ raw: (_t = (_s = value.response.incomplete_details) == null ? void 0 : _s.reason) != null ? _t : void 0
47103
47587
  };
47104
47588
  usage = value.response.usage;
47105
47589
  if (typeof value.response.service_tier === "string") {
@@ -47111,7 +47595,7 @@ ${user}:`]
47111
47595
  controller.enqueue({
47112
47596
  type: "source",
47113
47597
  sourceType: "url",
47114
- id: (_u = (_t = (_s = self2.config).generateId) == null ? void 0 : _t.call(_s)) != null ? _u : generateId$1(),
47598
+ id: (_w = (_v = (_u = self2.config).generateId) == null ? void 0 : _v.call(_u)) != null ? _w : generateId$1(),
47115
47599
  url: value.annotation.url,
47116
47600
  title: value.annotation.title
47117
47601
  });
@@ -47119,7 +47603,7 @@ ${user}:`]
47119
47603
  controller.enqueue({
47120
47604
  type: "source",
47121
47605
  sourceType: "document",
47122
- id: (_x = (_w = (_v = self2.config).generateId) == null ? void 0 : _w.call(_v)) != null ? _x : generateId$1(),
47606
+ id: (_z = (_y = (_x = self2.config).generateId) == null ? void 0 : _y.call(_x)) != null ? _z : generateId$1(),
47123
47607
  mediaType: "text/plain",
47124
47608
  title: value.annotation.filename,
47125
47609
  filename: value.annotation.filename,
@@ -47135,7 +47619,7 @@ ${user}:`]
47135
47619
  controller.enqueue({
47136
47620
  type: "source",
47137
47621
  sourceType: "document",
47138
- id: (_A = (_z = (_y = self2.config).generateId) == null ? void 0 : _z.call(_y)) != null ? _A : generateId$1(),
47622
+ id: (_C = (_B = (_A = self2.config).generateId) == null ? void 0 : _B.call(_A)) != null ? _C : generateId$1(),
47139
47623
  mediaType: "text/plain",
47140
47624
  title: value.annotation.filename,
47141
47625
  filename: value.annotation.filename,
@@ -47151,7 +47635,7 @@ ${user}:`]
47151
47635
  controller.enqueue({
47152
47636
  type: "source",
47153
47637
  sourceType: "document",
47154
- id: (_D = (_C = (_B = self2.config).generateId) == null ? void 0 : _C.call(_B)) != null ? _D : generateId$1(),
47638
+ id: (_F = (_E = (_D = self2.config).generateId) == null ? void 0 : _E.call(_D)) != null ? _F : generateId$1(),
47155
47639
  mediaType: "application/octet-stream",
47156
47640
  title: value.annotation.file_id,
47157
47641
  filename: value.annotation.file_id,
@@ -47205,6 +47689,9 @@ ${user}:`]
47205
47689
  function isResponseFunctionCallArgumentsDeltaChunk(chunk) {
47206
47690
  return chunk.type === "response.function_call_arguments.delta";
47207
47691
  }
47692
+ function isResponseCustomToolCallInputDeltaChunk(chunk) {
47693
+ return chunk.type === "response.custom_tool_call_input.delta";
47694
+ }
47208
47695
  function isResponseImageGenerationCallPartialImageChunk(chunk) {
47209
47696
  return chunk.type === "response.image_generation_call.partial_image";
47210
47697
  }
@@ -47586,7 +48073,7 @@ ${user}:`]
47586
48073
  };
47587
48074
  }
47588
48075
  };
47589
- var VERSION$2 = "3.0.33";
48076
+ var VERSION$2 = "3.0.41";
47590
48077
  function createOpenAI(options = {}) {
47591
48078
  var _a10, _b9;
47592
48079
  const baseURL = (_a10 = withoutTrailingSlash$1(
@@ -49406,9 +49893,13 @@ Error message: ${getErrorMessage(cause)}`,
49406
49893
  if (toolEntries.length === 0) {
49407
49894
  return "";
49408
49895
  }
49409
- let prompt = "\n\n# 工具调用\n\n";
49410
- prompt += "你可以根据需要调用以下工具:\n\n";
49411
- prompt += "<tools>\n";
49896
+ let prompt = `
49897
+ # 工具调用
49898
+
49899
+ 你可以根据需要调用以下工具:
49900
+
49901
+ <tools>
49902
+ `;
49412
49903
  toolEntries.forEach(([toolName, tool2]) => {
49413
49904
  const toolInfo = tool2;
49414
49905
  const description2 = toolInfo.description || "无描述";
@@ -49421,23 +49912,36 @@ Error message: ${getErrorMessage(cause)}`,
49421
49912
  prompt += `${JSON.stringify(toolJson, null, 2)}
49422
49913
  `;
49423
49914
  });
49424
- prompt += "</tools>\n\n";
49425
- prompt += "## 工具调用格式\n\n";
49426
- prompt += "要调用工具,请使用以下 XML 格式:\n";
49427
- prompt += "Thought: [你的思考过程]\n";
49428
- prompt += '<tool_call>{"name": "toolName", "arguments": {"arg1": "value1"}}</tool_call>\n\n';
49429
- prompt += "工具执行后,你将收到 <tool_response> 格式的结果。你可以继续思考或调用其他工具。\n\n";
49430
- prompt += "## 使用示例\n\n";
49431
- prompt += '如果用户要求"获取今天的日期",你可以这样调用工具:\n';
49432
- prompt += "Thought: 用户想要获取今天的日期,我需要调用日期相关的工具。\n";
49433
- prompt += '<tool_call>{"name": "get-today", "arguments": {}}</tool_call>\n\n';
49434
- prompt += "然后等待工具返回结果(Observation),再根据结果给出最终答案。\n\n";
49435
- prompt += "## 任务完成\n\n";
49436
- prompt += "当任务完成或无法继续时,直接给出最终答案即可。\n\n";
49437
- prompt += "**重要提示**:\n";
49438
- prompt += "- 必须严格按照 XML 格式调用工具\n";
49439
- prompt += "- arguments 必须是有效的 JSON 格式\n";
49440
- prompt += "- 如果不需要调用工具,直接给出最终答案即可\n";
49915
+ prompt += `
49916
+ </tools>
49917
+
49918
+ ## 工具调用格式
49919
+
49920
+ 要调用工具,请使用以下 XML 格式:
49921
+ Thought: [你的思考过程]
49922
+ <tool_call>
49923
+ {"name": "toolName", "arguments": {"arg1": "value1"}}
49924
+ </tool_call>
49925
+
49926
+ 工具执行后,你将收到 <tool_response> 格式的结果。你可以继续思考或调用其他工具。
49927
+
49928
+ ## 使用示例
49929
+
49930
+ 如果用户要求"获取今天的日期",你可以这样调用工具:
49931
+ Thought: 用户想要获取今天的日期,我需要调用日期相关的工具。
49932
+ <tool_call>{"name": "get-today", "arguments": {}}</tool_call>
49933
+
49934
+ 然后等待工具返回结果(Observation),再根据结果给出最终答案。
49935
+
49936
+ ## 任务完成
49937
+
49938
+ 当任务完成或无法继续时,直接给出最终答案即可。
49939
+
49940
+ **重要提示**:
49941
+ - 必须严格按照 XML 格式调用工具
49942
+ - arguments 必须是有效的 JSON 格式
49943
+ - 如果不需要调用工具,直接给出最终答案即可
49944
+ `;
49441
49945
  return prompt;
49442
49946
  }
49443
49947
  function parseReActAction(text2, availableTools) {
@@ -50044,6 +50548,124 @@ ${observationText}
50044
50548
  return this._chat(streamText, options);
50045
50549
  }
50046
50550
  }
50551
+ const MSG_TOOL_CALL = "next-sdk:tool-call";
50552
+ const MSG_TOOL_RESPONSE = "next-sdk:tool-response";
50553
+ const MSG_PAGE_READY = "next-sdk:page-ready";
50554
+ const activePages = /* @__PURE__ */ new Map();
50555
+ let _navigator = null;
50556
+ function setNavigator(fn) {
50557
+ _navigator = fn;
50558
+ }
50559
+ function buildPageHandler(name16, route, timeout = 3e4) {
50560
+ return (input) => {
50561
+ const callId = randomUUID();
50562
+ return new Promise((resolve2, reject) => {
50563
+ let timer;
50564
+ let readyHandler;
50565
+ const cleanup = () => {
50566
+ clearTimeout(timer);
50567
+ window.removeEventListener("message", responseHandler);
50568
+ if (readyHandler) {
50569
+ window.removeEventListener("message", readyHandler);
50570
+ }
50571
+ };
50572
+ timer = setTimeout(() => {
50573
+ cleanup();
50574
+ reject(new Error(`工具 [${name16}] 调用超时 (${timeout}ms),请检查目标页面是否正确调用了 registerPageTool`));
50575
+ }, timeout);
50576
+ const responseHandler = (event) => {
50577
+ if (event.source === window && event.data?.type === MSG_TOOL_RESPONSE && event.data.callId === callId) {
50578
+ cleanup();
50579
+ event.data.error ? reject(new Error(event.data.error)) : resolve2(event.data.result);
50580
+ }
50581
+ };
50582
+ window.addEventListener("message", responseHandler);
50583
+ const sendCall = () => {
50584
+ window.postMessage({ type: MSG_TOOL_CALL, callId, toolName: name16, route, input }, window.location.origin || "*");
50585
+ };
50586
+ let callSent = false;
50587
+ const sendCallOnce = () => {
50588
+ if (callSent) return;
50589
+ callSent = true;
50590
+ sendCall();
50591
+ };
50592
+ const run = async () => {
50593
+ try {
50594
+ if (activePages.get(route)) {
50595
+ sendCallOnce();
50596
+ return;
50597
+ }
50598
+ readyHandler = (event) => {
50599
+ if (event.source === window && event.data?.type === MSG_PAGE_READY && event.data.route === route) {
50600
+ window.removeEventListener("message", readyHandler);
50601
+ sendCallOnce();
50602
+ }
50603
+ };
50604
+ window.addEventListener("message", readyHandler);
50605
+ if (_navigator) {
50606
+ await _navigator(route);
50607
+ }
50608
+ if (activePages.get(route)) {
50609
+ window.removeEventListener("message", readyHandler);
50610
+ sendCallOnce();
50611
+ }
50612
+ } catch (err) {
50613
+ cleanup();
50614
+ reject(err instanceof Error ? err : new Error(String(err)));
50615
+ }
50616
+ };
50617
+ void run();
50618
+ });
50619
+ };
50620
+ }
50621
+ function withPageTools(server) {
50622
+ return new Proxy(server, {
50623
+ get(target, prop, receiver) {
50624
+ if (prop === "registerTool") {
50625
+ return (name16, config2, handlerOrRoute) => {
50626
+ const rawRegister = target.registerTool.bind(target);
50627
+ if (typeof handlerOrRoute === "function") {
50628
+ return rawRegister(name16, config2, handlerOrRoute);
50629
+ }
50630
+ const { route, timeout } = handlerOrRoute;
50631
+ return rawRegister(name16, config2, buildPageHandler(name16, route, timeout));
50632
+ };
50633
+ }
50634
+ return Reflect.get(target, prop, receiver);
50635
+ }
50636
+ });
50637
+ }
50638
+ function registerPageTool(options) {
50639
+ const { route: routeOption, handlers } = options;
50640
+ const normalizeRoute = (value) => value.replace(/\/+$/, "") || "/";
50641
+ const route = normalizeRoute(routeOption ?? window.location.pathname);
50642
+ const handleMessage = async (event) => {
50643
+ if (event.source !== window || event.data?.type !== MSG_TOOL_CALL || normalizeRoute(String(event.data?.route ?? "")) !== route || !(event.data.toolName in handlers)) {
50644
+ return;
50645
+ }
50646
+ const { callId, toolName, input } = event.data;
50647
+ try {
50648
+ const result = await handlers[toolName](input);
50649
+ window.postMessage({ type: MSG_TOOL_RESPONSE, callId, result }, window.location.origin || "*");
50650
+ } catch (err) {
50651
+ window.postMessage(
50652
+ {
50653
+ type: MSG_TOOL_RESPONSE,
50654
+ callId,
50655
+ error: err instanceof Error ? err.message : String(err)
50656
+ },
50657
+ window.location.origin || "*"
50658
+ );
50659
+ }
50660
+ };
50661
+ activePages.set(route, true);
50662
+ window.addEventListener("message", handleMessage);
50663
+ window.postMessage({ type: MSG_PAGE_READY, route }, window.location.origin || "*");
50664
+ return () => {
50665
+ activePages.delete(route);
50666
+ window.removeEventListener("message", handleMessage);
50667
+ };
50668
+ }
50047
50669
  const MAIN_SKILL_PATH_REG = /^\.\/[^/]+\/SKILL\.md$/;
50048
50670
  const FRONT_MATTER_BLOCK_REG = /^---\s*\n([\s\S]+?)\s*\n---/;
50049
50671
  function parseSkillFrontMatter(content) {
@@ -50056,14 +50678,27 @@ ${observationText}
50056
50678
  const description2 = descMatch?.[1]?.trim();
50057
50679
  return name16 && description2 ? { name: name16, description: description2 } : null;
50058
50680
  }
50681
+ function normalizeSkillModuleKeys(modules) {
50682
+ const result = {};
50683
+ for (const [key, content] of Object.entries(modules)) {
50684
+ const normalizedKey = key.replace(/\\/g, "/");
50685
+ const skillsIndex = normalizedKey.lastIndexOf("skills/");
50686
+ const relativePath = skillsIndex >= 0 ? normalizedKey.slice(skillsIndex + 7) : normalizedKey;
50687
+ const standardPath = relativePath.startsWith("./") ? relativePath : `./${relativePath}`;
50688
+ result[standardPath] = content;
50689
+ }
50690
+ return result;
50691
+ }
50059
50692
  function getMainSkillPaths(modules) {
50060
- return Object.keys(modules).filter((path) => MAIN_SKILL_PATH_REG.test(path));
50693
+ const normalized = normalizeSkillModuleKeys(modules);
50694
+ return Object.keys(normalized).filter((path) => MAIN_SKILL_PATH_REG.test(path));
50061
50695
  }
50062
50696
  function getSkillOverviews(modules) {
50063
- const mainPaths = getMainSkillPaths(modules);
50697
+ const normalized = normalizeSkillModuleKeys(modules);
50698
+ const mainPaths = Object.keys(normalized).filter((path) => MAIN_SKILL_PATH_REG.test(path));
50064
50699
  const list = [];
50065
50700
  for (const path of mainPaths) {
50066
- const content = modules[path];
50701
+ const content = normalized[path];
50067
50702
  if (!content) continue;
50068
50703
  const parsed = parseSkillFrontMatter(content);
50069
50704
  if (!parsed) continue;
@@ -50085,34 +50720,38 @@ ${lines.join("\n")}
50085
50720
  当需要用到某技能时,请使用 get_skill_content 工具获取该技能的完整文档内容。`;
50086
50721
  }
50087
50722
  function getSkillMdPaths(modules) {
50088
- return Object.keys(modules);
50723
+ const normalized = normalizeSkillModuleKeys(modules);
50724
+ return Object.keys(normalized);
50089
50725
  }
50090
50726
  function getSkillMdContent(modules, path) {
50091
- return modules[path];
50727
+ const normalized = normalizeSkillModuleKeys(modules);
50728
+ return normalized[path];
50092
50729
  }
50093
50730
  function getMainSkillPathByName(modules, name16) {
50094
50731
  return getMainSkillPaths(modules).find((p) => p.startsWith(`./${name16}/SKILL.md`));
50095
50732
  }
50733
+ const SKILL_INPUT_SCHEMA = objectType({
50734
+ skillName: stringType().optional().describe("技能名称,与目录名一致,如 calculator"),
50735
+ path: stringType().optional().describe("文档相对路径,如 ./calculator/SKILL.md 或 ./product-guide/reference/xxx.json")
50736
+ });
50096
50737
  function createSkillTools(modules) {
50738
+ const normalizedModules = normalizeSkillModuleKeys(modules);
50097
50739
  const getSkillContent = tool({
50098
- description: "根据技能名称或文档路径获取该技能的完整 Markdown 文档内容。传入 skillName(如 calculator)或 path(如 ./calculator/SKILL.md",
50099
- inputSchema: objectType({
50100
- skillName: stringType().optional().describe("技能名称,与目录名一致,如 calculator"),
50101
- path: stringType().optional().describe("文档相对路径,如 ./calculator/SKILL.md 或 ./product-guide/reference/xxx.md")
50102
- }),
50740
+ description: "根据技能名称或文档路径获取该技能的完整文档内容。传入 skillName(如 calculator)或 path(如 ./calculator/SKILL.md)。支持 .md、.json、.xml 等各类文本格式文件。",
50741
+ inputSchema: SKILL_INPUT_SCHEMA,
50103
50742
  execute: (args) => {
50104
50743
  const { skillName, path: pathArg } = args;
50105
50744
  let content;
50106
50745
  if (pathArg) {
50107
- content = getSkillMdContent(modules, pathArg);
50746
+ content = getSkillMdContent(normalizedModules, pathArg);
50108
50747
  } else if (skillName) {
50109
- const mainPath = getMainSkillPathByName(modules, skillName);
50110
- content = mainPath ? getSkillMdContent(modules, mainPath) : void 0;
50748
+ const mainPath = getMainSkillPathByName(normalizedModules, skillName);
50749
+ content = mainPath ? getSkillMdContent(normalizedModules, mainPath) : void 0;
50111
50750
  }
50112
50751
  if (content === void 0) {
50113
50752
  return { error: "未找到对应技能文档", skillName: skillName ?? pathArg };
50114
50753
  }
50115
- return { content, path: pathArg ?? getMainSkillPathByName(modules, skillName) };
50754
+ return { content, path: pathArg ?? getMainSkillPathByName(normalizedModules, skillName) };
50116
50755
  }
50117
50756
  });
50118
50757
  return {
@@ -50154,6 +50793,9 @@ ${lines.join("\n")}
50154
50793
  exports2.isSSEClientTransport = isSSEClientTransport;
50155
50794
  exports2.isStreamableHTTPClientTransport = isStreamableHTTPClientTransport;
50156
50795
  exports2.parseSkillFrontMatter = parseSkillFrontMatter;
50796
+ exports2.registerPageTool = registerPageTool;
50797
+ exports2.setNavigator = setNavigator;
50798
+ exports2.withPageTools = withPageTools;
50157
50799
  exports2.z = z;
50158
50800
  Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
50159
50801
  }));