@opentiny/next-sdk 0.2.6 → 0.2.7

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();
@@ -26982,10 +26982,11 @@ const DEFAULT_REMOTE_URL = "https://chat.opentiny.design";
26982
26982
  const DEFAULT_QR_CODE_URL = "https://ai.opentiny.design/next-remoter";
26983
26983
  const DEFAULT_LOGO_URL = "https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg";
26984
26984
  const getDefaultMenuItems = (options) => {
26985
- return [
26985
+ const hasSession = !!options.sessionId;
26986
+ const baseItems = [
26986
26987
  {
26987
26988
  action: "qr-code",
26988
- show: true,
26989
+ show: hasSession,
26989
26990
  text: "扫码登录",
26990
26991
  desc: "使用手机遥控页面",
26991
26992
  icon: qrCode
@@ -26999,7 +27000,7 @@ const getDefaultMenuItems = (options) => {
26999
27000
  },
27000
27001
  {
27001
27002
  action: "remote-url",
27002
- show: true,
27003
+ show: hasSession,
27003
27004
  text: `遥控器链接`,
27004
27005
  desc: `${options.remoteUrl}`,
27005
27006
  active: true,
@@ -27009,14 +27010,15 @@ const getDefaultMenuItems = (options) => {
27009
27010
  },
27010
27011
  {
27011
27012
  action: "remote-control",
27012
- show: true,
27013
+ show: hasSession,
27013
27014
  text: `识别码`,
27014
- desc: `${options.sessionId.slice(-6)}`,
27015
+ desc: hasSession ? `${options.sessionId.slice(-6)}` : "",
27015
27016
  know: true,
27016
27017
  showCopyIcon: true,
27017
27018
  icon: scan
27018
27019
  }
27019
27020
  ];
27021
+ return baseItems;
27020
27022
  };
27021
27023
  class FloatingBlock {
27022
27024
  constructor(options) {
@@ -27048,9 +27050,6 @@ class FloatingBlock {
27048
27050
  trigger: "hover"
27049
27051
  });
27050
27052
  };
27051
- if (!options.sessionId) {
27052
- throw new Error("sessionId is required");
27053
- }
27054
27053
  this.options = {
27055
27054
  ...options,
27056
27055
  qrCodeUrl: options.qrCodeUrl || DEFAULT_QR_CODE_URL,
@@ -27069,11 +27068,14 @@ class FloatingBlock {
27069
27068
  return this.options.qrCodeUrl?.includes("?") ? "&sessionId=" : "?sessionId=";
27070
27069
  }
27071
27070
  /**
27072
- * 合并菜单项配置
27073
- * @param userMenuItems 用户自定义菜单项配置
27074
- * @returns 合并后的菜单项配置
27071
+ * 合并菜单项配置。
27072
+ * - sessionId:使用默认菜单 + 用户配置(可定制每一项的 show/text/icon 等)
27073
+ * - 无 sessionId:不渲染任何下拉菜单,仅保留点击浮标打开对话框的能力
27075
27074
  */
27076
27075
  mergeMenuItems(userMenuItems) {
27076
+ if (!this.options.sessionId) {
27077
+ return [];
27078
+ }
27077
27079
  if (!userMenuItems) {
27078
27080
  return getDefaultMenuItems(this.options);
27079
27081
  }
@@ -27083,7 +27085,6 @@ class FloatingBlock {
27083
27085
  return {
27084
27086
  ...defaultItem,
27085
27087
  ...userItem,
27086
- // 确保show属性存在,默认为true
27087
27088
  show: userItem.show !== void 0 ? userItem.show : defaultItem.show
27088
27089
  };
27089
27090
  }
@@ -27227,9 +27228,11 @@ class FloatingBlock {
27227
27228
  this.closeDropdown();
27228
27229
  }
27229
27230
  copyRemoteControl() {
27231
+ if (!this.options.sessionId) return;
27230
27232
  this.copyToClipboard(this.options.sessionId.slice(-6));
27231
27233
  }
27232
27234
  copyRemoteURL() {
27235
+ if (!this.options.sessionId) return;
27233
27236
  this.copyToClipboard(this.options.remoteUrl + this.sessionPrefix + this.options.sessionId);
27234
27237
  }
27235
27238
  // 实现复制到剪贴板功能
@@ -27277,8 +27280,9 @@ class FloatingBlock {
27277
27280
  }, 300);
27278
27281
  }, 1500);
27279
27282
  }
27280
- // 创建二维码弹窗
27283
+ // 创建二维码弹窗(无 sessionId 时不展示)
27281
27284
  async showQRCode() {
27285
+ if (!this.options.sessionId) return;
27282
27286
  const qrCode2 = new QrCode((this.options.qrCodeUrl || "") + this.sessionPrefix + this.options.sessionId, {});
27283
27287
  const base642 = await qrCode2.toDataURL();
27284
27288
  const modal = this.createModal(
@@ -28049,25 +28053,30 @@ function combineHeaders$1(...headers) {
28049
28053
  }
28050
28054
  function createToolNameMapping({
28051
28055
  tools = [],
28052
- providerToolNames
28056
+ providerToolNames,
28057
+ resolveProviderToolName
28053
28058
  }) {
28059
+ var _a22;
28054
28060
  const customToolNameToProviderToolName = {};
28055
28061
  const providerToolNameToCustomToolName = {};
28056
28062
  for (const tool2 of tools) {
28057
- if (tool2.type === "provider" && tool2.id in providerToolNames) {
28058
- 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
+ }
28059
28068
  customToolNameToProviderToolName[tool2.name] = providerToolName;
28060
28069
  providerToolNameToCustomToolName[providerToolName] = tool2.name;
28061
28070
  }
28062
28071
  }
28063
28072
  return {
28064
28073
  toProviderToolName: (customToolName) => {
28065
- var _a22;
28066
- return (_a22 = customToolNameToProviderToolName[customToolName]) != null ? _a22 : customToolName;
28074
+ var _a32;
28075
+ return (_a32 = customToolNameToProviderToolName[customToolName]) != null ? _a32 : customToolName;
28067
28076
  },
28068
28077
  toCustomToolName: (providerToolName) => {
28069
- var _a22;
28070
- return (_a22 = providerToolNameToCustomToolName[providerToolName]) != null ? _a22 : providerToolName;
28078
+ var _a32;
28079
+ return (_a32 = providerToolNameToCustomToolName[providerToolName]) != null ? _a32 : providerToolName;
28071
28080
  }
28072
28081
  };
28073
28082
  }
@@ -28260,8 +28269,103 @@ async function readResponseWithSizeLimit({
28260
28269
  }
28261
28270
  return result;
28262
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
+ }
28263
28366
  async function downloadBlob(url2, options) {
28264
28367
  var _a22, _b22;
28368
+ validateDownloadUrl(url2);
28265
28369
  try {
28266
28370
  const response = await fetch(url2, {
28267
28371
  signal: options == null ? void 0 : options.abortSignal
@@ -28427,7 +28531,7 @@ function withUserAgentSuffix$1(headers, ...userAgentSuffixParts) {
28427
28531
  );
28428
28532
  return Object.fromEntries(normalizedHeaders.entries());
28429
28533
  }
28430
- var VERSION$7 = "4.0.15";
28534
+ var VERSION$7 = "4.0.19";
28431
28535
  var getOriginalFetch = () => globalThis.fetch;
28432
28536
  var getFromApi = async ({
28433
28537
  url: url2,
@@ -28570,8 +28674,8 @@ function mediaTypeToExtension(mediaType) {
28570
28674
  "x-m4a": "m4a"
28571
28675
  }[subtype]) != null ? _a22 : subtype;
28572
28676
  }
28573
- var suspectProtoRx$1 = /"__proto__"\s*:/;
28574
- 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*:/;
28575
28679
  function _parse$1(text2) {
28576
28680
  const obj = JSON.parse(text2);
28577
28681
  if (obj === null || typeof obj !== "object") {
@@ -28591,7 +28695,7 @@ function filter$1(obj) {
28591
28695
  if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
28592
28696
  throw new SyntaxError("Object contains forbidden prototype property");
28593
28697
  }
28594
- 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")) {
28595
28699
  throw new SyntaxError("Object contains forbidden prototype property");
28596
28700
  }
28597
28701
  for (const key in node) {
@@ -30078,6 +30182,33 @@ function tool(tool2) {
30078
30182
  function dynamicTool(tool2) {
30079
30183
  return { ...tool2, type: "dynamic" };
30080
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
+ }
30081
30212
  function createProviderToolFactoryWithOutputSchema({
30082
30213
  id: id2,
30083
30214
  inputSchema,
@@ -31548,7 +31679,7 @@ async function getVercelRequestId() {
31548
31679
  var _a92;
31549
31680
  return (_a92 = indexBrowserExports.getContext().headers) == null ? void 0 : _a92["x-vercel-id"];
31550
31681
  }
31551
- var VERSION$6 = "3.0.58";
31682
+ var VERSION$6 = "3.0.66";
31552
31683
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
31553
31684
  function createGatewayProvider(options = {}) {
31554
31685
  var _a92, _b9;
@@ -32686,6 +32817,8 @@ function asArray(value) {
32686
32817
  }
32687
32818
  async function notify(options) {
32688
32819
  for (const callback of asArray(options.callbacks)) {
32820
+ if (callback == null)
32821
+ continue;
32689
32822
  try {
32690
32823
  await callback(options.event);
32691
32824
  } catch (_ignored) {
@@ -32992,7 +33125,7 @@ function detectMediaType({
32992
33125
  }
32993
33126
  return void 0;
32994
33127
  }
32995
- var VERSION$4 = "6.0.104";
33128
+ var VERSION$4 = "6.0.116";
32996
33129
  var download = async ({
32997
33130
  url: url2,
32998
33131
  maxBytes,
@@ -33000,6 +33133,7 @@ var download = async ({
33000
33133
  }) => {
33001
33134
  var _a21;
33002
33135
  const urlText = url2.toString();
33136
+ validateDownloadUrl(urlText);
33003
33137
  try {
33004
33138
  const response = await fetch(urlText, {
33005
33139
  headers: withUserAgentSuffix$1(
@@ -34105,6 +34239,44 @@ function stringifyForTelemetry(prompt) {
34105
34239
  }))
34106
34240
  );
34107
34241
  }
34242
+ function getGlobalTelemetryIntegrations() {
34243
+ var _a21;
34244
+ return (_a21 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a21 : [];
34245
+ }
34246
+ function getGlobalTelemetryIntegration() {
34247
+ const globalIntegrations = getGlobalTelemetryIntegrations();
34248
+ return (integrations) => {
34249
+ const localIntegrations = asArray(integrations);
34250
+ const allIntegrations = [...globalIntegrations, ...localIntegrations];
34251
+ function createTelemetryComposite(getListenerFromIntegration) {
34252
+ const listeners = allIntegrations.map(getListenerFromIntegration).filter(Boolean);
34253
+ return async (event) => {
34254
+ for (const listener of listeners) {
34255
+ try {
34256
+ await listener(event);
34257
+ } catch (_ignored) {
34258
+ }
34259
+ }
34260
+ };
34261
+ }
34262
+ return {
34263
+ onStart: createTelemetryComposite((integration) => integration.onStart),
34264
+ onStepStart: createTelemetryComposite(
34265
+ (integration) => integration.onStepStart
34266
+ ),
34267
+ onToolCallStart: createTelemetryComposite(
34268
+ (integration) => integration.onToolCallStart
34269
+ ),
34270
+ onToolCallFinish: createTelemetryComposite(
34271
+ (integration) => integration.onToolCallFinish
34272
+ ),
34273
+ onStepFinish: createTelemetryComposite(
34274
+ (integration) => integration.onStepFinish
34275
+ ),
34276
+ onFinish: createTelemetryComposite((integration) => integration.onFinish)
34277
+ };
34278
+ };
34279
+ }
34108
34280
  function asLanguageModelUsage(usage) {
34109
34281
  return {
34110
34282
  inputTokens: usage.inputTokens.total,
@@ -35655,6 +35827,7 @@ async function generateText({
35655
35827
  ...settings
35656
35828
  }) {
35657
35829
  const model = resolveLanguageModel(modelArg);
35830
+ const createGlobalTelemetry = getGlobalTelemetryIntegration();
35658
35831
  const stopConditions = asArray(stopWhen);
35659
35832
  const totalTimeoutMs = getTotalTimeoutMs(timeout);
35660
35833
  const stepTimeoutMs = getStepTimeoutMs(timeout);
@@ -35685,6 +35858,7 @@ async function generateText({
35685
35858
  prompt,
35686
35859
  messages
35687
35860
  });
35861
+ const globalTelemetry = createGlobalTelemetry(telemetry == null ? void 0 : telemetry.integrations);
35688
35862
  await notify({
35689
35863
  event: {
35690
35864
  model: modelInfo,
@@ -35714,7 +35888,10 @@ async function generateText({
35714
35888
  metadata: telemetry == null ? void 0 : telemetry.metadata,
35715
35889
  experimental_context
35716
35890
  },
35717
- callbacks: onStart
35891
+ callbacks: [
35892
+ onStart,
35893
+ globalTelemetry.onStart
35894
+ ]
35718
35895
  });
35719
35896
  const tracer = getTracer(telemetry);
35720
35897
  try {
@@ -35759,8 +35936,14 @@ async function generateText({
35759
35936
  experimental_context,
35760
35937
  stepNumber: 0,
35761
35938
  model: modelInfo,
35762
- onToolCallStart,
35763
- onToolCallFinish
35939
+ onToolCallStart: [
35940
+ onToolCallStart,
35941
+ globalTelemetry.onToolCallStart
35942
+ ],
35943
+ onToolCallFinish: [
35944
+ onToolCallFinish,
35945
+ globalTelemetry.onToolCallFinish
35946
+ ]
35764
35947
  });
35765
35948
  const toolContent = [];
35766
35949
  for (const output2 of toolOutputs) {
@@ -35769,7 +35952,7 @@ async function generateText({
35769
35952
  input: output2.input,
35770
35953
  tool: tools == null ? void 0 : tools[output2.toolName],
35771
35954
  output: output2.type === "tool-result" ? output2.output : output2.error,
35772
- errorMode: output2.type === "tool-error" ? "json" : "none"
35955
+ errorMode: output2.type === "tool-error" ? "text" : "none"
35773
35956
  });
35774
35957
  toolContent.push({
35775
35958
  type: "tool-result",
@@ -35886,7 +36069,10 @@ async function generateText({
35886
36069
  metadata: telemetry == null ? void 0 : telemetry.metadata,
35887
36070
  experimental_context
35888
36071
  },
35889
- callbacks: onStepStart
36072
+ callbacks: [
36073
+ onStepStart,
36074
+ globalTelemetry.onStepStart
36075
+ ]
35890
36076
  });
35891
36077
  currentModelResponse = await retry(
35892
36078
  () => {
@@ -36064,8 +36250,14 @@ async function generateText({
36064
36250
  experimental_context,
36065
36251
  stepNumber: steps.length,
36066
36252
  model: stepModelInfo,
36067
- onToolCallStart,
36068
- onToolCallFinish
36253
+ onToolCallStart: [
36254
+ onToolCallStart,
36255
+ globalTelemetry.onToolCallStart
36256
+ ],
36257
+ onToolCallFinish: [
36258
+ onToolCallFinish,
36259
+ globalTelemetry.onToolCallFinish
36260
+ ]
36069
36261
  })
36070
36262
  );
36071
36263
  }
@@ -36132,7 +36324,10 @@ async function generateText({
36132
36324
  model: stepModelInfo.modelId
36133
36325
  });
36134
36326
  steps.push(currentStepResult);
36135
- await notify({ event: currentStepResult, callbacks: onStepFinish });
36327
+ await notify({
36328
+ event: currentStepResult,
36329
+ callbacks: [onStepFinish, globalTelemetry.onStepFinish]
36330
+ });
36136
36331
  } finally {
36137
36332
  if (stepTimeoutId != null) {
36138
36333
  clearTimeout(stepTimeoutId);
@@ -36213,7 +36408,10 @@ async function generateText({
36213
36408
  steps,
36214
36409
  totalUsage
36215
36410
  },
36216
- callbacks: onFinish
36411
+ callbacks: [
36412
+ onFinish,
36413
+ globalTelemetry.onFinish
36414
+ ]
36217
36415
  });
36218
36416
  let resolvedOutput;
36219
36417
  if (lastStep.finishReason === "stop") {
@@ -36832,7 +37030,8 @@ function processUIMessageStream({
36832
37030
  state.message.parts.push({
36833
37031
  type: "file",
36834
37032
  mediaType: chunk.mediaType,
36835
- url: chunk.url
37033
+ url: chunk.url,
37034
+ ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}
36836
37035
  });
36837
37036
  write();
36838
37037
  break;
@@ -37489,7 +37688,8 @@ function runToolsTransformation({
37489
37688
  file: new DefaultGeneratedFileWithType({
37490
37689
  data: chunk.data,
37491
37690
  mediaType: chunk.mediaType
37492
- })
37691
+ }),
37692
+ ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}
37493
37693
  });
37494
37694
  break;
37495
37695
  }
@@ -37877,6 +38077,8 @@ var DefaultStreamTextResult = class {
37877
38077
  this.outputSpecification = output;
37878
38078
  this.includeRawChunks = includeRawChunks;
37879
38079
  this.tools = tools;
38080
+ const createGlobalTelemetry = getGlobalTelemetryIntegration();
38081
+ const globalTelemetry = createGlobalTelemetry(telemetry == null ? void 0 : telemetry.integrations);
37880
38082
  let stepFinish;
37881
38083
  let recordedContent = [];
37882
38084
  const recordedResponseMessages = [];
@@ -37978,7 +38180,11 @@ var DefaultStreamTextResult = class {
37978
38180
  delete activeReasoningContent[part.id];
37979
38181
  }
37980
38182
  if (part.type === "file") {
37981
- recordedContent.push({ type: "file", file: part.file });
38183
+ recordedContent.push({
38184
+ type: "file",
38185
+ file: part.file,
38186
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
38187
+ });
37982
38188
  }
37983
38189
  if (part.type === "source") {
37984
38190
  recordedContent.push(part);
@@ -38024,7 +38230,10 @@ var DefaultStreamTextResult = class {
38024
38230
  },
38025
38231
  providerMetadata: part.providerMetadata
38026
38232
  });
38027
- await notify({ event: currentStepResult, callbacks: onStepFinish });
38233
+ await notify({
38234
+ event: currentStepResult,
38235
+ callbacks: [onStepFinish, globalTelemetry.onStepFinish]
38236
+ });
38028
38237
  logWarnings({
38029
38238
  warnings: recordedWarnings,
38030
38239
  provider: modelInfo.provider,
@@ -38088,7 +38297,10 @@ var DefaultStreamTextResult = class {
38088
38297
  providerMetadata: finalStep.providerMetadata,
38089
38298
  steps: recordedSteps
38090
38299
  },
38091
- callbacks: onFinish
38300
+ callbacks: [
38301
+ onFinish,
38302
+ globalTelemetry.onFinish
38303
+ ]
38092
38304
  });
38093
38305
  rootSpan.setAttributes(
38094
38306
  await selectTelemetryAttributes({
@@ -38245,7 +38457,10 @@ var DefaultStreamTextResult = class {
38245
38457
  ...callbackTelemetryProps,
38246
38458
  experimental_context
38247
38459
  },
38248
- callbacks: onStart
38460
+ callbacks: [
38461
+ onStart,
38462
+ globalTelemetry.onStart
38463
+ ]
38249
38464
  });
38250
38465
  const initialMessages = initialPrompt.messages;
38251
38466
  const initialResponseMessages = [];
@@ -38295,8 +38510,14 @@ var DefaultStreamTextResult = class {
38295
38510
  experimental_context,
38296
38511
  stepNumber: recordedSteps.length,
38297
38512
  model: modelInfo,
38298
- onToolCallStart,
38299
- onToolCallFinish,
38513
+ onToolCallStart: [
38514
+ onToolCallStart,
38515
+ globalTelemetry.onToolCallStart
38516
+ ],
38517
+ onToolCallFinish: [
38518
+ onToolCallFinish,
38519
+ globalTelemetry.onToolCallFinish
38520
+ ],
38300
38521
  onPreliminaryToolResult: (result2) => {
38301
38522
  toolExecutionStepStreamController == null ? void 0 : toolExecutionStepStreamController.enqueue(result2);
38302
38523
  }
@@ -38333,7 +38554,7 @@ var DefaultStreamTextResult = class {
38333
38554
  input: output2.input,
38334
38555
  tool: tools == null ? void 0 : tools[output2.toolName],
38335
38556
  output: output2.type === "tool-result" ? output2.output : output2.error,
38336
- errorMode: output2.type === "tool-error" ? "json" : "none"
38557
+ errorMode: output2.type === "tool-error" ? "text" : "none"
38337
38558
  })
38338
38559
  });
38339
38560
  }
@@ -38447,7 +38668,10 @@ var DefaultStreamTextResult = class {
38447
38668
  ...callbackTelemetryProps,
38448
38669
  experimental_context
38449
38670
  },
38450
- callbacks: onStepStart
38671
+ callbacks: [
38672
+ onStepStart,
38673
+ globalTelemetry.onStepStart
38674
+ ]
38451
38675
  });
38452
38676
  const {
38453
38677
  result: { stream: stream2, response, request },
@@ -38523,8 +38747,14 @@ var DefaultStreamTextResult = class {
38523
38747
  generateId: generateId2,
38524
38748
  stepNumber: recordedSteps.length,
38525
38749
  model: stepModelInfo,
38526
- onToolCallStart,
38527
- onToolCallFinish
38750
+ onToolCallStart: [
38751
+ onToolCallStart,
38752
+ globalTelemetry.onToolCallStart
38753
+ ],
38754
+ onToolCallFinish: [
38755
+ onToolCallFinish,
38756
+ globalTelemetry.onToolCallFinish
38757
+ ]
38528
38758
  });
38529
38759
  const stepRequest = ((_i = include == null ? void 0 : include.requestBody) != null ? _i : true) ? request != null ? request : {} : { ...request, body: void 0 };
38530
38760
  const stepToolCalls = [];
@@ -39106,7 +39336,8 @@ var DefaultStreamTextResult = class {
39106
39336
  controller.enqueue({
39107
39337
  type: "file",
39108
39338
  mediaType: part.file.mediaType,
39109
- url: `data:${part.file.mediaType};base64,${part.file.base64}`
39339
+ url: `data:${part.file.mediaType};base64,${part.file.base64}`,
39340
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
39110
39341
  });
39111
39342
  break;
39112
39343
  }
@@ -41428,7 +41659,7 @@ var openaiFailedResponseHandler = createJsonErrorResponseHandler$1({
41428
41659
  function getOpenAILanguageModelCapabilities(modelId) {
41429
41660
  const supportsFlexProcessing = modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat");
41430
41661
  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");
41431
- 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");
41662
+ const isReasoningModel = modelId.startsWith("o1") || modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat");
41432
41663
  const supportsNonReasoningParameters = modelId.startsWith("gpt-5.1") || modelId.startsWith("gpt-5.2");
41433
41664
  const systemMessageMode = isReasoningModel ? "developer" : "system";
41434
41665
  return {
@@ -43335,6 +43566,30 @@ var codeInterpreterToolFactory = createProviderToolFactoryWithOutputSchema({
43335
43566
  var codeInterpreter = (args = {}) => {
43336
43567
  return codeInterpreterToolFactory(args);
43337
43568
  };
43569
+ var customArgsSchema = lazySchema(
43570
+ () => zodSchema(
43571
+ object$2({
43572
+ name: string(),
43573
+ description: string().optional(),
43574
+ format: union([
43575
+ object$2({
43576
+ type: literal("grammar"),
43577
+ syntax: _enum(["regex", "lark"]),
43578
+ definition: string()
43579
+ }),
43580
+ object$2({
43581
+ type: literal("text")
43582
+ })
43583
+ ]).optional()
43584
+ })
43585
+ )
43586
+ );
43587
+ var customInputSchema = lazySchema(() => zodSchema(string()));
43588
+ var customToolFactory = createProviderToolFactory({
43589
+ id: "openai.custom",
43590
+ inputSchema: customInputSchema
43591
+ });
43592
+ var customTool = (args) => customToolFactory(args);
43338
43593
  var comparisonFilterSchema = object$2({
43339
43594
  key: string(),
43340
43595
  type: _enum(["eq", "ne", "gt", "gte", "lt", "lte", "in", "nin"]),
@@ -43687,6 +43942,16 @@ var openaiTools = {
43687
43942
  *
43688
43943
  */
43689
43944
  applyPatch,
43945
+ /**
43946
+ * Custom tools let callers constrain model output to a grammar (regex or
43947
+ * Lark syntax). The model returns a `custom_tool_call` output item whose
43948
+ * `input` field is a string matching the specified grammar.
43949
+ *
43950
+ * @param name - The name of the custom tool.
43951
+ * @param description - An optional description of the tool.
43952
+ * @param format - The output format constraint (grammar type, syntax, and definition).
43953
+ */
43954
+ customTool,
43690
43955
  /**
43691
43956
  * The Code Interpreter tool allows models to write and run Python code in a
43692
43957
  * sandboxed environment to solve complex problems in domains like data analysis,
@@ -43727,7 +43992,7 @@ var openaiTools = {
43727
43992
  * Local shell is a tool that allows agents to run shell commands locally
43728
43993
  * on a machine you or the user provides.
43729
43994
  *
43730
- * Supported models: `gpt-5-codex` and `codex-mini-latest`
43995
+ * Supported models: `gpt-5-codex`
43731
43996
  */
43732
43997
  localShell,
43733
43998
  /**
@@ -43825,9 +44090,10 @@ async function convertToOpenAIResponsesInput({
43825
44090
  hasConversation = false,
43826
44091
  hasLocalShellTool = false,
43827
44092
  hasShellTool = false,
43828
- hasApplyPatchTool = false
44093
+ hasApplyPatchTool = false,
44094
+ customProviderToolNames
43829
44095
  }) {
43830
- var _a10, _b9, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
44096
+ var _a10, _b9, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
43831
44097
  const input = [];
43832
44098
  const warnings = [];
43833
44099
  const processedApprovalIds = /* @__PURE__ */ new Set();
@@ -43996,6 +44262,16 @@ async function convertToOpenAIResponsesInput({
43996
44262
  });
43997
44263
  break;
43998
44264
  }
44265
+ if (customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) {
44266
+ input.push({
44267
+ type: "custom_tool_call",
44268
+ call_id: part.toolCallId,
44269
+ name: resolvedToolName,
44270
+ input: typeof part.input === "string" ? part.input : JSON.stringify(part.input),
44271
+ id: id2
44272
+ });
44273
+ break;
44274
+ }
43999
44275
  input.push({
44000
44276
  type: "function_call",
44001
44277
  call_id: part.toolCallId,
@@ -44200,6 +44476,61 @@ async function convertToOpenAIResponsesInput({
44200
44476
  });
44201
44477
  continue;
44202
44478
  }
44479
+ if (customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) {
44480
+ let outputValue;
44481
+ switch (output.type) {
44482
+ case "text":
44483
+ case "error-text":
44484
+ outputValue = output.value;
44485
+ break;
44486
+ case "execution-denied":
44487
+ outputValue = (_l = output.reason) != null ? _l : "Tool execution denied.";
44488
+ break;
44489
+ case "json":
44490
+ case "error-json":
44491
+ outputValue = JSON.stringify(output.value);
44492
+ break;
44493
+ case "content":
44494
+ outputValue = output.value.map((item) => {
44495
+ var _a22;
44496
+ switch (item.type) {
44497
+ case "text":
44498
+ return { type: "input_text", text: item.text };
44499
+ case "image-data":
44500
+ return {
44501
+ type: "input_image",
44502
+ image_url: `data:${item.mediaType};base64,${item.data}`
44503
+ };
44504
+ case "image-url":
44505
+ return {
44506
+ type: "input_image",
44507
+ image_url: item.url
44508
+ };
44509
+ case "file-data":
44510
+ return {
44511
+ type: "input_file",
44512
+ filename: (_a22 = item.filename) != null ? _a22 : "data",
44513
+ file_data: `data:${item.mediaType};base64,${item.data}`
44514
+ };
44515
+ default:
44516
+ warnings.push({
44517
+ type: "other",
44518
+ message: `unsupported custom tool content part type: ${item.type}`
44519
+ });
44520
+ return void 0;
44521
+ }
44522
+ }).filter(isNonNullable);
44523
+ break;
44524
+ default:
44525
+ outputValue = "";
44526
+ }
44527
+ input.push({
44528
+ type: "custom_tool_call_output",
44529
+ call_id: part.toolCallId,
44530
+ output: outputValue
44531
+ });
44532
+ continue;
44533
+ }
44203
44534
  let contentValue;
44204
44535
  switch (output.type) {
44205
44536
  case "text":
@@ -44207,7 +44538,7 @@ async function convertToOpenAIResponsesInput({
44207
44538
  contentValue = output.value;
44208
44539
  break;
44209
44540
  case "execution-denied":
44210
- contentValue = (_l = output.reason) != null ? _l : "Tool execution denied.";
44541
+ contentValue = (_m = output.reason) != null ? _m : "Tool execution denied.";
44211
44542
  break;
44212
44543
  case "json":
44213
44544
  case "error-json":
@@ -44416,6 +44747,13 @@ var openaiResponsesChunkSchema = lazySchema(
44416
44747
  })
44417
44748
  ])
44418
44749
  }),
44750
+ object$2({
44751
+ type: literal("custom_tool_call"),
44752
+ id: string(),
44753
+ call_id: string(),
44754
+ name: string(),
44755
+ input: string()
44756
+ }),
44419
44757
  object$2({
44420
44758
  type: literal("shell_call"),
44421
44759
  id: string(),
@@ -44468,6 +44806,14 @@ var openaiResponsesChunkSchema = lazySchema(
44468
44806
  arguments: string(),
44469
44807
  status: literal("completed")
44470
44808
  }),
44809
+ object$2({
44810
+ type: literal("custom_tool_call"),
44811
+ id: string(),
44812
+ call_id: string(),
44813
+ name: string(),
44814
+ input: string(),
44815
+ status: literal("completed")
44816
+ }),
44471
44817
  object$2({
44472
44818
  type: literal("code_interpreter_call"),
44473
44819
  id: string(),
@@ -44651,6 +44997,12 @@ var openaiResponsesChunkSchema = lazySchema(
44651
44997
  output_index: number$1(),
44652
44998
  delta: string()
44653
44999
  }),
45000
+ object$2({
45001
+ type: literal("response.custom_tool_call_input.delta"),
45002
+ item_id: string(),
45003
+ output_index: number$1(),
45004
+ delta: string()
45005
+ }),
44654
45006
  object$2({
44655
45007
  type: literal("response.image_generation_call.partial_image"),
44656
45008
  item_id: string(),
@@ -44898,6 +45250,13 @@ var openaiResponsesResponseSchema = lazySchema(
44898
45250
  arguments: string(),
44899
45251
  id: string()
44900
45252
  }),
45253
+ object$2({
45254
+ type: literal("custom_tool_call"),
45255
+ call_id: string(),
45256
+ name: string(),
45257
+ input: string(),
45258
+ id: string()
45259
+ }),
44901
45260
  object$2({
44902
45261
  type: literal("computer_call"),
44903
45262
  id: string(),
@@ -45181,14 +45540,18 @@ var openaiLanguageModelResponsesOptionsSchema = lazySchema(
45181
45540
  );
45182
45541
  async function prepareResponsesTools({
45183
45542
  tools,
45184
- toolChoice
45543
+ toolChoice,
45544
+ toolNameMapping,
45545
+ customProviderToolNames
45185
45546
  }) {
45547
+ var _a10;
45186
45548
  tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
45187
45549
  const toolWarnings = [];
45188
45550
  if (tools == null) {
45189
45551
  return { tools: void 0, toolChoice: void 0, toolWarnings };
45190
45552
  }
45191
45553
  const openaiTools2 = [];
45554
+ const resolvedCustomProviderToolNames = customProviderToolNames != null ? customProviderToolNames : /* @__PURE__ */ new Set();
45192
45555
  for (const tool2 of tools) {
45193
45556
  switch (tool2.type) {
45194
45557
  case "function":
@@ -45330,6 +45693,20 @@ async function prepareResponsesTools({
45330
45693
  });
45331
45694
  break;
45332
45695
  }
45696
+ case "openai.custom": {
45697
+ const args = await validateTypes$1({
45698
+ value: tool2.args,
45699
+ schema: customArgsSchema
45700
+ });
45701
+ openaiTools2.push({
45702
+ type: "custom",
45703
+ name: args.name,
45704
+ description: args.description,
45705
+ format: args.format
45706
+ });
45707
+ resolvedCustomProviderToolNames.add(args.name);
45708
+ break;
45709
+ }
45333
45710
  }
45334
45711
  break;
45335
45712
  }
@@ -45350,12 +45727,14 @@ async function prepareResponsesTools({
45350
45727
  case "none":
45351
45728
  case "required":
45352
45729
  return { tools: openaiTools2, toolChoice: type2, toolWarnings };
45353
- case "tool":
45730
+ case "tool": {
45731
+ const resolvedToolName = (_a10 = toolNameMapping == null ? void 0 : toolNameMapping.toProviderToolName(toolChoice.toolName)) != null ? _a10 : toolChoice.toolName;
45354
45732
  return {
45355
45733
  tools: openaiTools2,
45356
- 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 },
45734
+ 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 },
45357
45735
  toolWarnings
45358
45736
  };
45737
+ }
45359
45738
  default: {
45360
45739
  const _exhaustiveCheck = type2;
45361
45740
  throw new UnsupportedFunctionalityError$1({
@@ -45504,7 +45883,19 @@ var OpenAIResponsesLanguageModel = class {
45504
45883
  "openai.web_search_preview": "web_search_preview",
45505
45884
  "openai.mcp": "mcp",
45506
45885
  "openai.apply_patch": "apply_patch"
45507
- }
45886
+ },
45887
+ resolveProviderToolName: (tool2) => tool2.id === "openai.custom" ? tool2.args.name : void 0
45888
+ });
45889
+ const customProviderToolNames = /* @__PURE__ */ new Set();
45890
+ const {
45891
+ tools: openaiTools2,
45892
+ toolChoice: openaiToolChoice,
45893
+ toolWarnings
45894
+ } = await prepareResponsesTools({
45895
+ tools,
45896
+ toolChoice,
45897
+ toolNameMapping,
45898
+ customProviderToolNames
45508
45899
  });
45509
45900
  const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({
45510
45901
  prompt,
@@ -45516,7 +45907,8 @@ var OpenAIResponsesLanguageModel = class {
45516
45907
  hasConversation: (openaiOptions == null ? void 0 : openaiOptions.conversation) != null,
45517
45908
  hasLocalShellTool: hasOpenAITool("openai.local_shell"),
45518
45909
  hasShellTool: hasOpenAITool("openai.shell"),
45519
- hasApplyPatchTool: hasOpenAITool("openai.apply_patch")
45910
+ hasApplyPatchTool: hasOpenAITool("openai.apply_patch"),
45911
+ customProviderToolNames: customProviderToolNames.size > 0 ? customProviderToolNames : void 0
45520
45912
  });
45521
45913
  warnings.push(...inputWarnings);
45522
45914
  const strictJsonSchema = (_d = openaiOptions == null ? void 0 : openaiOptions.strictJsonSchema) != null ? _d : true;
@@ -45649,14 +46041,6 @@ var OpenAIResponsesLanguageModel = class {
45649
46041
  });
45650
46042
  delete baseArgs.service_tier;
45651
46043
  }
45652
- const {
45653
- tools: openaiTools2,
45654
- toolChoice: openaiToolChoice,
45655
- toolWarnings
45656
- } = await prepareResponsesTools({
45657
- tools,
45658
- toolChoice
45659
- });
45660
46044
  const shellToolEnvType = (_i = (_h = (_g = tools == null ? void 0 : tools.find(
45661
46045
  (tool2) => tool2.type === "provider" && tool2.id === "openai.shell"
45662
46046
  )) == null ? void 0 : _g.args) == null ? void 0 : _h.environment) == null ? void 0 : _i.type;
@@ -45906,6 +46290,22 @@ var OpenAIResponsesLanguageModel = class {
45906
46290
  });
45907
46291
  break;
45908
46292
  }
46293
+ case "custom_tool_call": {
46294
+ hasFunctionCall = true;
46295
+ const toolName = toolNameMapping.toCustomToolName(part.name);
46296
+ content.push({
46297
+ type: "tool-call",
46298
+ toolCallId: part.call_id,
46299
+ toolName,
46300
+ input: JSON.stringify(part.input),
46301
+ providerMetadata: {
46302
+ [providerOptionsName]: {
46303
+ itemId: part.id
46304
+ }
46305
+ }
46306
+ });
46307
+ break;
46308
+ }
45909
46309
  case "web_search_call": {
45910
46310
  content.push({
45911
46311
  type: "tool-call",
@@ -46164,6 +46564,19 @@ var OpenAIResponsesLanguageModel = class {
46164
46564
  id: value.item.call_id,
46165
46565
  toolName: value.item.name
46166
46566
  });
46567
+ } else if (value.item.type === "custom_tool_call") {
46568
+ const toolName = toolNameMapping.toCustomToolName(
46569
+ value.item.name
46570
+ );
46571
+ ongoingToolCalls[value.output_index] = {
46572
+ toolName,
46573
+ toolCallId: value.item.call_id
46574
+ };
46575
+ controller.enqueue({
46576
+ type: "tool-input-start",
46577
+ id: value.item.call_id,
46578
+ toolName
46579
+ });
46167
46580
  } else if (value.item.type === "web_search_call") {
46168
46581
  ongoingToolCalls[value.output_index] = {
46169
46582
  toolName: toolNameMapping.toCustomToolName(
@@ -46348,6 +46761,27 @@ var OpenAIResponsesLanguageModel = class {
46348
46761
  }
46349
46762
  }
46350
46763
  });
46764
+ } else if (value.item.type === "custom_tool_call") {
46765
+ ongoingToolCalls[value.output_index] = void 0;
46766
+ hasFunctionCall = true;
46767
+ const toolName = toolNameMapping.toCustomToolName(
46768
+ value.item.name
46769
+ );
46770
+ controller.enqueue({
46771
+ type: "tool-input-end",
46772
+ id: value.item.call_id
46773
+ });
46774
+ controller.enqueue({
46775
+ type: "tool-call",
46776
+ toolCallId: value.item.call_id,
46777
+ toolName,
46778
+ input: JSON.stringify(value.item.input),
46779
+ providerMetadata: {
46780
+ [providerOptionsName]: {
46781
+ itemId: value.item.id
46782
+ }
46783
+ }
46784
+ });
46351
46785
  } else if (value.item.type === "web_search_call") {
46352
46786
  ongoingToolCalls[value.output_index] = void 0;
46353
46787
  controller.enqueue({
@@ -46597,6 +47031,15 @@ var OpenAIResponsesLanguageModel = class {
46597
47031
  delta: value.delta
46598
47032
  });
46599
47033
  }
47034
+ } else if (isResponseCustomToolCallInputDeltaChunk(value)) {
47035
+ const toolCall = ongoingToolCalls[value.output_index];
47036
+ if (toolCall != null) {
47037
+ controller.enqueue({
47038
+ type: "tool-input-delta",
47039
+ id: toolCall.toolCallId,
47040
+ delta: value.delta
47041
+ });
47042
+ }
46600
47043
  } else if (isResponseApplyPatchCallOperationDiffDeltaChunk(value)) {
46601
47044
  const toolCall = ongoingToolCalls[value.output_index];
46602
47045
  if (toolCall == null ? void 0 : toolCall.applyPatch) {
@@ -46857,6 +47300,9 @@ function isResponseCreatedChunk(chunk) {
46857
47300
  function isResponseFunctionCallArgumentsDeltaChunk(chunk) {
46858
47301
  return chunk.type === "response.function_call_arguments.delta";
46859
47302
  }
47303
+ function isResponseCustomToolCallInputDeltaChunk(chunk) {
47304
+ return chunk.type === "response.custom_tool_call_input.delta";
47305
+ }
46860
47306
  function isResponseImageGenerationCallPartialImageChunk(chunk) {
46861
47307
  return chunk.type === "response.image_generation_call.partial_image";
46862
47308
  }
@@ -47238,7 +47684,7 @@ var OpenAITranscriptionModel = class {
47238
47684
  };
47239
47685
  }
47240
47686
  };
47241
- var VERSION$2 = "3.0.36";
47687
+ var VERSION$2 = "3.0.41";
47242
47688
  function createOpenAI(options = {}) {
47243
47689
  var _a10, _b9;
47244
47690
  const baseURL = (_a10 = withoutTrailingSlash$1(
@@ -49058,9 +49504,13 @@ function generateReActToolsPrompt(tools) {
49058
49504
  if (toolEntries.length === 0) {
49059
49505
  return "";
49060
49506
  }
49061
- let prompt = "\n\n# 工具调用\n\n";
49062
- prompt += "你可以根据需要调用以下工具:\n\n";
49063
- prompt += "<tools>\n";
49507
+ let prompt = `
49508
+ # 工具调用
49509
+
49510
+ 你可以根据需要调用以下工具:
49511
+
49512
+ <tools>
49513
+ `;
49064
49514
  toolEntries.forEach(([toolName, tool2]) => {
49065
49515
  const toolInfo = tool2;
49066
49516
  const description2 = toolInfo.description || "无描述";
@@ -49073,23 +49523,36 @@ function generateReActToolsPrompt(tools) {
49073
49523
  prompt += `${JSON.stringify(toolJson, null, 2)}
49074
49524
  `;
49075
49525
  });
49076
- prompt += "</tools>\n\n";
49077
- prompt += "## 工具调用格式\n\n";
49078
- prompt += "要调用工具,请使用以下 XML 格式:\n";
49079
- prompt += "Thought: [你的思考过程]\n";
49080
- prompt += '<tool_call>{"name": "toolName", "arguments": {"arg1": "value1"}}</tool_call>\n\n';
49081
- prompt += "工具执行后,你将收到 <tool_response> 格式的结果。你可以继续思考或调用其他工具。\n\n";
49082
- prompt += "## 使用示例\n\n";
49083
- prompt += '如果用户要求"获取今天的日期",你可以这样调用工具:\n';
49084
- prompt += "Thought: 用户想要获取今天的日期,我需要调用日期相关的工具。\n";
49085
- prompt += '<tool_call>{"name": "get-today", "arguments": {}}</tool_call>\n\n';
49086
- prompt += "然后等待工具返回结果(Observation),再根据结果给出最终答案。\n\n";
49087
- prompt += "## 任务完成\n\n";
49088
- prompt += "当任务完成或无法继续时,直接给出最终答案即可。\n\n";
49089
- prompt += "**重要提示**:\n";
49090
- prompt += "- 必须严格按照 XML 格式调用工具\n";
49091
- prompt += "- arguments 必须是有效的 JSON 格式\n";
49092
- prompt += "- 如果不需要调用工具,直接给出最终答案即可\n";
49526
+ prompt += `
49527
+ </tools>
49528
+
49529
+ ## 工具调用格式
49530
+
49531
+ 要调用工具,请使用以下 XML 格式:
49532
+ Thought: [你的思考过程]
49533
+ <tool_call>
49534
+ {"name": "toolName", "arguments": {"arg1": "value1"}}
49535
+ </tool_call>
49536
+
49537
+ 工具执行后,你将收到 <tool_response> 格式的结果。你可以继续思考或调用其他工具。
49538
+
49539
+ ## 使用示例
49540
+
49541
+ 如果用户要求"获取今天的日期",你可以这样调用工具:
49542
+ Thought: 用户想要获取今天的日期,我需要调用日期相关的工具。
49543
+ <tool_call>{"name": "get-today", "arguments": {}}</tool_call>
49544
+
49545
+ 然后等待工具返回结果(Observation),再根据结果给出最终答案。
49546
+
49547
+ ## 任务完成
49548
+
49549
+ 当任务完成或无法继续时,直接给出最终答案即可。
49550
+
49551
+ **重要提示**:
49552
+ - 必须严格按照 XML 格式调用工具
49553
+ - arguments 必须是有效的 JSON 格式
49554
+ - 如果不需要调用工具,直接给出最终答案即可
49555
+ `;
49093
49556
  return prompt;
49094
49557
  }
49095
49558
  function parseReActAction(text2, availableTools) {
@@ -49696,6 +50159,171 @@ ${observationText}
49696
50159
  return this._chat(streamText, options);
49697
50160
  }
49698
50161
  }
50162
+ const MSG_TOOL_CALL = "next-sdk:tool-call";
50163
+ const MSG_TOOL_RESPONSE = "next-sdk:tool-response";
50164
+ const MSG_PAGE_READY = "next-sdk:page-ready";
50165
+ const MSG_PAGE_LEAVE = "next-sdk:page-leave";
50166
+ const MSG_REMOTER_READY = "next-sdk:remoter-ready";
50167
+ const MSG_ROUTE_STATE_INITIAL = "next-sdk:route-state-initial";
50168
+ const activePages = /* @__PURE__ */ new Map();
50169
+ const broadcastTargets = /* @__PURE__ */ new Set();
50170
+ function initBroadcastTargets() {
50171
+ if (typeof window !== "undefined") {
50172
+ broadcastTargets.add({ win: window, origin: window.location.origin || "*" });
50173
+ }
50174
+ }
50175
+ initBroadcastTargets();
50176
+ function broadcastRouteChange(type2, route) {
50177
+ const msg = { type: type2, route };
50178
+ broadcastTargets.forEach(({ win, origin }) => {
50179
+ try {
50180
+ win.postMessage(msg, origin);
50181
+ } catch {
50182
+ }
50183
+ });
50184
+ }
50185
+ function setupIframeRemoterBridge() {
50186
+ if (typeof window === "undefined") return;
50187
+ window.addEventListener("message", (event) => {
50188
+ if (event.data?.type !== MSG_REMOTER_READY || !event.source) return;
50189
+ if (event.origin !== window.location.origin) return;
50190
+ const target = event.source;
50191
+ broadcastTargets.add({ win: target, origin: event.origin || "*" });
50192
+ const payload = {
50193
+ type: MSG_ROUTE_STATE_INITIAL,
50194
+ toolRouteMap: Array.from(toolRouteMap.entries()),
50195
+ activeRoutes: Array.from(activePages.keys())
50196
+ };
50197
+ try {
50198
+ target.postMessage(payload, event.origin || "*");
50199
+ } catch {
50200
+ }
50201
+ });
50202
+ }
50203
+ setupIframeRemoterBridge();
50204
+ const toolRouteMap = /* @__PURE__ */ new Map();
50205
+ function getToolRouteMap() {
50206
+ return new Map(toolRouteMap);
50207
+ }
50208
+ function getActiveRoutes() {
50209
+ return new Set(activePages.keys());
50210
+ }
50211
+ let _navigator = null;
50212
+ function setNavigator(fn) {
50213
+ _navigator = fn;
50214
+ }
50215
+ function buildPageHandler(name16, route, timeout = 3e4) {
50216
+ return (input) => {
50217
+ const callId = randomUUID();
50218
+ return new Promise((resolve2, reject) => {
50219
+ let timer;
50220
+ let readyHandler;
50221
+ const cleanup = () => {
50222
+ clearTimeout(timer);
50223
+ window.removeEventListener("message", responseHandler);
50224
+ if (readyHandler) {
50225
+ window.removeEventListener("message", readyHandler);
50226
+ }
50227
+ };
50228
+ timer = setTimeout(() => {
50229
+ cleanup();
50230
+ reject(new Error(`工具 [${name16}] 调用超时 (${timeout}ms),请检查目标页面是否正确调用了 registerPageTool`));
50231
+ }, timeout);
50232
+ const responseHandler = (event) => {
50233
+ if (event.source === window && event.data?.type === MSG_TOOL_RESPONSE && event.data.callId === callId) {
50234
+ cleanup();
50235
+ event.data.error ? reject(new Error(event.data.error)) : resolve2(event.data.result);
50236
+ }
50237
+ };
50238
+ window.addEventListener("message", responseHandler);
50239
+ const sendCall = () => {
50240
+ window.postMessage({ type: MSG_TOOL_CALL, callId, toolName: name16, route, input }, window.location.origin || "*");
50241
+ };
50242
+ let callSent = false;
50243
+ const sendCallOnce = () => {
50244
+ if (callSent) return;
50245
+ callSent = true;
50246
+ sendCall();
50247
+ };
50248
+ const run = async () => {
50249
+ try {
50250
+ if (activePages.get(route)) {
50251
+ sendCallOnce();
50252
+ return;
50253
+ }
50254
+ readyHandler = (event) => {
50255
+ if (event.source === window && event.data?.type === MSG_PAGE_READY && event.data.route === route) {
50256
+ window.removeEventListener("message", readyHandler);
50257
+ sendCallOnce();
50258
+ }
50259
+ };
50260
+ window.addEventListener("message", readyHandler);
50261
+ if (_navigator) {
50262
+ await _navigator(route);
50263
+ }
50264
+ if (activePages.get(route)) {
50265
+ window.removeEventListener("message", readyHandler);
50266
+ sendCallOnce();
50267
+ }
50268
+ } catch (err) {
50269
+ cleanup();
50270
+ reject(err instanceof Error ? err : new Error(String(err)));
50271
+ }
50272
+ };
50273
+ void run();
50274
+ });
50275
+ };
50276
+ }
50277
+ function withPageTools(server) {
50278
+ return new Proxy(server, {
50279
+ get(target, prop, receiver) {
50280
+ if (prop === "registerTool") {
50281
+ return (name16, config2, handlerOrRoute) => {
50282
+ const rawRegister = target.registerTool.bind(target);
50283
+ if (typeof handlerOrRoute === "function") {
50284
+ return rawRegister(name16, config2, handlerOrRoute);
50285
+ }
50286
+ const { route, timeout } = handlerOrRoute;
50287
+ toolRouteMap.set(name16, route);
50288
+ return rawRegister(name16, config2, buildPageHandler(name16, route, timeout));
50289
+ };
50290
+ }
50291
+ return Reflect.get(target, prop, receiver);
50292
+ }
50293
+ });
50294
+ }
50295
+ function registerPageTool(options) {
50296
+ const { route: routeOption, handlers } = options;
50297
+ const normalizeRoute = (value) => value.replace(/\/+$/, "") || "/";
50298
+ const route = normalizeRoute(routeOption ?? window.location.pathname);
50299
+ const handleMessage = async (event) => {
50300
+ if (event.source !== window || event.data?.type !== MSG_TOOL_CALL || normalizeRoute(String(event.data?.route ?? "")) !== route || !(event.data.toolName in handlers)) {
50301
+ return;
50302
+ }
50303
+ const { callId, toolName, input } = event.data;
50304
+ try {
50305
+ const result = await handlers[toolName](input);
50306
+ window.postMessage({ type: MSG_TOOL_RESPONSE, callId, result }, window.location.origin || "*");
50307
+ } catch (err) {
50308
+ window.postMessage(
50309
+ {
50310
+ type: MSG_TOOL_RESPONSE,
50311
+ callId,
50312
+ error: err instanceof Error ? err.message : String(err)
50313
+ },
50314
+ window.location.origin || "*"
50315
+ );
50316
+ }
50317
+ };
50318
+ activePages.set(route, true);
50319
+ window.addEventListener("message", handleMessage);
50320
+ broadcastRouteChange(MSG_PAGE_READY, route);
50321
+ return () => {
50322
+ activePages.delete(route);
50323
+ window.removeEventListener("message", handleMessage);
50324
+ broadcastRouteChange(MSG_PAGE_LEAVE, route);
50325
+ };
50326
+ }
49699
50327
  const MAIN_SKILL_PATH_REG = /^\.\/[^/]+\/SKILL\.md$/;
49700
50328
  const FRONT_MATTER_BLOCK_REG = /^---\s*\n([\s\S]+?)\s*\n---/;
49701
50329
  function parseSkillFrontMatter(content) {
@@ -49708,14 +50336,27 @@ function parseSkillFrontMatter(content) {
49708
50336
  const description2 = descMatch?.[1]?.trim();
49709
50337
  return name16 && description2 ? { name: name16, description: description2 } : null;
49710
50338
  }
50339
+ function normalizeSkillModuleKeys(modules) {
50340
+ const result = {};
50341
+ for (const [key, content] of Object.entries(modules)) {
50342
+ const normalizedKey = key.replace(/\\/g, "/");
50343
+ const skillsIndex = normalizedKey.lastIndexOf("skills/");
50344
+ const relativePath = skillsIndex >= 0 ? normalizedKey.slice(skillsIndex + 7) : normalizedKey;
50345
+ const standardPath = relativePath.startsWith("./") ? relativePath : `./${relativePath}`;
50346
+ result[standardPath] = content;
50347
+ }
50348
+ return result;
50349
+ }
49711
50350
  function getMainSkillPaths(modules) {
49712
- return Object.keys(modules).filter((path) => MAIN_SKILL_PATH_REG.test(path));
50351
+ const normalized = normalizeSkillModuleKeys(modules);
50352
+ return Object.keys(normalized).filter((path) => MAIN_SKILL_PATH_REG.test(path));
49713
50353
  }
49714
50354
  function getSkillOverviews(modules) {
49715
- const mainPaths = getMainSkillPaths(modules);
50355
+ const normalized = normalizeSkillModuleKeys(modules);
50356
+ const mainPaths = Object.keys(normalized).filter((path) => MAIN_SKILL_PATH_REG.test(path));
49716
50357
  const list = [];
49717
50358
  for (const path of mainPaths) {
49718
- const content = modules[path];
50359
+ const content = normalized[path];
49719
50360
  if (!content) continue;
49720
50361
  const parsed = parseSkillFrontMatter(content);
49721
50362
  if (!parsed) continue;
@@ -49737,34 +50378,38 @@ ${lines.join("\n")}
49737
50378
  当需要用到某技能时,请使用 get_skill_content 工具获取该技能的完整文档内容。`;
49738
50379
  }
49739
50380
  function getSkillMdPaths(modules) {
49740
- return Object.keys(modules);
50381
+ const normalized = normalizeSkillModuleKeys(modules);
50382
+ return Object.keys(normalized);
49741
50383
  }
49742
50384
  function getSkillMdContent(modules, path) {
49743
- return modules[path];
50385
+ const normalized = normalizeSkillModuleKeys(modules);
50386
+ return normalized[path];
49744
50387
  }
49745
50388
  function getMainSkillPathByName(modules, name16) {
49746
50389
  return getMainSkillPaths(modules).find((p) => p.startsWith(`./${name16}/SKILL.md`));
49747
50390
  }
50391
+ const SKILL_INPUT_SCHEMA = objectType({
50392
+ skillName: stringType().optional().describe("技能名称,与目录名一致,如 calculator"),
50393
+ path: stringType().optional().describe("文档相对路径,如 ./calculator/SKILL.md 或 ./product-guide/reference/xxx.json")
50394
+ });
49748
50395
  function createSkillTools(modules) {
50396
+ const normalizedModules = normalizeSkillModuleKeys(modules);
49749
50397
  const getSkillContent = tool({
49750
50398
  description: "根据技能名称或文档路径获取该技能的完整文档内容。传入 skillName(如 calculator)或 path(如 ./calculator/SKILL.md)。支持 .md、.json、.xml 等各类文本格式文件。",
49751
- inputSchema: objectType({
49752
- skillName: stringType().optional().describe("技能名称,与目录名一致,如 calculator"),
49753
- path: stringType().optional().describe("文档相对路径,如 ./calculator/SKILL.md 或 ./product-guide/reference/xxx.json")
49754
- }),
50399
+ inputSchema: SKILL_INPUT_SCHEMA,
49755
50400
  execute: (args) => {
49756
50401
  const { skillName, path: pathArg } = args;
49757
50402
  let content;
49758
50403
  if (pathArg) {
49759
- content = getSkillMdContent(modules, pathArg);
50404
+ content = getSkillMdContent(normalizedModules, pathArg);
49760
50405
  } else if (skillName) {
49761
- const mainPath = getMainSkillPathByName(modules, skillName);
49762
- content = mainPath ? getSkillMdContent(modules, mainPath) : void 0;
50406
+ const mainPath = getMainSkillPathByName(normalizedModules, skillName);
50407
+ content = mainPath ? getSkillMdContent(normalizedModules, mainPath) : void 0;
49763
50408
  }
49764
50409
  if (content === void 0) {
49765
50410
  return { error: "未找到对应技能文档", skillName: skillName ?? pathArg };
49766
50411
  }
49767
- return { content, path: pathArg ?? getMainSkillPathByName(modules, skillName) };
50412
+ return { content, path: pathArg ?? getMainSkillPathByName(normalizedModules, skillName) };
49768
50413
  }
49769
50414
  });
49770
50415
  return {
@@ -49779,6 +50424,9 @@ export {
49779
50424
  ExtensionClientTransport,
49780
50425
  ExtensionPageServerTransport,
49781
50426
  InMemoryTransport,
50427
+ MSG_PAGE_LEAVE,
50428
+ MSG_REMOTER_READY,
50429
+ MSG_ROUTE_STATE_INITIAL,
49782
50430
  QrCode,
49783
50431
  ResourceTemplate,
49784
50432
  UriTemplate,
@@ -49794,12 +50442,14 @@ export {
49794
50442
  createStreamableHTTPClientTransport,
49795
50443
  formatSkillsForSystemPrompt,
49796
50444
  getAISDKTools,
50445
+ getActiveRoutes,
49797
50446
  getDisplayName,
49798
50447
  getMainSkillPathByName,
49799
50448
  getMainSkillPaths,
49800
50449
  getSkillMdContent,
49801
50450
  getSkillMdPaths,
49802
50451
  getSkillOverviews,
50452
+ getToolRouteMap,
49803
50453
  isMcpClient,
49804
50454
  isMcpServer,
49805
50455
  isMessageChannelClientTransport,
@@ -49807,5 +50457,8 @@ export {
49807
50457
  isSSEClientTransport,
49808
50458
  isStreamableHTTPClientTransport,
49809
50459
  parseSkillFrontMatter,
50460
+ registerPageTool,
50461
+ setNavigator,
50462
+ withPageTools,
49810
50463
  z
49811
50464
  };