@opentiny/next-sdk 0.2.5 → 0.2.6-beta.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.
@@ -3083,7 +3083,7 @@ function requireUtils$2() {
3083
3083
  if (hasRequiredUtils$2) return utils$2;
3084
3084
  hasRequiredUtils$2 = 1;
3085
3085
  const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
3086
- 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);
3086
+ 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);
3087
3087
  function stringArrayToHexStripped(input) {
3088
3088
  let acc = "";
3089
3089
  let code2 = 0;
@@ -3306,7 +3306,7 @@ function requireUtils$2() {
3306
3306
  }
3307
3307
  if (component.host !== void 0) {
3308
3308
  let host = unescape(component.host);
3309
- if (!isIPv4(host)) {
3309
+ if (!isIPv42(host)) {
3310
3310
  const ipV6res = normalizeIPv6(host);
3311
3311
  if (ipV6res.isIPV6 === true) {
3312
3312
  host = `[${ipV6res.escapedHost}]`;
@@ -3327,7 +3327,7 @@ function requireUtils$2() {
3327
3327
  recomposeAuthority,
3328
3328
  normalizeComponentEncoding,
3329
3329
  removeDotSegments,
3330
- isIPv4,
3330
+ isIPv4: isIPv42,
3331
3331
  isUUID,
3332
3332
  normalizeIPv6,
3333
3333
  stringArrayToHexStripped
@@ -3548,7 +3548,7 @@ var hasRequiredFastUri;
3548
3548
  function requireFastUri() {
3549
3549
  if (hasRequiredFastUri) return fastUri.exports;
3550
3550
  hasRequiredFastUri = 1;
3551
- const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = requireUtils$2();
3551
+ const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4: isIPv42, nonSimpleDomain } = requireUtils$2();
3552
3552
  const { SCHEMES, getSchemeHandler } = requireSchemes();
3553
3553
  function normalize(uri2, options) {
3554
3554
  if (typeof uri2 === "string") {
@@ -3729,7 +3729,7 @@ function requireFastUri() {
3729
3729
  parsed.port = matches[5];
3730
3730
  }
3731
3731
  if (parsed.host) {
3732
- const ipv4result = isIPv4(parsed.host);
3732
+ const ipv4result = isIPv42(parsed.host);
3733
3733
  if (ipv4result === false) {
3734
3734
  const ipv6result = normalizeIPv6(parsed.host);
3735
3735
  parsed.host = ipv6result.host.toLowerCase();
@@ -28049,25 +28049,30 @@ function combineHeaders$1(...headers) {
28049
28049
  }
28050
28050
  function createToolNameMapping({
28051
28051
  tools = [],
28052
- providerToolNames
28052
+ providerToolNames,
28053
+ resolveProviderToolName
28053
28054
  }) {
28055
+ var _a22;
28054
28056
  const customToolNameToProviderToolName = {};
28055
28057
  const providerToolNameToCustomToolName = {};
28056
28058
  for (const tool2 of tools) {
28057
- if (tool2.type === "provider" && tool2.id in providerToolNames) {
28058
- const providerToolName = providerToolNames[tool2.id];
28059
+ if (tool2.type === "provider") {
28060
+ const providerToolName = (_a22 = resolveProviderToolName == null ? void 0 : resolveProviderToolName(tool2)) != null ? _a22 : tool2.id in providerToolNames ? providerToolNames[tool2.id] : void 0;
28061
+ if (providerToolName == null) {
28062
+ continue;
28063
+ }
28059
28064
  customToolNameToProviderToolName[tool2.name] = providerToolName;
28060
28065
  providerToolNameToCustomToolName[providerToolName] = tool2.name;
28061
28066
  }
28062
28067
  }
28063
28068
  return {
28064
28069
  toProviderToolName: (customToolName) => {
28065
- var _a22;
28066
- return (_a22 = customToolNameToProviderToolName[customToolName]) != null ? _a22 : customToolName;
28070
+ var _a32;
28071
+ return (_a32 = customToolNameToProviderToolName[customToolName]) != null ? _a32 : customToolName;
28067
28072
  },
28068
28073
  toCustomToolName: (providerToolName) => {
28069
- var _a22;
28070
- return (_a22 = providerToolNameToCustomToolName[providerToolName]) != null ? _a22 : providerToolName;
28074
+ var _a32;
28075
+ return (_a32 = providerToolNameToCustomToolName[providerToolName]) != null ? _a32 : providerToolName;
28071
28076
  }
28072
28077
  };
28073
28078
  }
@@ -28260,8 +28265,103 @@ async function readResponseWithSizeLimit({
28260
28265
  }
28261
28266
  return result;
28262
28267
  }
28268
+ function validateDownloadUrl(url2) {
28269
+ let parsed;
28270
+ try {
28271
+ parsed = new URL(url2);
28272
+ } catch (e) {
28273
+ throw new DownloadError({
28274
+ url: url2,
28275
+ message: `Invalid URL: ${url2}`
28276
+ });
28277
+ }
28278
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
28279
+ throw new DownloadError({
28280
+ url: url2,
28281
+ message: `URL scheme must be http or https, got ${parsed.protocol}`
28282
+ });
28283
+ }
28284
+ const hostname2 = parsed.hostname;
28285
+ if (!hostname2) {
28286
+ throw new DownloadError({
28287
+ url: url2,
28288
+ message: `URL must have a hostname`
28289
+ });
28290
+ }
28291
+ if (hostname2 === "localhost" || hostname2.endsWith(".local") || hostname2.endsWith(".localhost")) {
28292
+ throw new DownloadError({
28293
+ url: url2,
28294
+ message: `URL with hostname ${hostname2} is not allowed`
28295
+ });
28296
+ }
28297
+ if (hostname2.startsWith("[") && hostname2.endsWith("]")) {
28298
+ const ipv62 = hostname2.slice(1, -1);
28299
+ if (isPrivateIPv6(ipv62)) {
28300
+ throw new DownloadError({
28301
+ url: url2,
28302
+ message: `URL with IPv6 address ${hostname2} is not allowed`
28303
+ });
28304
+ }
28305
+ return;
28306
+ }
28307
+ if (isIPv4(hostname2)) {
28308
+ if (isPrivateIPv4(hostname2)) {
28309
+ throw new DownloadError({
28310
+ url: url2,
28311
+ message: `URL with IP address ${hostname2} is not allowed`
28312
+ });
28313
+ }
28314
+ return;
28315
+ }
28316
+ }
28317
+ function isIPv4(hostname2) {
28318
+ const parts = hostname2.split(".");
28319
+ if (parts.length !== 4) return false;
28320
+ return parts.every((part) => {
28321
+ const num = Number(part);
28322
+ return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;
28323
+ });
28324
+ }
28325
+ function isPrivateIPv4(ip) {
28326
+ const parts = ip.split(".").map(Number);
28327
+ const [a, b] = parts;
28328
+ if (a === 0) return true;
28329
+ if (a === 10) return true;
28330
+ if (a === 127) return true;
28331
+ if (a === 169 && b === 254) return true;
28332
+ if (a === 172 && b >= 16 && b <= 31) return true;
28333
+ if (a === 192 && b === 168) return true;
28334
+ return false;
28335
+ }
28336
+ function isPrivateIPv6(ip) {
28337
+ const normalized = ip.toLowerCase();
28338
+ if (normalized === "::1") return true;
28339
+ if (normalized === "::") return true;
28340
+ if (normalized.startsWith("::ffff:")) {
28341
+ const mappedPart = normalized.slice(7);
28342
+ if (isIPv4(mappedPart)) {
28343
+ return isPrivateIPv4(mappedPart);
28344
+ }
28345
+ const hexParts = mappedPart.split(":");
28346
+ if (hexParts.length === 2) {
28347
+ const high = parseInt(hexParts[0], 16);
28348
+ const low = parseInt(hexParts[1], 16);
28349
+ if (!isNaN(high) && !isNaN(low)) {
28350
+ const a = high >> 8 & 255;
28351
+ const b = high & 255;
28352
+ const c = low >> 8 & 255;
28353
+ const d = low & 255;
28354
+ return isPrivateIPv4(`${a}.${b}.${c}.${d}`);
28355
+ }
28356
+ }
28357
+ }
28358
+ if (normalized.startsWith("fc") || normalized.startsWith("fd")) return true;
28359
+ if (normalized.startsWith("fe80")) return true;
28360
+ return false;
28361
+ }
28263
28362
  async function downloadBlob(url2, options) {
28264
28363
  var _a22, _b22;
28364
+ validateDownloadUrl(url2);
28265
28365
  try {
28266
28366
  const response = await fetch(url2, {
28267
28367
  signal: options == null ? void 0 : options.abortSignal
@@ -28427,7 +28527,7 @@ function withUserAgentSuffix$1(headers, ...userAgentSuffixParts) {
28427
28527
  );
28428
28528
  return Object.fromEntries(normalizedHeaders.entries());
28429
28529
  }
28430
- var VERSION$7 = "4.0.15";
28530
+ var VERSION$7 = "4.0.19";
28431
28531
  var getOriginalFetch = () => globalThis.fetch;
28432
28532
  var getFromApi = async ({
28433
28533
  url: url2,
@@ -28570,8 +28670,8 @@ function mediaTypeToExtension(mediaType) {
28570
28670
  "x-m4a": "m4a"
28571
28671
  }[subtype]) != null ? _a22 : subtype;
28572
28672
  }
28573
- var suspectProtoRx$1 = /"__proto__"\s*:/;
28574
- var suspectConstructorRx$1 = /"constructor"\s*:/;
28673
+ var suspectProtoRx$1 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
28674
+ 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*:/;
28575
28675
  function _parse$1(text2) {
28576
28676
  const obj = JSON.parse(text2);
28577
28677
  if (obj === null || typeof obj !== "object") {
@@ -28591,7 +28691,7 @@ function filter$1(obj) {
28591
28691
  if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
28592
28692
  throw new SyntaxError("Object contains forbidden prototype property");
28593
28693
  }
28594
- if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
28694
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
28595
28695
  throw new SyntaxError("Object contains forbidden prototype property");
28596
28696
  }
28597
28697
  for (const key in node) {
@@ -30078,6 +30178,33 @@ function tool(tool2) {
30078
30178
  function dynamicTool(tool2) {
30079
30179
  return { ...tool2, type: "dynamic" };
30080
30180
  }
30181
+ function createProviderToolFactory({
30182
+ id: id2,
30183
+ inputSchema
30184
+ }) {
30185
+ return ({
30186
+ execute,
30187
+ outputSchema: outputSchema2,
30188
+ needsApproval,
30189
+ toModelOutput,
30190
+ onInputStart,
30191
+ onInputDelta,
30192
+ onInputAvailable,
30193
+ ...args
30194
+ }) => tool({
30195
+ type: "provider",
30196
+ id: id2,
30197
+ args,
30198
+ inputSchema,
30199
+ outputSchema: outputSchema2,
30200
+ execute,
30201
+ needsApproval,
30202
+ toModelOutput,
30203
+ onInputStart,
30204
+ onInputDelta,
30205
+ onInputAvailable
30206
+ });
30207
+ }
30081
30208
  function createProviderToolFactoryWithOutputSchema({
30082
30209
  id: id2,
30083
30210
  inputSchema,
@@ -31548,7 +31675,7 @@ async function getVercelRequestId() {
31548
31675
  var _a92;
31549
31676
  return (_a92 = indexBrowserExports.getContext().headers) == null ? void 0 : _a92["x-vercel-id"];
31550
31677
  }
31551
- var VERSION$6 = "3.0.55";
31678
+ var VERSION$6 = "3.0.66";
31552
31679
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
31553
31680
  function createGatewayProvider(options = {}) {
31554
31681
  var _a92, _b9;
@@ -32681,6 +32808,19 @@ var RetryError = class extends AISDKError$1 {
32681
32808
  }
32682
32809
  };
32683
32810
  _a19 = symbol19;
32811
+ function asArray(value) {
32812
+ return value === void 0 ? [] : Array.isArray(value) ? value : [value];
32813
+ }
32814
+ async function notify(options) {
32815
+ for (const callback of asArray(options.callbacks)) {
32816
+ if (callback == null)
32817
+ continue;
32818
+ try {
32819
+ await callback(options.event);
32820
+ } catch (_ignored) {
32821
+ }
32822
+ }
32823
+ }
32684
32824
  function formatWarning({
32685
32825
  warning,
32686
32826
  provider,
@@ -32981,7 +33121,7 @@ function detectMediaType({
32981
33121
  }
32982
33122
  return void 0;
32983
33123
  }
32984
- var VERSION$4 = "6.0.99";
33124
+ var VERSION$4 = "6.0.116";
32985
33125
  var download = async ({
32986
33126
  url: url2,
32987
33127
  maxBytes,
@@ -32989,6 +33129,7 @@ var download = async ({
32989
33129
  }) => {
32990
33130
  var _a21;
32991
33131
  const urlText = url2.toString();
33132
+ validateDownloadUrl(urlText);
32992
33133
  try {
32993
33134
  const response = await fetch(urlText, {
32994
33135
  headers: withUserAgentSuffix$1(
@@ -33089,9 +33230,6 @@ function convertDataContentToBase64String(content) {
33089
33230
  }
33090
33231
  return convertUint8ArrayToBase64$1(content);
33091
33232
  }
33092
- function asArray(value) {
33093
- return value === void 0 ? [] : Array.isArray(value) ? value : [value];
33094
- }
33095
33233
  async function convertToLanguageModelPrompt({
33096
33234
  prompt,
33097
33235
  supportedUrls,
@@ -34097,6 +34235,44 @@ function stringifyForTelemetry(prompt) {
34097
34235
  }))
34098
34236
  );
34099
34237
  }
34238
+ function getGlobalTelemetryIntegrations() {
34239
+ var _a21;
34240
+ return (_a21 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a21 : [];
34241
+ }
34242
+ function getGlobalTelemetryIntegration() {
34243
+ const globalIntegrations = getGlobalTelemetryIntegrations();
34244
+ return (integrations) => {
34245
+ const localIntegrations = asArray(integrations);
34246
+ const allIntegrations = [...globalIntegrations, ...localIntegrations];
34247
+ function createTelemetryComposite(getListenerFromIntegration) {
34248
+ const listeners = allIntegrations.map(getListenerFromIntegration).filter(Boolean);
34249
+ return async (event) => {
34250
+ for (const listener of listeners) {
34251
+ try {
34252
+ await listener(event);
34253
+ } catch (_ignored) {
34254
+ }
34255
+ }
34256
+ };
34257
+ }
34258
+ return {
34259
+ onStart: createTelemetryComposite((integration) => integration.onStart),
34260
+ onStepStart: createTelemetryComposite(
34261
+ (integration) => integration.onStepStart
34262
+ ),
34263
+ onToolCallStart: createTelemetryComposite(
34264
+ (integration) => integration.onToolCallStart
34265
+ ),
34266
+ onToolCallFinish: createTelemetryComposite(
34267
+ (integration) => integration.onToolCallFinish
34268
+ ),
34269
+ onStepFinish: createTelemetryComposite(
34270
+ (integration) => integration.onStepFinish
34271
+ ),
34272
+ onFinish: createTelemetryComposite((integration) => integration.onFinish)
34273
+ };
34274
+ };
34275
+ }
34100
34276
  function asLanguageModelUsage(usage) {
34101
34277
  return {
34102
34278
  inputTokens: usage.inputTokens.total,
@@ -34458,10 +34634,7 @@ async function executeToolCall({
34458
34634
  tracer,
34459
34635
  fn: async (span) => {
34460
34636
  let output;
34461
- try {
34462
- await (onToolCallStart == null ? void 0 : onToolCallStart(baseCallbackEvent));
34463
- } catch (_ignored) {
34464
- }
34637
+ await notify({ event: baseCallbackEvent, callbacks: onToolCallStart });
34465
34638
  const startTime = now();
34466
34639
  try {
34467
34640
  const stream = executeTool({
@@ -34488,15 +34661,15 @@ async function executeToolCall({
34488
34661
  }
34489
34662
  } catch (error) {
34490
34663
  const durationMs2 = now() - startTime;
34491
- try {
34492
- await (onToolCallFinish == null ? void 0 : onToolCallFinish({
34664
+ await notify({
34665
+ event: {
34493
34666
  ...baseCallbackEvent,
34494
34667
  success: false,
34495
34668
  error,
34496
34669
  durationMs: durationMs2
34497
- }));
34498
- } catch (_ignored) {
34499
- }
34670
+ },
34671
+ callbacks: onToolCallFinish
34672
+ });
34500
34673
  recordErrorOnSpan(span, error);
34501
34674
  return {
34502
34675
  type: "tool-error",
@@ -34509,15 +34682,15 @@ async function executeToolCall({
34509
34682
  };
34510
34683
  }
34511
34684
  const durationMs = now() - startTime;
34512
- try {
34513
- await (onToolCallFinish == null ? void 0 : onToolCallFinish({
34685
+ await notify({
34686
+ event: {
34514
34687
  ...baseCallbackEvent,
34515
34688
  success: true,
34516
34689
  output,
34517
34690
  durationMs
34518
- }));
34519
- } catch (_ignored) {
34520
- }
34691
+ },
34692
+ callbacks: onToolCallFinish
34693
+ });
34521
34694
  try {
34522
34695
  span.setAttributes(
34523
34696
  await selectTelemetryAttributes({
@@ -35650,6 +35823,7 @@ async function generateText({
35650
35823
  ...settings
35651
35824
  }) {
35652
35825
  const model = resolveLanguageModel(modelArg);
35826
+ const createGlobalTelemetry = getGlobalTelemetryIntegration();
35653
35827
  const stopConditions = asArray(stopWhen);
35654
35828
  const totalTimeoutMs = getTotalTimeoutMs(timeout);
35655
35829
  const stepTimeoutMs = getStepTimeoutMs(timeout);
@@ -35680,8 +35854,9 @@ async function generateText({
35680
35854
  prompt,
35681
35855
  messages
35682
35856
  });
35683
- try {
35684
- await (onStart == null ? void 0 : onStart({
35857
+ const globalTelemetry = createGlobalTelemetry(telemetry == null ? void 0 : telemetry.integrations);
35858
+ await notify({
35859
+ event: {
35685
35860
  model: modelInfo,
35686
35861
  system,
35687
35862
  prompt,
@@ -35708,9 +35883,12 @@ async function generateText({
35708
35883
  functionId: telemetry == null ? void 0 : telemetry.functionId,
35709
35884
  metadata: telemetry == null ? void 0 : telemetry.metadata,
35710
35885
  experimental_context
35711
- }));
35712
- } catch (_ignored) {
35713
- }
35886
+ },
35887
+ callbacks: [
35888
+ onStart,
35889
+ globalTelemetry.onStart
35890
+ ]
35891
+ });
35714
35892
  const tracer = getTracer(telemetry);
35715
35893
  try {
35716
35894
  return await recordSpan({
@@ -35754,8 +35932,14 @@ async function generateText({
35754
35932
  experimental_context,
35755
35933
  stepNumber: 0,
35756
35934
  model: modelInfo,
35757
- onToolCallStart,
35758
- onToolCallFinish
35935
+ onToolCallStart: [
35936
+ onToolCallStart,
35937
+ globalTelemetry.onToolCallStart
35938
+ ],
35939
+ onToolCallFinish: [
35940
+ onToolCallFinish,
35941
+ globalTelemetry.onToolCallFinish
35942
+ ]
35759
35943
  });
35760
35944
  const toolContent = [];
35761
35945
  for (const output2 of toolOutputs) {
@@ -35764,7 +35948,7 @@ async function generateText({
35764
35948
  input: output2.input,
35765
35949
  tool: tools == null ? void 0 : tools[output2.toolName],
35766
35950
  output: output2.type === "tool-result" ? output2.output : output2.error,
35767
- errorMode: output2.type === "tool-error" ? "json" : "none"
35951
+ errorMode: output2.type === "tool-error" ? "text" : "none"
35768
35952
  });
35769
35953
  toolContent.push({
35770
35954
  type: "tool-result",
@@ -35860,8 +36044,8 @@ async function generateText({
35860
36044
  providerOptions,
35861
36045
  prepareStepResult == null ? void 0 : prepareStepResult.providerOptions
35862
36046
  );
35863
- try {
35864
- await (onStepStart == null ? void 0 : onStepStart({
36047
+ await notify({
36048
+ event: {
35865
36049
  stepNumber: steps.length,
35866
36050
  model: stepModelInfo,
35867
36051
  system: stepSystem,
@@ -35880,9 +36064,12 @@ async function generateText({
35880
36064
  functionId: telemetry == null ? void 0 : telemetry.functionId,
35881
36065
  metadata: telemetry == null ? void 0 : telemetry.metadata,
35882
36066
  experimental_context
35883
- }));
35884
- } catch (_ignored) {
35885
- }
36067
+ },
36068
+ callbacks: [
36069
+ onStepStart,
36070
+ globalTelemetry.onStepStart
36071
+ ]
36072
+ });
35886
36073
  currentModelResponse = await retry(
35887
36074
  () => {
35888
36075
  var _a22;
@@ -36059,8 +36246,14 @@ async function generateText({
36059
36246
  experimental_context,
36060
36247
  stepNumber: steps.length,
36061
36248
  model: stepModelInfo,
36062
- onToolCallStart,
36063
- onToolCallFinish
36249
+ onToolCallStart: [
36250
+ onToolCallStart,
36251
+ globalTelemetry.onToolCallStart
36252
+ ],
36253
+ onToolCallFinish: [
36254
+ onToolCallFinish,
36255
+ globalTelemetry.onToolCallFinish
36256
+ ]
36064
36257
  })
36065
36258
  );
36066
36259
  }
@@ -36127,7 +36320,10 @@ async function generateText({
36127
36320
  model: stepModelInfo.modelId
36128
36321
  });
36129
36322
  steps.push(currentStepResult);
36130
- await (onStepFinish == null ? void 0 : onStepFinish(currentStepResult));
36323
+ await notify({
36324
+ event: currentStepResult,
36325
+ callbacks: [onStepFinish, globalTelemetry.onStepFinish]
36326
+ });
36131
36327
  } finally {
36132
36328
  if (stepTimeoutId != null) {
36133
36329
  clearTimeout(stepTimeoutId);
@@ -36179,34 +36375,40 @@ async function generateText({
36179
36375
  cachedInputTokens: void 0
36180
36376
  }
36181
36377
  );
36182
- await (onFinish == null ? void 0 : onFinish({
36183
- stepNumber: lastStep.stepNumber,
36184
- model: lastStep.model,
36185
- functionId: lastStep.functionId,
36186
- metadata: lastStep.metadata,
36187
- experimental_context: lastStep.experimental_context,
36188
- finishReason: lastStep.finishReason,
36189
- rawFinishReason: lastStep.rawFinishReason,
36190
- usage: lastStep.usage,
36191
- content: lastStep.content,
36192
- text: lastStep.text,
36193
- reasoningText: lastStep.reasoningText,
36194
- reasoning: lastStep.reasoning,
36195
- files: lastStep.files,
36196
- sources: lastStep.sources,
36197
- toolCalls: lastStep.toolCalls,
36198
- staticToolCalls: lastStep.staticToolCalls,
36199
- dynamicToolCalls: lastStep.dynamicToolCalls,
36200
- toolResults: lastStep.toolResults,
36201
- staticToolResults: lastStep.staticToolResults,
36202
- dynamicToolResults: lastStep.dynamicToolResults,
36203
- request: lastStep.request,
36204
- response: lastStep.response,
36205
- warnings: lastStep.warnings,
36206
- providerMetadata: lastStep.providerMetadata,
36207
- steps,
36208
- totalUsage
36209
- }));
36378
+ await notify({
36379
+ event: {
36380
+ stepNumber: lastStep.stepNumber,
36381
+ model: lastStep.model,
36382
+ functionId: lastStep.functionId,
36383
+ metadata: lastStep.metadata,
36384
+ experimental_context: lastStep.experimental_context,
36385
+ finishReason: lastStep.finishReason,
36386
+ rawFinishReason: lastStep.rawFinishReason,
36387
+ usage: lastStep.usage,
36388
+ content: lastStep.content,
36389
+ text: lastStep.text,
36390
+ reasoningText: lastStep.reasoningText,
36391
+ reasoning: lastStep.reasoning,
36392
+ files: lastStep.files,
36393
+ sources: lastStep.sources,
36394
+ toolCalls: lastStep.toolCalls,
36395
+ staticToolCalls: lastStep.staticToolCalls,
36396
+ dynamicToolCalls: lastStep.dynamicToolCalls,
36397
+ toolResults: lastStep.toolResults,
36398
+ staticToolResults: lastStep.staticToolResults,
36399
+ dynamicToolResults: lastStep.dynamicToolResults,
36400
+ request: lastStep.request,
36401
+ response: lastStep.response,
36402
+ warnings: lastStep.warnings,
36403
+ providerMetadata: lastStep.providerMetadata,
36404
+ steps,
36405
+ totalUsage
36406
+ },
36407
+ callbacks: [
36408
+ onFinish,
36409
+ globalTelemetry.onFinish
36410
+ ]
36411
+ });
36210
36412
  let resolvedOutput;
36211
36413
  if (lastStep.finishReason === "stop") {
36212
36414
  const outputSpecification = output != null ? output : text();
@@ -36824,7 +37026,8 @@ function processUIMessageStream({
36824
37026
  state.message.parts.push({
36825
37027
  type: "file",
36826
37028
  mediaType: chunk.mediaType,
36827
- url: chunk.url
37029
+ url: chunk.url,
37030
+ ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}
36828
37031
  });
36829
37032
  write();
36830
37033
  break;
@@ -36949,7 +37152,9 @@ function processUIMessageStream({
36949
37152
  break;
36950
37153
  }
36951
37154
  case "tool-input-error": {
36952
- if (chunk.dynamic) {
37155
+ const existingPart = state.message.parts.filter(isToolUIPart).find((p) => p.toolCallId === chunk.toolCallId);
37156
+ const isDynamic = existingPart != null ? existingPart.type === "dynamic-tool" : !!chunk.dynamic;
37157
+ if (isDynamic) {
36953
37158
  updateDynamicToolPart({
36954
37159
  toolCallId: chunk.toolCallId,
36955
37160
  toolName: chunk.toolName,
@@ -37479,7 +37684,8 @@ function runToolsTransformation({
37479
37684
  file: new DefaultGeneratedFileWithType({
37480
37685
  data: chunk.data,
37481
37686
  mediaType: chunk.mediaType
37482
- })
37687
+ }),
37688
+ ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}
37483
37689
  });
37484
37690
  break;
37485
37691
  }
@@ -37867,6 +38073,8 @@ var DefaultStreamTextResult = class {
37867
38073
  this.outputSpecification = output;
37868
38074
  this.includeRawChunks = includeRawChunks;
37869
38075
  this.tools = tools;
38076
+ const createGlobalTelemetry = getGlobalTelemetryIntegration();
38077
+ const globalTelemetry = createGlobalTelemetry(telemetry == null ? void 0 : telemetry.integrations);
37870
38078
  let stepFinish;
37871
38079
  let recordedContent = [];
37872
38080
  const recordedResponseMessages = [];
@@ -37968,7 +38176,11 @@ var DefaultStreamTextResult = class {
37968
38176
  delete activeReasoningContent[part.id];
37969
38177
  }
37970
38178
  if (part.type === "file") {
37971
- recordedContent.push({ type: "file", file: part.file });
38179
+ recordedContent.push({
38180
+ type: "file",
38181
+ file: part.file,
38182
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
38183
+ });
37972
38184
  }
37973
38185
  if (part.type === "source") {
37974
38186
  recordedContent.push(part);
@@ -38014,7 +38226,10 @@ var DefaultStreamTextResult = class {
38014
38226
  },
38015
38227
  providerMetadata: part.providerMetadata
38016
38228
  });
38017
- await (onStepFinish == null ? void 0 : onStepFinish(currentStepResult));
38229
+ await notify({
38230
+ event: currentStepResult,
38231
+ callbacks: [onStepFinish, globalTelemetry.onStepFinish]
38232
+ });
38018
38233
  logWarnings({
38019
38234
  warnings: recordedWarnings,
38020
38235
  provider: modelInfo.provider,
@@ -38049,34 +38264,40 @@ var DefaultStreamTextResult = class {
38049
38264
  self2._totalUsage.resolve(totalUsage);
38050
38265
  self2._steps.resolve(recordedSteps);
38051
38266
  const finalStep = recordedSteps[recordedSteps.length - 1];
38052
- await (onFinish == null ? void 0 : onFinish({
38053
- stepNumber: finalStep.stepNumber,
38054
- model: finalStep.model,
38055
- functionId: finalStep.functionId,
38056
- metadata: finalStep.metadata,
38057
- experimental_context: finalStep.experimental_context,
38058
- finishReason: finalStep.finishReason,
38059
- rawFinishReason: finalStep.rawFinishReason,
38060
- totalUsage,
38061
- usage: finalStep.usage,
38062
- content: finalStep.content,
38063
- text: finalStep.text,
38064
- reasoningText: finalStep.reasoningText,
38065
- reasoning: finalStep.reasoning,
38066
- files: finalStep.files,
38067
- sources: finalStep.sources,
38068
- toolCalls: finalStep.toolCalls,
38069
- staticToolCalls: finalStep.staticToolCalls,
38070
- dynamicToolCalls: finalStep.dynamicToolCalls,
38071
- toolResults: finalStep.toolResults,
38072
- staticToolResults: finalStep.staticToolResults,
38073
- dynamicToolResults: finalStep.dynamicToolResults,
38074
- request: finalStep.request,
38075
- response: finalStep.response,
38076
- warnings: finalStep.warnings,
38077
- providerMetadata: finalStep.providerMetadata,
38078
- steps: recordedSteps
38079
- }));
38267
+ await notify({
38268
+ event: {
38269
+ stepNumber: finalStep.stepNumber,
38270
+ model: finalStep.model,
38271
+ functionId: finalStep.functionId,
38272
+ metadata: finalStep.metadata,
38273
+ experimental_context: finalStep.experimental_context,
38274
+ finishReason: finalStep.finishReason,
38275
+ rawFinishReason: finalStep.rawFinishReason,
38276
+ totalUsage,
38277
+ usage: finalStep.usage,
38278
+ content: finalStep.content,
38279
+ text: finalStep.text,
38280
+ reasoningText: finalStep.reasoningText,
38281
+ reasoning: finalStep.reasoning,
38282
+ files: finalStep.files,
38283
+ sources: finalStep.sources,
38284
+ toolCalls: finalStep.toolCalls,
38285
+ staticToolCalls: finalStep.staticToolCalls,
38286
+ dynamicToolCalls: finalStep.dynamicToolCalls,
38287
+ toolResults: finalStep.toolResults,
38288
+ staticToolResults: finalStep.staticToolResults,
38289
+ dynamicToolResults: finalStep.dynamicToolResults,
38290
+ request: finalStep.request,
38291
+ response: finalStep.response,
38292
+ warnings: finalStep.warnings,
38293
+ providerMetadata: finalStep.providerMetadata,
38294
+ steps: recordedSteps
38295
+ },
38296
+ callbacks: [
38297
+ onFinish,
38298
+ globalTelemetry.onFinish
38299
+ ]
38300
+ });
38080
38301
  rootSpan.setAttributes(
38081
38302
  await selectTelemetryAttributes({
38082
38303
  telemetry,
@@ -38204,8 +38425,8 @@ var DefaultStreamTextResult = class {
38204
38425
  prompt,
38205
38426
  messages
38206
38427
  });
38207
- try {
38208
- await (onStart == null ? void 0 : onStart({
38428
+ await notify({
38429
+ event: {
38209
38430
  model: modelInfo,
38210
38431
  system,
38211
38432
  prompt,
@@ -38231,9 +38452,12 @@ var DefaultStreamTextResult = class {
38231
38452
  include,
38232
38453
  ...callbackTelemetryProps,
38233
38454
  experimental_context
38234
- }));
38235
- } catch (_ignored) {
38236
- }
38455
+ },
38456
+ callbacks: [
38457
+ onStart,
38458
+ globalTelemetry.onStart
38459
+ ]
38460
+ });
38237
38461
  const initialMessages = initialPrompt.messages;
38238
38462
  const initialResponseMessages = [];
38239
38463
  const { approvedToolApprovals, deniedToolApprovals } = collectToolApprovals({ messages: initialMessages });
@@ -38282,8 +38506,14 @@ var DefaultStreamTextResult = class {
38282
38506
  experimental_context,
38283
38507
  stepNumber: recordedSteps.length,
38284
38508
  model: modelInfo,
38285
- onToolCallStart,
38286
- onToolCallFinish,
38509
+ onToolCallStart: [
38510
+ onToolCallStart,
38511
+ globalTelemetry.onToolCallStart
38512
+ ],
38513
+ onToolCallFinish: [
38514
+ onToolCallFinish,
38515
+ globalTelemetry.onToolCallFinish
38516
+ ],
38287
38517
  onPreliminaryToolResult: (result2) => {
38288
38518
  toolExecutionStepStreamController == null ? void 0 : toolExecutionStepStreamController.enqueue(result2);
38289
38519
  }
@@ -38320,7 +38550,7 @@ var DefaultStreamTextResult = class {
38320
38550
  input: output2.input,
38321
38551
  tool: tools == null ? void 0 : tools[output2.toolName],
38322
38552
  output: output2.type === "tool-result" ? output2.output : output2.error,
38323
- errorMode: output2.type === "tool-error" ? "json" : "none"
38553
+ errorMode: output2.type === "tool-error" ? "text" : "none"
38324
38554
  })
38325
38555
  });
38326
38556
  }
@@ -38414,8 +38644,8 @@ var DefaultStreamTextResult = class {
38414
38644
  providerOptions,
38415
38645
  prepareStepResult == null ? void 0 : prepareStepResult.providerOptions
38416
38646
  );
38417
- try {
38418
- await (onStepStart == null ? void 0 : onStepStart({
38647
+ await notify({
38648
+ event: {
38419
38649
  stepNumber: recordedSteps.length,
38420
38650
  model: stepModelInfo,
38421
38651
  system: stepSystem,
@@ -38433,9 +38663,12 @@ var DefaultStreamTextResult = class {
38433
38663
  include,
38434
38664
  ...callbackTelemetryProps,
38435
38665
  experimental_context
38436
- }));
38437
- } catch (_ignored) {
38438
- }
38666
+ },
38667
+ callbacks: [
38668
+ onStepStart,
38669
+ globalTelemetry.onStepStart
38670
+ ]
38671
+ });
38439
38672
  const {
38440
38673
  result: { stream: stream2, response, request },
38441
38674
  doStreamSpan,
@@ -38510,8 +38743,14 @@ var DefaultStreamTextResult = class {
38510
38743
  generateId: generateId2,
38511
38744
  stepNumber: recordedSteps.length,
38512
38745
  model: stepModelInfo,
38513
- onToolCallStart,
38514
- onToolCallFinish
38746
+ onToolCallStart: [
38747
+ onToolCallStart,
38748
+ globalTelemetry.onToolCallStart
38749
+ ],
38750
+ onToolCallFinish: [
38751
+ onToolCallFinish,
38752
+ globalTelemetry.onToolCallFinish
38753
+ ]
38515
38754
  });
38516
38755
  const stepRequest = ((_i = include == null ? void 0 : include.requestBody) != null ? _i : true) ? request != null ? request : {} : { ...request, body: void 0 };
38517
38756
  const stepToolCalls = [];
@@ -39093,7 +39332,8 @@ var DefaultStreamTextResult = class {
39093
39332
  controller.enqueue({
39094
39333
  type: "file",
39095
39334
  mediaType: part.file.mediaType,
39096
- url: `data:${part.file.mediaType};base64,${part.file.base64}`
39335
+ url: `data:${part.file.mediaType};base64,${part.file.base64}`,
39336
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
39097
39337
  });
39098
39338
  break;
39099
39339
  }
@@ -41415,7 +41655,7 @@ var openaiFailedResponseHandler = createJsonErrorResponseHandler$1({
41415
41655
  function getOpenAILanguageModelCapabilities(modelId) {
41416
41656
  const supportsFlexProcessing = modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat");
41417
41657
  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");
41418
- 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");
41658
+ const isReasoningModel = modelId.startsWith("o1") || modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat");
41419
41659
  const supportsNonReasoningParameters = modelId.startsWith("gpt-5.1") || modelId.startsWith("gpt-5.2");
41420
41660
  const systemMessageMode = isReasoningModel ? "developer" : "system";
41421
41661
  return {
@@ -42350,7 +42590,7 @@ var OpenAIChatLanguageModel = class {
42350
42590
  for (const toolCallDelta of delta.tool_calls) {
42351
42591
  const index = toolCallDelta.index;
42352
42592
  if (toolCalls[index] == null) {
42353
- if (toolCallDelta.type !== "function") {
42593
+ if (toolCallDelta.type != null && toolCallDelta.type !== "function") {
42354
42594
  throw new InvalidResponseDataError$1({
42355
42595
  data: toolCallDelta,
42356
42596
  message: `Expected 'function' type.`
@@ -43044,6 +43284,7 @@ var modelMaxImagesPerCall = {
43044
43284
  "chatgpt-image-latest": 10
43045
43285
  };
43046
43286
  var defaultResponseFormatPrefixes = [
43287
+ "chatgpt-image-",
43047
43288
  "gpt-image-1-mini",
43048
43289
  "gpt-image-1.5",
43049
43290
  "gpt-image-1"
@@ -43321,6 +43562,30 @@ var codeInterpreterToolFactory = createProviderToolFactoryWithOutputSchema({
43321
43562
  var codeInterpreter = (args = {}) => {
43322
43563
  return codeInterpreterToolFactory(args);
43323
43564
  };
43565
+ var customArgsSchema = lazySchema(
43566
+ () => zodSchema(
43567
+ object$2({
43568
+ name: string(),
43569
+ description: string().optional(),
43570
+ format: union([
43571
+ object$2({
43572
+ type: literal("grammar"),
43573
+ syntax: _enum(["regex", "lark"]),
43574
+ definition: string()
43575
+ }),
43576
+ object$2({
43577
+ type: literal("text")
43578
+ })
43579
+ ]).optional()
43580
+ })
43581
+ )
43582
+ );
43583
+ var customInputSchema = lazySchema(() => zodSchema(string()));
43584
+ var customToolFactory = createProviderToolFactory({
43585
+ id: "openai.custom",
43586
+ inputSchema: customInputSchema
43587
+ });
43588
+ var customTool = (args) => customToolFactory(args);
43324
43589
  var comparisonFilterSchema = object$2({
43325
43590
  key: string(),
43326
43591
  type: _enum(["eq", "ne", "gt", "gte", "lt", "lte", "in", "nin"]),
@@ -43673,6 +43938,16 @@ var openaiTools = {
43673
43938
  *
43674
43939
  */
43675
43940
  applyPatch,
43941
+ /**
43942
+ * Custom tools let callers constrain model output to a grammar (regex or
43943
+ * Lark syntax). The model returns a `custom_tool_call` output item whose
43944
+ * `input` field is a string matching the specified grammar.
43945
+ *
43946
+ * @param name - The name of the custom tool.
43947
+ * @param description - An optional description of the tool.
43948
+ * @param format - The output format constraint (grammar type, syntax, and definition).
43949
+ */
43950
+ customTool,
43676
43951
  /**
43677
43952
  * The Code Interpreter tool allows models to write and run Python code in a
43678
43953
  * sandboxed environment to solve complex problems in domains like data analysis,
@@ -43713,7 +43988,7 @@ var openaiTools = {
43713
43988
  * Local shell is a tool that allows agents to run shell commands locally
43714
43989
  * on a machine you or the user provides.
43715
43990
  *
43716
- * Supported models: `gpt-5-codex` and `codex-mini-latest`
43991
+ * Supported models: `gpt-5-codex`
43717
43992
  */
43718
43993
  localShell,
43719
43994
  /**
@@ -43811,7 +44086,8 @@ async function convertToOpenAIResponsesInput({
43811
44086
  hasConversation = false,
43812
44087
  hasLocalShellTool = false,
43813
44088
  hasShellTool = false,
43814
- hasApplyPatchTool = false
44089
+ hasApplyPatchTool = false,
44090
+ customProviderToolNames
43815
44091
  }) {
43816
44092
  var _a10, _b9, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
43817
44093
  const input = [];
@@ -43894,7 +44170,9 @@ async function convertToOpenAIResponsesInput({
43894
44170
  for (const part of content) {
43895
44171
  switch (part.type) {
43896
44172
  case "text": {
43897
- const id2 = (_b9 = (_a10 = part.providerOptions) == null ? void 0 : _a10[providerOptionsName]) == null ? void 0 : _b9.itemId;
44173
+ const providerOpts = (_a10 = part.providerOptions) == null ? void 0 : _a10[providerOptionsName];
44174
+ const id2 = providerOpts == null ? void 0 : providerOpts.itemId;
44175
+ const phase = providerOpts == null ? void 0 : providerOpts.phase;
43898
44176
  if (hasConversation && id2 != null) {
43899
44177
  break;
43900
44178
  }
@@ -43905,12 +44183,13 @@ async function convertToOpenAIResponsesInput({
43905
44183
  input.push({
43906
44184
  role: "assistant",
43907
44185
  content: [{ type: "output_text", text: part.text }],
43908
- id: id2
44186
+ id: id2,
44187
+ ...phase != null && { phase }
43909
44188
  });
43910
44189
  break;
43911
44190
  }
43912
44191
  case "tool-call": {
43913
- 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;
44192
+ 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;
43914
44193
  if (hasConversation && id2 != null) {
43915
44194
  break;
43916
44195
  }
@@ -43979,6 +44258,16 @@ async function convertToOpenAIResponsesInput({
43979
44258
  });
43980
44259
  break;
43981
44260
  }
44261
+ if (customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) {
44262
+ input.push({
44263
+ type: "custom_tool_call",
44264
+ call_id: part.toolCallId,
44265
+ name: resolvedToolName,
44266
+ input: typeof part.input === "string" ? part.input : JSON.stringify(part.input),
44267
+ id: id2
44268
+ });
44269
+ break;
44270
+ }
43982
44271
  input.push({
43983
44272
  type: "function_call",
43984
44273
  call_id: part.toolCallId,
@@ -44021,7 +44310,7 @@ async function convertToOpenAIResponsesInput({
44021
44310
  break;
44022
44311
  }
44023
44312
  if (store) {
44024
- const itemId = (_j = (_i = (_h = part.providerOptions) == null ? void 0 : _h[providerOptionsName]) == null ? void 0 : _i.itemId) != null ? _j : part.toolCallId;
44313
+ const itemId = (_i = (_h = (_g = part.providerOptions) == null ? void 0 : _g[providerOptionsName]) == null ? void 0 : _h.itemId) != null ? _i : part.toolCallId;
44025
44314
  input.push({ type: "item_reference", id: itemId });
44026
44315
  } else {
44027
44316
  warnings.push({
@@ -44081,10 +44370,26 @@ async function convertToOpenAIResponsesInput({
44081
44370
  }
44082
44371
  }
44083
44372
  } else {
44084
- warnings.push({
44085
- type: "other",
44086
- message: `Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(part)}.`
44087
- });
44373
+ const encryptedContent = providerOptions == null ? void 0 : providerOptions.reasoningEncryptedContent;
44374
+ if (encryptedContent != null) {
44375
+ const summaryParts = [];
44376
+ if (part.text.length > 0) {
44377
+ summaryParts.push({
44378
+ type: "summary_text",
44379
+ text: part.text
44380
+ });
44381
+ }
44382
+ input.push({
44383
+ type: "reasoning",
44384
+ encrypted_content: encryptedContent,
44385
+ summary: summaryParts
44386
+ });
44387
+ } else {
44388
+ warnings.push({
44389
+ type: "other",
44390
+ message: `Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(part)}.`
44391
+ });
44392
+ }
44088
44393
  }
44089
44394
  break;
44090
44395
  }
@@ -44115,7 +44420,7 @@ async function convertToOpenAIResponsesInput({
44115
44420
  }
44116
44421
  const output = part.output;
44117
44422
  if (output.type === "execution-denied") {
44118
- const approvalId = (_l = (_k = output.providerOptions) == null ? void 0 : _k.openai) == null ? void 0 : _l.approvalId;
44423
+ const approvalId = (_k = (_j = output.providerOptions) == null ? void 0 : _j.openai) == null ? void 0 : _k.approvalId;
44119
44424
  if (approvalId) {
44120
44425
  continue;
44121
44426
  }
@@ -44167,6 +44472,61 @@ async function convertToOpenAIResponsesInput({
44167
44472
  });
44168
44473
  continue;
44169
44474
  }
44475
+ if (customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) {
44476
+ let outputValue;
44477
+ switch (output.type) {
44478
+ case "text":
44479
+ case "error-text":
44480
+ outputValue = output.value;
44481
+ break;
44482
+ case "execution-denied":
44483
+ outputValue = (_l = output.reason) != null ? _l : "Tool execution denied.";
44484
+ break;
44485
+ case "json":
44486
+ case "error-json":
44487
+ outputValue = JSON.stringify(output.value);
44488
+ break;
44489
+ case "content":
44490
+ outputValue = output.value.map((item) => {
44491
+ var _a22;
44492
+ switch (item.type) {
44493
+ case "text":
44494
+ return { type: "input_text", text: item.text };
44495
+ case "image-data":
44496
+ return {
44497
+ type: "input_image",
44498
+ image_url: `data:${item.mediaType};base64,${item.data}`
44499
+ };
44500
+ case "image-url":
44501
+ return {
44502
+ type: "input_image",
44503
+ image_url: item.url
44504
+ };
44505
+ case "file-data":
44506
+ return {
44507
+ type: "input_file",
44508
+ filename: (_a22 = item.filename) != null ? _a22 : "data",
44509
+ file_data: `data:${item.mediaType};base64,${item.data}`
44510
+ };
44511
+ default:
44512
+ warnings.push({
44513
+ type: "other",
44514
+ message: `unsupported custom tool content part type: ${item.type}`
44515
+ });
44516
+ return void 0;
44517
+ }
44518
+ }).filter(isNonNullable);
44519
+ break;
44520
+ default:
44521
+ outputValue = "";
44522
+ }
44523
+ input.push({
44524
+ type: "custom_tool_call_output",
44525
+ call_id: part.toolCallId,
44526
+ output: outputValue
44527
+ });
44528
+ continue;
44529
+ }
44170
44530
  let contentValue;
44171
44531
  switch (output.type) {
44172
44532
  case "text":
@@ -44301,7 +44661,8 @@ var openaiResponsesChunkSchema = lazySchema(
44301
44661
  item: discriminatedUnion("type", [
44302
44662
  object$2({
44303
44663
  type: literal("message"),
44304
- id: string()
44664
+ id: string(),
44665
+ phase: _enum(["commentary", "final_answer"]).nullish()
44305
44666
  }),
44306
44667
  object$2({
44307
44668
  type: literal("reasoning"),
@@ -44382,6 +44743,13 @@ var openaiResponsesChunkSchema = lazySchema(
44382
44743
  })
44383
44744
  ])
44384
44745
  }),
44746
+ object$2({
44747
+ type: literal("custom_tool_call"),
44748
+ id: string(),
44749
+ call_id: string(),
44750
+ name: string(),
44751
+ input: string()
44752
+ }),
44385
44753
  object$2({
44386
44754
  type: literal("shell_call"),
44387
44755
  id: string(),
@@ -44418,7 +44786,8 @@ var openaiResponsesChunkSchema = lazySchema(
44418
44786
  item: discriminatedUnion("type", [
44419
44787
  object$2({
44420
44788
  type: literal("message"),
44421
- id: string()
44789
+ id: string(),
44790
+ phase: _enum(["commentary", "final_answer"]).nullish()
44422
44791
  }),
44423
44792
  object$2({
44424
44793
  type: literal("reasoning"),
@@ -44433,6 +44802,14 @@ var openaiResponsesChunkSchema = lazySchema(
44433
44802
  arguments: string(),
44434
44803
  status: literal("completed")
44435
44804
  }),
44805
+ object$2({
44806
+ type: literal("custom_tool_call"),
44807
+ id: string(),
44808
+ call_id: string(),
44809
+ name: string(),
44810
+ input: string(),
44811
+ status: literal("completed")
44812
+ }),
44436
44813
  object$2({
44437
44814
  type: literal("code_interpreter_call"),
44438
44815
  id: string(),
@@ -44616,6 +44993,12 @@ var openaiResponsesChunkSchema = lazySchema(
44616
44993
  output_index: number$1(),
44617
44994
  delta: string()
44618
44995
  }),
44996
+ object$2({
44997
+ type: literal("response.custom_tool_call_input.delta"),
44998
+ item_id: string(),
44999
+ output_index: number$1(),
45000
+ delta: string()
45001
+ }),
44619
45002
  object$2({
44620
45003
  type: literal("response.image_generation_call.partial_image"),
44621
45004
  item_id: string(),
@@ -44730,6 +45113,7 @@ var openaiResponsesResponseSchema = lazySchema(
44730
45113
  type: literal("message"),
44731
45114
  role: literal("assistant"),
44732
45115
  id: string(),
45116
+ phase: _enum(["commentary", "final_answer"]).nullish(),
44733
45117
  content: array$1(
44734
45118
  object$2({
44735
45119
  type: literal("output_text"),
@@ -44862,6 +45246,13 @@ var openaiResponsesResponseSchema = lazySchema(
44862
45246
  arguments: string(),
44863
45247
  id: string()
44864
45248
  }),
45249
+ object$2({
45250
+ type: literal("custom_tool_call"),
45251
+ call_id: string(),
45252
+ name: string(),
45253
+ input: string(),
45254
+ id: string()
45255
+ }),
44865
45256
  object$2({
44866
45257
  type: literal("computer_call"),
44867
45258
  id: string(),
@@ -45145,14 +45536,18 @@ var openaiLanguageModelResponsesOptionsSchema = lazySchema(
45145
45536
  );
45146
45537
  async function prepareResponsesTools({
45147
45538
  tools,
45148
- toolChoice
45539
+ toolChoice,
45540
+ toolNameMapping,
45541
+ customProviderToolNames
45149
45542
  }) {
45543
+ var _a10;
45150
45544
  tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
45151
45545
  const toolWarnings = [];
45152
45546
  if (tools == null) {
45153
45547
  return { tools: void 0, toolChoice: void 0, toolWarnings };
45154
45548
  }
45155
45549
  const openaiTools2 = [];
45550
+ const resolvedCustomProviderToolNames = customProviderToolNames != null ? customProviderToolNames : /* @__PURE__ */ new Set();
45156
45551
  for (const tool2 of tools) {
45157
45552
  switch (tool2.type) {
45158
45553
  case "function":
@@ -45294,6 +45689,20 @@ async function prepareResponsesTools({
45294
45689
  });
45295
45690
  break;
45296
45691
  }
45692
+ case "openai.custom": {
45693
+ const args = await validateTypes$1({
45694
+ value: tool2.args,
45695
+ schema: customArgsSchema
45696
+ });
45697
+ openaiTools2.push({
45698
+ type: "custom",
45699
+ name: args.name,
45700
+ description: args.description,
45701
+ format: args.format
45702
+ });
45703
+ resolvedCustomProviderToolNames.add(args.name);
45704
+ break;
45705
+ }
45297
45706
  }
45298
45707
  break;
45299
45708
  }
@@ -45314,12 +45723,14 @@ async function prepareResponsesTools({
45314
45723
  case "none":
45315
45724
  case "required":
45316
45725
  return { tools: openaiTools2, toolChoice: type2, toolWarnings };
45317
- case "tool":
45726
+ case "tool": {
45727
+ const resolvedToolName = (_a10 = toolNameMapping == null ? void 0 : toolNameMapping.toProviderToolName(toolChoice.toolName)) != null ? _a10 : toolChoice.toolName;
45318
45728
  return {
45319
45729
  tools: openaiTools2,
45320
- 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 },
45730
+ 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 },
45321
45731
  toolWarnings
45322
45732
  };
45733
+ }
45323
45734
  default: {
45324
45735
  const _exhaustiveCheck = type2;
45325
45736
  throw new UnsupportedFunctionalityError$1({
@@ -45468,7 +45879,19 @@ var OpenAIResponsesLanguageModel = class {
45468
45879
  "openai.web_search_preview": "web_search_preview",
45469
45880
  "openai.mcp": "mcp",
45470
45881
  "openai.apply_patch": "apply_patch"
45471
- }
45882
+ },
45883
+ resolveProviderToolName: (tool2) => tool2.id === "openai.custom" ? tool2.args.name : void 0
45884
+ });
45885
+ const customProviderToolNames = /* @__PURE__ */ new Set();
45886
+ const {
45887
+ tools: openaiTools2,
45888
+ toolChoice: openaiToolChoice,
45889
+ toolWarnings
45890
+ } = await prepareResponsesTools({
45891
+ tools,
45892
+ toolChoice,
45893
+ toolNameMapping,
45894
+ customProviderToolNames
45472
45895
  });
45473
45896
  const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({
45474
45897
  prompt,
@@ -45480,7 +45903,8 @@ var OpenAIResponsesLanguageModel = class {
45480
45903
  hasConversation: (openaiOptions == null ? void 0 : openaiOptions.conversation) != null,
45481
45904
  hasLocalShellTool: hasOpenAITool("openai.local_shell"),
45482
45905
  hasShellTool: hasOpenAITool("openai.shell"),
45483
- hasApplyPatchTool: hasOpenAITool("openai.apply_patch")
45906
+ hasApplyPatchTool: hasOpenAITool("openai.apply_patch"),
45907
+ customProviderToolNames: customProviderToolNames.size > 0 ? customProviderToolNames : void 0
45484
45908
  });
45485
45909
  warnings.push(...inputWarnings);
45486
45910
  const strictJsonSchema = (_d = openaiOptions == null ? void 0 : openaiOptions.strictJsonSchema) != null ? _d : true;
@@ -45613,14 +46037,6 @@ var OpenAIResponsesLanguageModel = class {
45613
46037
  });
45614
46038
  delete baseArgs.service_tier;
45615
46039
  }
45616
- const {
45617
- tools: openaiTools2,
45618
- toolChoice: openaiToolChoice,
45619
- toolWarnings
45620
- } = await prepareResponsesTools({
45621
- tools,
45622
- toolChoice
45623
- });
45624
46040
  const shellToolEnvType = (_i = (_h = (_g = tools == null ? void 0 : tools.find(
45625
46041
  (tool2) => tool2.type === "provider" && tool2.id === "openai.shell"
45626
46042
  )) == null ? void 0 : _g.args) == null ? void 0 : _h.environment) == null ? void 0 : _i.type;
@@ -45781,6 +46197,7 @@ var OpenAIResponsesLanguageModel = class {
45781
46197
  }
45782
46198
  const providerMetadata2 = {
45783
46199
  itemId: part.id,
46200
+ ...part.phase != null && { phase: part.phase },
45784
46201
  ...contentPart.annotations.length > 0 && {
45785
46202
  annotations: contentPart.annotations
45786
46203
  }
@@ -45869,6 +46286,22 @@ var OpenAIResponsesLanguageModel = class {
45869
46286
  });
45870
46287
  break;
45871
46288
  }
46289
+ case "custom_tool_call": {
46290
+ hasFunctionCall = true;
46291
+ const toolName = toolNameMapping.toCustomToolName(part.name);
46292
+ content.push({
46293
+ type: "tool-call",
46294
+ toolCallId: part.call_id,
46295
+ toolName,
46296
+ input: JSON.stringify(part.input),
46297
+ providerMetadata: {
46298
+ [providerOptionsName]: {
46299
+ itemId: part.id
46300
+ }
46301
+ }
46302
+ });
46303
+ break;
46304
+ }
45872
46305
  case "web_search_call": {
45873
46306
  content.push({
45874
46307
  type: "tool-call",
@@ -46095,6 +46528,7 @@ var OpenAIResponsesLanguageModel = class {
46095
46528
  let responseId = null;
46096
46529
  const ongoingToolCalls = {};
46097
46530
  const ongoingAnnotations = [];
46531
+ let activeMessagePhase;
46098
46532
  let hasFunctionCall = false;
46099
46533
  const activeReasoning = {};
46100
46534
  let serviceTier;
@@ -46105,7 +46539,7 @@ var OpenAIResponsesLanguageModel = class {
46105
46539
  controller.enqueue({ type: "stream-start", warnings });
46106
46540
  },
46107
46541
  transform(chunk, controller) {
46108
- 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;
46542
+ 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;
46109
46543
  if (options.includeRawChunks) {
46110
46544
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
46111
46545
  }
@@ -46126,6 +46560,19 @@ var OpenAIResponsesLanguageModel = class {
46126
46560
  id: value.item.call_id,
46127
46561
  toolName: value.item.name
46128
46562
  });
46563
+ } else if (value.item.type === "custom_tool_call") {
46564
+ const toolName = toolNameMapping.toCustomToolName(
46565
+ value.item.name
46566
+ );
46567
+ ongoingToolCalls[value.output_index] = {
46568
+ toolName,
46569
+ toolCallId: value.item.call_id
46570
+ };
46571
+ controller.enqueue({
46572
+ type: "tool-input-start",
46573
+ id: value.item.call_id,
46574
+ toolName
46575
+ });
46129
46576
  } else if (value.item.type === "web_search_call") {
46130
46577
  ongoingToolCalls[value.output_index] = {
46131
46578
  toolName: toolNameMapping.toCustomToolName(
@@ -46246,12 +46693,16 @@ var OpenAIResponsesLanguageModel = class {
46246
46693
  } else if (value.item.type === "shell_call_output") ;
46247
46694
  else if (value.item.type === "message") {
46248
46695
  ongoingAnnotations.splice(0, ongoingAnnotations.length);
46696
+ activeMessagePhase = (_a10 = value.item.phase) != null ? _a10 : void 0;
46249
46697
  controller.enqueue({
46250
46698
  type: "text-start",
46251
46699
  id: value.item.id,
46252
46700
  providerMetadata: {
46253
46701
  [providerOptionsName]: {
46254
- itemId: value.item.id
46702
+ itemId: value.item.id,
46703
+ ...value.item.phase != null && {
46704
+ phase: value.item.phase
46705
+ }
46255
46706
  }
46256
46707
  }
46257
46708
  });
@@ -46266,19 +46717,22 @@ var OpenAIResponsesLanguageModel = class {
46266
46717
  providerMetadata: {
46267
46718
  [providerOptionsName]: {
46268
46719
  itemId: value.item.id,
46269
- reasoningEncryptedContent: (_a10 = value.item.encrypted_content) != null ? _a10 : null
46720
+ reasoningEncryptedContent: (_b9 = value.item.encrypted_content) != null ? _b9 : null
46270
46721
  }
46271
46722
  }
46272
46723
  });
46273
46724
  }
46274
46725
  } else if (isResponseOutputItemDoneChunk(value)) {
46275
46726
  if (value.item.type === "message") {
46727
+ const phase = (_c = value.item.phase) != null ? _c : activeMessagePhase;
46728
+ activeMessagePhase = void 0;
46276
46729
  controller.enqueue({
46277
46730
  type: "text-end",
46278
46731
  id: value.item.id,
46279
46732
  providerMetadata: {
46280
46733
  [providerOptionsName]: {
46281
46734
  itemId: value.item.id,
46735
+ ...phase != null && { phase },
46282
46736
  ...ongoingAnnotations.length > 0 && {
46283
46737
  annotations: ongoingAnnotations
46284
46738
  }
@@ -46303,6 +46757,27 @@ var OpenAIResponsesLanguageModel = class {
46303
46757
  }
46304
46758
  }
46305
46759
  });
46760
+ } else if (value.item.type === "custom_tool_call") {
46761
+ ongoingToolCalls[value.output_index] = void 0;
46762
+ hasFunctionCall = true;
46763
+ const toolName = toolNameMapping.toCustomToolName(
46764
+ value.item.name
46765
+ );
46766
+ controller.enqueue({
46767
+ type: "tool-input-end",
46768
+ id: value.item.call_id
46769
+ });
46770
+ controller.enqueue({
46771
+ type: "tool-call",
46772
+ toolCallId: value.item.call_id,
46773
+ toolName,
46774
+ input: JSON.stringify(value.item.input),
46775
+ providerMetadata: {
46776
+ [providerOptionsName]: {
46777
+ itemId: value.item.id
46778
+ }
46779
+ }
46780
+ });
46306
46781
  } else if (value.item.type === "web_search_call") {
46307
46782
  ongoingToolCalls[value.output_index] = void 0;
46308
46783
  controller.enqueue({
@@ -46343,13 +46818,13 @@ var OpenAIResponsesLanguageModel = class {
46343
46818
  toolName: toolNameMapping.toCustomToolName("file_search"),
46344
46819
  result: {
46345
46820
  queries: value.item.queries,
46346
- results: (_c = (_b9 = value.item.results) == null ? void 0 : _b9.map((result) => ({
46821
+ results: (_e = (_d = value.item.results) == null ? void 0 : _d.map((result) => ({
46347
46822
  attributes: result.attributes,
46348
46823
  fileId: result.file_id,
46349
46824
  filename: result.filename,
46350
46825
  score: result.score,
46351
46826
  text: result.text
46352
- }))) != null ? _c : null
46827
+ }))) != null ? _e : null
46353
46828
  }
46354
46829
  });
46355
46830
  } else if (value.item.type === "code_interpreter_call") {
@@ -46373,10 +46848,10 @@ var OpenAIResponsesLanguageModel = class {
46373
46848
  });
46374
46849
  } else if (value.item.type === "mcp_call") {
46375
46850
  ongoingToolCalls[value.output_index] = void 0;
46376
- const approvalRequestId = (_d = value.item.approval_request_id) != null ? _d : void 0;
46377
- const aliasedToolCallId = approvalRequestId != null ? (_f = (_e = approvalRequestIdToDummyToolCallIdFromStream.get(
46851
+ const approvalRequestId = (_f = value.item.approval_request_id) != null ? _f : void 0;
46852
+ const aliasedToolCallId = approvalRequestId != null ? (_h = (_g = approvalRequestIdToDummyToolCallIdFromStream.get(
46378
46853
  approvalRequestId
46379
- )) != null ? _e : approvalRequestIdToDummyToolCallIdFromPrompt[approvalRequestId]) != null ? _f : value.item.id : value.item.id;
46854
+ )) != null ? _g : approvalRequestIdToDummyToolCallIdFromPrompt[approvalRequestId]) != null ? _h : value.item.id : value.item.id;
46380
46855
  const toolName = `mcp.${value.item.name}`;
46381
46856
  controller.enqueue({
46382
46857
  type: "tool-call",
@@ -46446,8 +46921,8 @@ var OpenAIResponsesLanguageModel = class {
46446
46921
  ongoingToolCalls[value.output_index] = void 0;
46447
46922
  } else if (value.item.type === "mcp_approval_request") {
46448
46923
  ongoingToolCalls[value.output_index] = void 0;
46449
- const dummyToolCallId = (_i = (_h = (_g = self2.config).generateId) == null ? void 0 : _h.call(_g)) != null ? _i : generateId$1();
46450
- const approvalRequestId = (_j = value.item.approval_request_id) != null ? _j : value.item.id;
46924
+ const dummyToolCallId = (_k = (_j = (_i = self2.config).generateId) == null ? void 0 : _j.call(_i)) != null ? _k : generateId$1();
46925
+ const approvalRequestId = (_l = value.item.approval_request_id) != null ? _l : value.item.id;
46451
46926
  approvalRequestIdToDummyToolCallIdFromStream.set(
46452
46927
  approvalRequestId,
46453
46928
  dummyToolCallId
@@ -46536,7 +47011,7 @@ var OpenAIResponsesLanguageModel = class {
46536
47011
  providerMetadata: {
46537
47012
  [providerOptionsName]: {
46538
47013
  itemId: value.item.id,
46539
- reasoningEncryptedContent: (_k = value.item.encrypted_content) != null ? _k : null
47014
+ reasoningEncryptedContent: (_m = value.item.encrypted_content) != null ? _m : null
46540
47015
  }
46541
47016
  }
46542
47017
  });
@@ -46552,6 +47027,15 @@ var OpenAIResponsesLanguageModel = class {
46552
47027
  delta: value.delta
46553
47028
  });
46554
47029
  }
47030
+ } else if (isResponseCustomToolCallInputDeltaChunk(value)) {
47031
+ const toolCall = ongoingToolCalls[value.output_index];
47032
+ if (toolCall != null) {
47033
+ controller.enqueue({
47034
+ type: "tool-input-delta",
47035
+ id: toolCall.toolCallId,
47036
+ delta: value.delta
47037
+ });
47038
+ }
46555
47039
  } else if (isResponseApplyPatchCallOperationDiffDeltaChunk(value)) {
46556
47040
  const toolCall = ongoingToolCalls[value.output_index];
46557
47041
  if (toolCall == null ? void 0 : toolCall.applyPatch) {
@@ -46640,7 +47124,7 @@ var OpenAIResponsesLanguageModel = class {
46640
47124
  id: value.item_id,
46641
47125
  delta: value.delta
46642
47126
  });
46643
- if (((_m = (_l = options.providerOptions) == null ? void 0 : _l[providerOptionsName]) == null ? void 0 : _m.logprobs) && value.logprobs) {
47127
+ if (((_o = (_n = options.providerOptions) == null ? void 0 : _n[providerOptionsName]) == null ? void 0 : _o.logprobs) && value.logprobs) {
46644
47128
  logprobs.push(value.logprobs);
46645
47129
  }
46646
47130
  } else if (value.type === "response.reasoning_summary_part.added") {
@@ -46669,7 +47153,7 @@ var OpenAIResponsesLanguageModel = class {
46669
47153
  providerMetadata: {
46670
47154
  [providerOptionsName]: {
46671
47155
  itemId: value.item_id,
46672
- reasoningEncryptedContent: (_o = (_n = activeReasoning[value.item_id]) == null ? void 0 : _n.encryptedContent) != null ? _o : null
47156
+ reasoningEncryptedContent: (_q = (_p = activeReasoning[value.item_id]) == null ? void 0 : _p.encryptedContent) != null ? _q : null
46673
47157
  }
46674
47158
  }
46675
47159
  });
@@ -46703,10 +47187,10 @@ var OpenAIResponsesLanguageModel = class {
46703
47187
  } else if (isResponseFinishedChunk(value)) {
46704
47188
  finishReason = {
46705
47189
  unified: mapOpenAIResponseFinishReason({
46706
- finishReason: (_p = value.response.incomplete_details) == null ? void 0 : _p.reason,
47190
+ finishReason: (_r = value.response.incomplete_details) == null ? void 0 : _r.reason,
46707
47191
  hasFunctionCall
46708
47192
  }),
46709
- raw: (_r = (_q = value.response.incomplete_details) == null ? void 0 : _q.reason) != null ? _r : void 0
47193
+ raw: (_t = (_s = value.response.incomplete_details) == null ? void 0 : _s.reason) != null ? _t : void 0
46710
47194
  };
46711
47195
  usage = value.response.usage;
46712
47196
  if (typeof value.response.service_tier === "string") {
@@ -46718,7 +47202,7 @@ var OpenAIResponsesLanguageModel = class {
46718
47202
  controller.enqueue({
46719
47203
  type: "source",
46720
47204
  sourceType: "url",
46721
- id: (_u = (_t = (_s = self2.config).generateId) == null ? void 0 : _t.call(_s)) != null ? _u : generateId$1(),
47205
+ id: (_w = (_v = (_u = self2.config).generateId) == null ? void 0 : _v.call(_u)) != null ? _w : generateId$1(),
46722
47206
  url: value.annotation.url,
46723
47207
  title: value.annotation.title
46724
47208
  });
@@ -46726,7 +47210,7 @@ var OpenAIResponsesLanguageModel = class {
46726
47210
  controller.enqueue({
46727
47211
  type: "source",
46728
47212
  sourceType: "document",
46729
- id: (_x = (_w = (_v = self2.config).generateId) == null ? void 0 : _w.call(_v)) != null ? _x : generateId$1(),
47213
+ id: (_z = (_y = (_x = self2.config).generateId) == null ? void 0 : _y.call(_x)) != null ? _z : generateId$1(),
46730
47214
  mediaType: "text/plain",
46731
47215
  title: value.annotation.filename,
46732
47216
  filename: value.annotation.filename,
@@ -46742,7 +47226,7 @@ var OpenAIResponsesLanguageModel = class {
46742
47226
  controller.enqueue({
46743
47227
  type: "source",
46744
47228
  sourceType: "document",
46745
- id: (_A = (_z = (_y = self2.config).generateId) == null ? void 0 : _z.call(_y)) != null ? _A : generateId$1(),
47229
+ id: (_C = (_B = (_A = self2.config).generateId) == null ? void 0 : _B.call(_A)) != null ? _C : generateId$1(),
46746
47230
  mediaType: "text/plain",
46747
47231
  title: value.annotation.filename,
46748
47232
  filename: value.annotation.filename,
@@ -46758,7 +47242,7 @@ var OpenAIResponsesLanguageModel = class {
46758
47242
  controller.enqueue({
46759
47243
  type: "source",
46760
47244
  sourceType: "document",
46761
- id: (_D = (_C = (_B = self2.config).generateId) == null ? void 0 : _C.call(_B)) != null ? _D : generateId$1(),
47245
+ id: (_F = (_E = (_D = self2.config).generateId) == null ? void 0 : _E.call(_D)) != null ? _F : generateId$1(),
46762
47246
  mediaType: "application/octet-stream",
46763
47247
  title: value.annotation.file_id,
46764
47248
  filename: value.annotation.file_id,
@@ -46812,6 +47296,9 @@ function isResponseCreatedChunk(chunk) {
46812
47296
  function isResponseFunctionCallArgumentsDeltaChunk(chunk) {
46813
47297
  return chunk.type === "response.function_call_arguments.delta";
46814
47298
  }
47299
+ function isResponseCustomToolCallInputDeltaChunk(chunk) {
47300
+ return chunk.type === "response.custom_tool_call_input.delta";
47301
+ }
46815
47302
  function isResponseImageGenerationCallPartialImageChunk(chunk) {
46816
47303
  return chunk.type === "response.image_generation_call.partial_image";
46817
47304
  }
@@ -47193,7 +47680,7 @@ var OpenAITranscriptionModel = class {
47193
47680
  };
47194
47681
  }
47195
47682
  };
47196
- var VERSION$2 = "3.0.33";
47683
+ var VERSION$2 = "3.0.41";
47197
47684
  function createOpenAI(options = {}) {
47198
47685
  var _a10, _b9;
47199
47686
  const baseURL = (_a10 = withoutTrailingSlash$1(
@@ -49013,9 +49500,13 @@ function generateReActToolsPrompt(tools) {
49013
49500
  if (toolEntries.length === 0) {
49014
49501
  return "";
49015
49502
  }
49016
- let prompt = "\n\n# 工具调用\n\n";
49017
- prompt += "你可以根据需要调用以下工具:\n\n";
49018
- prompt += "<tools>\n";
49503
+ let prompt = `
49504
+ # 工具调用
49505
+
49506
+ 你可以根据需要调用以下工具:
49507
+
49508
+ <tools>
49509
+ `;
49019
49510
  toolEntries.forEach(([toolName, tool2]) => {
49020
49511
  const toolInfo = tool2;
49021
49512
  const description2 = toolInfo.description || "无描述";
@@ -49028,23 +49519,36 @@ function generateReActToolsPrompt(tools) {
49028
49519
  prompt += `${JSON.stringify(toolJson, null, 2)}
49029
49520
  `;
49030
49521
  });
49031
- prompt += "</tools>\n\n";
49032
- prompt += "## 工具调用格式\n\n";
49033
- prompt += "要调用工具,请使用以下 XML 格式:\n";
49034
- prompt += "Thought: [你的思考过程]\n";
49035
- prompt += '<tool_call>{"name": "toolName", "arguments": {"arg1": "value1"}}</tool_call>\n\n';
49036
- prompt += "工具执行后,你将收到 <tool_response> 格式的结果。你可以继续思考或调用其他工具。\n\n";
49037
- prompt += "## 使用示例\n\n";
49038
- prompt += '如果用户要求"获取今天的日期",你可以这样调用工具:\n';
49039
- prompt += "Thought: 用户想要获取今天的日期,我需要调用日期相关的工具。\n";
49040
- prompt += '<tool_call>{"name": "get-today", "arguments": {}}</tool_call>\n\n';
49041
- prompt += "然后等待工具返回结果(Observation),再根据结果给出最终答案。\n\n";
49042
- prompt += "## 任务完成\n\n";
49043
- prompt += "当任务完成或无法继续时,直接给出最终答案即可。\n\n";
49044
- prompt += "**重要提示**:\n";
49045
- prompt += "- 必须严格按照 XML 格式调用工具\n";
49046
- prompt += "- arguments 必须是有效的 JSON 格式\n";
49047
- prompt += "- 如果不需要调用工具,直接给出最终答案即可\n";
49522
+ prompt += `
49523
+ </tools>
49524
+
49525
+ ## 工具调用格式
49526
+
49527
+ 要调用工具,请使用以下 XML 格式:
49528
+ Thought: [你的思考过程]
49529
+ <tool_call>
49530
+ {"name": "toolName", "arguments": {"arg1": "value1"}}
49531
+ </tool_call>
49532
+
49533
+ 工具执行后,你将收到 <tool_response> 格式的结果。你可以继续思考或调用其他工具。
49534
+
49535
+ ## 使用示例
49536
+
49537
+ 如果用户要求"获取今天的日期",你可以这样调用工具:
49538
+ Thought: 用户想要获取今天的日期,我需要调用日期相关的工具。
49539
+ <tool_call>{"name": "get-today", "arguments": {}}</tool_call>
49540
+
49541
+ 然后等待工具返回结果(Observation),再根据结果给出最终答案。
49542
+
49543
+ ## 任务完成
49544
+
49545
+ 当任务完成或无法继续时,直接给出最终答案即可。
49546
+
49547
+ **重要提示**:
49548
+ - 必须严格按照 XML 格式调用工具
49549
+ - arguments 必须是有效的 JSON 格式
49550
+ - 如果不需要调用工具,直接给出最终答案即可
49551
+ `;
49048
49552
  return prompt;
49049
49553
  }
49050
49554
  function parseReActAction(text2, availableTools) {
@@ -49651,6 +50155,122 @@ ${observationText}
49651
50155
  return this._chat(streamText, options);
49652
50156
  }
49653
50157
  }
50158
+ const MSG_TOOL_CALL = "next-sdk:tool-call";
50159
+ const MSG_TOOL_RESPONSE = "next-sdk:tool-response";
50160
+ const MSG_PAGE_READY = "next-sdk:page-ready";
50161
+ const activePages = /* @__PURE__ */ new Map();
50162
+ let _navigator = null;
50163
+ function setNavigator(fn) {
50164
+ _navigator = fn;
50165
+ }
50166
+ function buildPageHandler(name16, route, timeout = 3e4) {
50167
+ return (input) => {
50168
+ const callId = randomUUID();
50169
+ return new Promise((resolve2, reject) => {
50170
+ let timer;
50171
+ let readyHandler;
50172
+ const cleanup = () => {
50173
+ clearTimeout(timer);
50174
+ window.removeEventListener("message", responseHandler);
50175
+ if (readyHandler) {
50176
+ window.removeEventListener("message", readyHandler);
50177
+ }
50178
+ };
50179
+ timer = setTimeout(() => {
50180
+ cleanup();
50181
+ reject(new Error(`工具 [${name16}] 调用超时 (${timeout}ms),请检查目标页面是否正确调用了 registerPageTool`));
50182
+ }, timeout);
50183
+ const responseHandler = (event) => {
50184
+ if (event.source === window && event.data?.type === MSG_TOOL_RESPONSE && event.data.callId === callId) {
50185
+ cleanup();
50186
+ event.data.error ? reject(new Error(event.data.error)) : resolve2(event.data.result);
50187
+ }
50188
+ };
50189
+ window.addEventListener("message", responseHandler);
50190
+ const sendCall = () => {
50191
+ window.postMessage({ type: MSG_TOOL_CALL, callId, toolName: name16, route, input }, window.location.origin || "*");
50192
+ };
50193
+ let callSent = false;
50194
+ const sendCallOnce = () => {
50195
+ if (callSent) return;
50196
+ callSent = true;
50197
+ sendCall();
50198
+ };
50199
+ const run = async () => {
50200
+ try {
50201
+ if (activePages.get(route)) {
50202
+ sendCallOnce();
50203
+ return;
50204
+ }
50205
+ readyHandler = (event) => {
50206
+ if (event.source === window && event.data?.type === MSG_PAGE_READY && event.data.route === route) {
50207
+ window.removeEventListener("message", readyHandler);
50208
+ sendCallOnce();
50209
+ }
50210
+ };
50211
+ window.addEventListener("message", readyHandler);
50212
+ if (_navigator) {
50213
+ await _navigator(route);
50214
+ }
50215
+ if (activePages.get(route)) {
50216
+ window.removeEventListener("message", readyHandler);
50217
+ sendCallOnce();
50218
+ }
50219
+ } catch (err) {
50220
+ cleanup();
50221
+ reject(err instanceof Error ? err : new Error(String(err)));
50222
+ }
50223
+ };
50224
+ void run();
50225
+ });
50226
+ };
50227
+ }
50228
+ function withPageTools(server) {
50229
+ return new Proxy(server, {
50230
+ get(target, prop, receiver) {
50231
+ if (prop === "registerTool") {
50232
+ return (name16, config2, handlerOrRoute) => {
50233
+ if (typeof handlerOrRoute === "function") {
50234
+ return target.registerTool(name16, config2, handlerOrRoute);
50235
+ }
50236
+ const { route, timeout } = handlerOrRoute;
50237
+ return target.registerTool(name16, config2, buildPageHandler(name16, route, timeout));
50238
+ };
50239
+ }
50240
+ return Reflect.get(target, prop, receiver);
50241
+ }
50242
+ });
50243
+ }
50244
+ function registerPageTool(options) {
50245
+ const { handlers } = options;
50246
+ const route = window.location.pathname;
50247
+ const handleMessage = async (event) => {
50248
+ if (event.source !== window || event.data?.type !== MSG_TOOL_CALL || event.data?.route !== route || !(event.data.toolName in handlers)) {
50249
+ return;
50250
+ }
50251
+ const { callId, toolName, input } = event.data;
50252
+ try {
50253
+ const result = await handlers[toolName](input);
50254
+ window.postMessage({ type: MSG_TOOL_RESPONSE, callId, result }, window.location.origin || "*");
50255
+ } catch (err) {
50256
+ window.postMessage(
50257
+ {
50258
+ type: MSG_TOOL_RESPONSE,
50259
+ callId,
50260
+ error: err instanceof Error ? err.message : String(err)
50261
+ },
50262
+ window.location.origin || "*"
50263
+ );
50264
+ }
50265
+ };
50266
+ activePages.set(route, true);
50267
+ window.addEventListener("message", handleMessage);
50268
+ window.postMessage({ type: MSG_PAGE_READY, route }, window.location.origin || "*");
50269
+ return () => {
50270
+ activePages.delete(route);
50271
+ window.removeEventListener("message", handleMessage);
50272
+ };
50273
+ }
49654
50274
  const MAIN_SKILL_PATH_REG = /^\.\/[^/]+\/SKILL\.md$/;
49655
50275
  const FRONT_MATTER_BLOCK_REG = /^---\s*\n([\s\S]+?)\s*\n---/;
49656
50276
  function parseSkillFrontMatter(content) {
@@ -49663,14 +50283,27 @@ function parseSkillFrontMatter(content) {
49663
50283
  const description2 = descMatch?.[1]?.trim();
49664
50284
  return name16 && description2 ? { name: name16, description: description2 } : null;
49665
50285
  }
50286
+ function normalizeSkillModuleKeys(modules) {
50287
+ const result = {};
50288
+ for (const [key, content] of Object.entries(modules)) {
50289
+ const normalizedKey = key.replace(/\\/g, "/");
50290
+ const skillsIndex = normalizedKey.lastIndexOf("skills/");
50291
+ const relativePath = skillsIndex >= 0 ? normalizedKey.slice(skillsIndex + 7) : normalizedKey;
50292
+ const standardPath = relativePath.startsWith("./") ? relativePath : `./${relativePath}`;
50293
+ result[standardPath] = content;
50294
+ }
50295
+ return result;
50296
+ }
49666
50297
  function getMainSkillPaths(modules) {
49667
- return Object.keys(modules).filter((path) => MAIN_SKILL_PATH_REG.test(path));
50298
+ const normalized = normalizeSkillModuleKeys(modules);
50299
+ return Object.keys(normalized).filter((path) => MAIN_SKILL_PATH_REG.test(path));
49668
50300
  }
49669
50301
  function getSkillOverviews(modules) {
49670
- const mainPaths = getMainSkillPaths(modules);
50302
+ const normalized = normalizeSkillModuleKeys(modules);
50303
+ const mainPaths = Object.keys(normalized).filter((path) => MAIN_SKILL_PATH_REG.test(path));
49671
50304
  const list = [];
49672
50305
  for (const path of mainPaths) {
49673
- const content = modules[path];
50306
+ const content = normalized[path];
49674
50307
  if (!content) continue;
49675
50308
  const parsed = parseSkillFrontMatter(content);
49676
50309
  if (!parsed) continue;
@@ -49692,34 +50325,38 @@ ${lines.join("\n")}
49692
50325
  当需要用到某技能时,请使用 get_skill_content 工具获取该技能的完整文档内容。`;
49693
50326
  }
49694
50327
  function getSkillMdPaths(modules) {
49695
- return Object.keys(modules);
50328
+ const normalized = normalizeSkillModuleKeys(modules);
50329
+ return Object.keys(normalized);
49696
50330
  }
49697
50331
  function getSkillMdContent(modules, path) {
49698
- return modules[path];
50332
+ const normalized = normalizeSkillModuleKeys(modules);
50333
+ return normalized[path];
49699
50334
  }
49700
50335
  function getMainSkillPathByName(modules, name16) {
49701
50336
  return getMainSkillPaths(modules).find((p) => p.startsWith(`./${name16}/SKILL.md`));
49702
50337
  }
50338
+ const SKILL_INPUT_SCHEMA = objectType({
50339
+ skillName: stringType().optional().describe("技能名称,与目录名一致,如 calculator"),
50340
+ path: stringType().optional().describe("文档相对路径,如 ./calculator/SKILL.md 或 ./product-guide/reference/xxx.json")
50341
+ });
49703
50342
  function createSkillTools(modules) {
50343
+ const normalizedModules = normalizeSkillModuleKeys(modules);
49704
50344
  const getSkillContent = tool({
49705
- description: "根据技能名称或文档路径获取该技能的完整 Markdown 文档内容。传入 skillName(如 calculator)或 path(如 ./calculator/SKILL.md",
49706
- inputSchema: objectType({
49707
- skillName: stringType().optional().describe("技能名称,与目录名一致,如 calculator"),
49708
- path: stringType().optional().describe("文档相对路径,如 ./calculator/SKILL.md 或 ./product-guide/reference/xxx.md")
49709
- }),
50345
+ description: "根据技能名称或文档路径获取该技能的完整文档内容。传入 skillName(如 calculator)或 path(如 ./calculator/SKILL.md)。支持 .md、.json、.xml 等各类文本格式文件。",
50346
+ inputSchema: SKILL_INPUT_SCHEMA,
49710
50347
  execute: (args) => {
49711
50348
  const { skillName, path: pathArg } = args;
49712
50349
  let content;
49713
50350
  if (pathArg) {
49714
- content = getSkillMdContent(modules, pathArg);
50351
+ content = getSkillMdContent(normalizedModules, pathArg);
49715
50352
  } else if (skillName) {
49716
- const mainPath = getMainSkillPathByName(modules, skillName);
49717
- content = mainPath ? getSkillMdContent(modules, mainPath) : void 0;
50353
+ const mainPath = getMainSkillPathByName(normalizedModules, skillName);
50354
+ content = mainPath ? getSkillMdContent(normalizedModules, mainPath) : void 0;
49718
50355
  }
49719
50356
  if (content === void 0) {
49720
50357
  return { error: "未找到对应技能文档", skillName: skillName ?? pathArg };
49721
50358
  }
49722
- return { content, path: pathArg ?? getMainSkillPathByName(modules, skillName) };
50359
+ return { content, path: pathArg ?? getMainSkillPathByName(normalizedModules, skillName) };
49723
50360
  }
49724
50361
  });
49725
50362
  return {
@@ -49762,5 +50399,8 @@ export {
49762
50399
  isSSEClientTransport,
49763
50400
  isStreamableHTTPClientTransport,
49764
50401
  parseSkillFrontMatter,
50402
+ registerPageTool,
50403
+ setNavigator,
50404
+ withPageTools,
49765
50405
  z
49766
50406
  };