@meetsmore-oss/use-ai-server 1.7.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/dist/agents/AISDKAgent.d.ts +29 -6
  2. package/dist/agents/AISDKAgent.d.ts.map +1 -1
  3. package/dist/agents/AISDKAgent.maxSteps.test.d.ts +2 -0
  4. package/dist/agents/AISDKAgent.maxSteps.test.d.ts.map +1 -0
  5. package/dist/agents/toolApproval.d.ts.map +1 -1
  6. package/dist/agents/toolApproval.test.d.ts +2 -0
  7. package/dist/agents/toolApproval.test.d.ts.map +1 -0
  8. package/dist/agents/types.d.ts +5 -0
  9. package/dist/agents/types.d.ts.map +1 -1
  10. package/dist/index.d.ts +6 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +2037 -336
  13. package/dist/instrumentation.d.ts +48 -2
  14. package/dist/instrumentation.d.ts.map +1 -1
  15. package/dist/instrumentation.test.d.ts +1 -1
  16. package/dist/mcp/index.d.ts +2 -0
  17. package/dist/mcp/index.d.ts.map +1 -1
  18. package/dist/mcp/mcpConfirmation.d.ts +23 -0
  19. package/dist/mcp/mcpConfirmation.d.ts.map +1 -0
  20. package/dist/mcp/mcpConfirmation.test.d.ts +2 -0
  21. package/dist/mcp/mcpConfirmation.test.d.ts.map +1 -0
  22. package/dist/mcp/useAIInternalResponse.d.ts +5 -0
  23. package/dist/mcp/useAIInternalResponse.d.ts.map +1 -0
  24. package/dist/mcp/useAIInternalResponse.test.d.ts +2 -0
  25. package/dist/mcp/useAIInternalResponse.test.d.ts.map +1 -0
  26. package/dist/server.d.ts +1 -0
  27. package/dist/server.d.ts.map +1 -1
  28. package/dist/span-processors.integration.test.d.ts +8 -0
  29. package/dist/span-processors.integration.test.d.ts.map +1 -0
  30. package/dist/src/agents/AISDKAgent.d.ts +29 -6
  31. package/dist/src/agents/AISDKAgent.d.ts.map +1 -1
  32. package/dist/src/agents/AISDKAgent.maxSteps.test.d.ts +2 -0
  33. package/dist/src/agents/AISDKAgent.maxSteps.test.d.ts.map +1 -0
  34. package/dist/src/agents/toolApproval.d.ts.map +1 -1
  35. package/dist/src/agents/toolApproval.test.d.ts +2 -0
  36. package/dist/src/agents/toolApproval.test.d.ts.map +1 -0
  37. package/dist/src/agents/types.d.ts +5 -0
  38. package/dist/src/agents/types.d.ts.map +1 -1
  39. package/dist/src/index.d.ts +6 -1
  40. package/dist/src/index.d.ts.map +1 -1
  41. package/dist/src/instrumentation.d.ts +48 -2
  42. package/dist/src/instrumentation.d.ts.map +1 -1
  43. package/dist/src/instrumentation.test.d.ts +1 -1
  44. package/dist/src/mcp/index.d.ts +2 -0
  45. package/dist/src/mcp/index.d.ts.map +1 -1
  46. package/dist/src/mcp/mcpConfirmation.d.ts +23 -0
  47. package/dist/src/mcp/mcpConfirmation.d.ts.map +1 -0
  48. package/dist/src/mcp/mcpConfirmation.test.d.ts +2 -0
  49. package/dist/src/mcp/mcpConfirmation.test.d.ts.map +1 -0
  50. package/dist/src/mcp/useAIInternalResponse.d.ts +5 -0
  51. package/dist/src/mcp/useAIInternalResponse.d.ts.map +1 -0
  52. package/dist/src/mcp/useAIInternalResponse.test.d.ts +2 -0
  53. package/dist/src/mcp/useAIInternalResponse.test.d.ts.map +1 -0
  54. package/dist/src/server.d.ts +1 -0
  55. package/dist/src/server.d.ts.map +1 -1
  56. package/dist/src/span-processors.integration.test.d.ts +8 -0
  57. package/dist/src/span-processors.integration.test.d.ts.map +1 -0
  58. package/dist/src/telemetry.d.ts +41 -0
  59. package/dist/src/telemetry.d.ts.map +1 -0
  60. package/dist/src/telemetry.test.d.ts +2 -0
  61. package/dist/src/telemetry.test.d.ts.map +1 -0
  62. package/dist/src/test-preload.d.ts +4 -0
  63. package/dist/src/test-preload.d.ts.map +1 -1
  64. package/dist/src/tools/defineServerTool.d.ts +54 -0
  65. package/dist/src/tools/defineServerTool.d.ts.map +1 -0
  66. package/dist/src/tools/defineServerTool.test.d.ts +2 -0
  67. package/dist/src/tools/defineServerTool.test.d.ts.map +1 -0
  68. package/dist/src/tools/index.d.ts +4 -0
  69. package/dist/src/tools/index.d.ts.map +1 -0
  70. package/dist/src/tools/serverToolExecutor.d.ts +21 -0
  71. package/dist/src/tools/serverToolExecutor.d.ts.map +1 -0
  72. package/dist/src/tools/serverToolExecutor.test.d.ts +2 -0
  73. package/dist/src/tools/serverToolExecutor.test.d.ts.map +1 -0
  74. package/dist/src/tools/types.d.ts +65 -0
  75. package/dist/src/tools/types.d.ts.map +1 -0
  76. package/dist/src/types.d.ts +35 -0
  77. package/dist/src/types.d.ts.map +1 -1
  78. package/dist/src/utils/index.d.ts +1 -1
  79. package/dist/src/utils/index.d.ts.map +1 -1
  80. package/dist/src/utils/toolConverter.d.ts.map +1 -1
  81. package/dist/src/utils/toolConverter.test.d.ts +2 -0
  82. package/dist/src/utils/toolConverter.test.d.ts.map +1 -0
  83. package/dist/src/utils/toolFilters.d.ts +16 -0
  84. package/dist/src/utils/toolFilters.d.ts.map +1 -1
  85. package/dist/src/utils/toolFilters.test.d.ts +2 -0
  86. package/dist/src/utils/toolFilters.test.d.ts.map +1 -0
  87. package/dist/telemetry.d.ts +41 -0
  88. package/dist/telemetry.d.ts.map +1 -0
  89. package/dist/telemetry.test.d.ts +2 -0
  90. package/dist/telemetry.test.d.ts.map +1 -0
  91. package/dist/test/test-utils.d.ts +1 -0
  92. package/dist/test/test-utils.d.ts.map +1 -1
  93. package/dist/test-preload.d.ts +4 -0
  94. package/dist/test-preload.d.ts.map +1 -1
  95. package/dist/tools/defineServerTool.d.ts +54 -0
  96. package/dist/tools/defineServerTool.d.ts.map +1 -0
  97. package/dist/tools/defineServerTool.test.d.ts +2 -0
  98. package/dist/tools/defineServerTool.test.d.ts.map +1 -0
  99. package/dist/tools/index.d.ts +4 -0
  100. package/dist/tools/index.d.ts.map +1 -0
  101. package/dist/tools/serverToolExecutor.d.ts +21 -0
  102. package/dist/tools/serverToolExecutor.d.ts.map +1 -0
  103. package/dist/tools/serverToolExecutor.test.d.ts +2 -0
  104. package/dist/tools/serverToolExecutor.test.d.ts.map +1 -0
  105. package/dist/tools/types.d.ts +65 -0
  106. package/dist/tools/types.d.ts.map +1 -0
  107. package/dist/tsconfig.tsbuildinfo +1 -1
  108. package/dist/types.d.ts +35 -0
  109. package/dist/types.d.ts.map +1 -1
  110. package/dist/utils/index.d.ts +1 -1
  111. package/dist/utils/index.d.ts.map +1 -1
  112. package/dist/utils/toolConverter.d.ts.map +1 -1
  113. package/dist/utils/toolConverter.test.d.ts +2 -0
  114. package/dist/utils/toolConverter.test.d.ts.map +1 -0
  115. package/dist/utils/toolFilters.d.ts +16 -0
  116. package/dist/utils/toolFilters.d.ts.map +1 -1
  117. package/dist/utils/toolFilters.test.d.ts +2 -0
  118. package/dist/utils/toolFilters.test.d.ts.map +1 -0
  119. package/package.json +5 -4
package/dist/index.js CHANGED
@@ -5,39 +5,60 @@ var __defProp = Object.defineProperty;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ function __accessProp(key) {
9
+ return this[key];
10
+ }
11
+ var __toESMCache_node;
12
+ var __toESMCache_esm;
8
13
  var __toESM = (mod2, isNodeMode, target) => {
14
+ var canCache = mod2 != null && typeof mod2 === "object";
15
+ if (canCache) {
16
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
17
+ var cached = cache.get(mod2);
18
+ if (cached)
19
+ return cached;
20
+ }
9
21
  target = mod2 != null ? __create(__getProtoOf(mod2)) : {};
10
22
  const to = isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target;
11
23
  for (let key of __getOwnPropNames(mod2))
12
24
  if (!__hasOwnProp.call(to, key))
13
25
  __defProp(to, key, {
14
- get: () => mod2[key],
26
+ get: __accessProp.bind(mod2, key),
15
27
  enumerable: true
16
28
  });
29
+ if (canCache)
30
+ cache.set(mod2, to);
17
31
  return to;
18
32
  };
19
- var __moduleCache = /* @__PURE__ */ new WeakMap;
20
33
  var __toCommonJS = (from) => {
21
- var entry = __moduleCache.get(from), desc;
34
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
22
35
  if (entry)
23
36
  return entry;
24
37
  entry = __defProp({}, "__esModule", { value: true });
25
- if (from && typeof from === "object" || typeof from === "function")
26
- __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
27
- get: () => from[key],
28
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
29
- }));
38
+ if (from && typeof from === "object" || typeof from === "function") {
39
+ for (var key of __getOwnPropNames(from))
40
+ if (!__hasOwnProp.call(entry, key))
41
+ __defProp(entry, key, {
42
+ get: __accessProp.bind(from, key),
43
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
44
+ });
45
+ }
30
46
  __moduleCache.set(from, entry);
31
47
  return entry;
32
48
  };
49
+ var __moduleCache;
33
50
  var __commonJS = (cb, mod2) => () => (mod2 || cb((mod2 = { exports: {} }).exports, mod2), mod2.exports);
51
+ var __returnValue = (v) => v;
52
+ function __exportSetter(name, newValue) {
53
+ this[name] = __returnValue.bind(null, newValue);
54
+ }
34
55
  var __export = (target, all) => {
35
56
  for (var name in all)
36
57
  __defProp(target, name, {
37
58
  get: all[name],
38
59
  enumerable: true,
39
60
  configurable: true,
40
- set: (newValue) => all[name] = () => newValue
61
+ set: __exportSetter.bind(all, name)
41
62
  });
42
63
  };
43
64
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
@@ -81212,15 +81233,29 @@ var __getProtoOf2 = Object.getPrototypeOf;
81212
81233
  var __defProp2 = Object.defineProperty;
81213
81234
  var __getOwnPropNames2 = Object.getOwnPropertyNames;
81214
81235
  var __hasOwnProp2 = Object.prototype.hasOwnProperty;
81236
+ function __accessProp2(key) {
81237
+ return this[key];
81238
+ }
81239
+ var __toESMCache_node2;
81240
+ var __toESMCache_esm2;
81215
81241
  var __toESM2 = (mod2, isNodeMode, target) => {
81242
+ var canCache = mod2 != null && typeof mod2 === "object";
81243
+ if (canCache) {
81244
+ var cache = isNodeMode ? __toESMCache_node2 ??= new WeakMap : __toESMCache_esm2 ??= new WeakMap;
81245
+ var cached = cache.get(mod2);
81246
+ if (cached)
81247
+ return cached;
81248
+ }
81216
81249
  target = mod2 != null ? __create2(__getProtoOf2(mod2)) : {};
81217
81250
  const to = isNodeMode || !mod2 || !mod2.__esModule ? __defProp2(target, "default", { value: mod2, enumerable: true }) : target;
81218
81251
  for (let key of __getOwnPropNames2(mod2))
81219
81252
  if (!__hasOwnProp2.call(to, key))
81220
81253
  __defProp2(to, key, {
81221
- get: () => mod2[key],
81254
+ get: __accessProp2.bind(mod2, key),
81222
81255
  enumerable: true
81223
81256
  });
81257
+ if (canCache)
81258
+ cache.set(mod2, to);
81224
81259
  return to;
81225
81260
  };
81226
81261
  var __commonJS2 = (cb, mod2) => () => (mod2 || cb((mod2 = { exports: {} }).exports, mod2), mod2.exports);
@@ -85697,6 +85732,17 @@ var ErrorCode;
85697
85732
  ErrorCode2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
85698
85733
  })(ErrorCode ||= {});
85699
85734
  var TOOL_APPROVAL_REQUEST = "TOOL_APPROVAL_REQUEST";
85735
+ function asRecord(value) {
85736
+ return value != null && typeof value === "object" ? value : null;
85737
+ }
85738
+ function isMcpConfirmationResponse(value) {
85739
+ const obj = asRecord(value);
85740
+ const metadata = obj ? asRecord(obj._use_ai_metadata) : null;
85741
+ return !!(obj && obj._use_ai_internal === true && obj._use_ai_type === "confirmation_required" && metadata && typeof metadata.message === "string");
85742
+ }
85743
+ function isUseAIInternalResponse(value) {
85744
+ return isMcpConfirmationResponse(value);
85745
+ }
85700
85746
  var export_EventType = import_core.EventType;
85701
85747
 
85702
85748
  // src/rateLimiter.ts
@@ -85873,56 +85919,6 @@ class Logger {
85873
85919
  }
85874
85920
  var logger2 = new Logger;
85875
85921
 
85876
- // ../../node_modules/.bun/uuid@11.1.0/node_modules/uuid/dist/esm/stringify.js
85877
- var byteToHex = [];
85878
- for (let i = 0;i < 256; ++i) {
85879
- byteToHex.push((i + 256).toString(16).slice(1));
85880
- }
85881
- function unsafeStringify(arr, offset = 0) {
85882
- return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
85883
- }
85884
-
85885
- // ../../node_modules/.bun/uuid@11.1.0/node_modules/uuid/dist/esm/rng.js
85886
- import { randomFillSync } from "crypto";
85887
- var rnds8Pool = new Uint8Array(256);
85888
- var poolPtr = rnds8Pool.length;
85889
- function rng() {
85890
- if (poolPtr > rnds8Pool.length - 16) {
85891
- randomFillSync(rnds8Pool);
85892
- poolPtr = 0;
85893
- }
85894
- return rnds8Pool.slice(poolPtr, poolPtr += 16);
85895
- }
85896
-
85897
- // ../../node_modules/.bun/uuid@11.1.0/node_modules/uuid/dist/esm/native.js
85898
- import { randomUUID } from "crypto";
85899
- var native_default = { randomUUID };
85900
-
85901
- // ../../node_modules/.bun/uuid@11.1.0/node_modules/uuid/dist/esm/v4.js
85902
- function v4(options, buf, offset) {
85903
- if (native_default.randomUUID && !buf && !options) {
85904
- return native_default.randomUUID();
85905
- }
85906
- options = options || {};
85907
- const rnds = options.random ?? options.rng?.() ?? rng();
85908
- if (rnds.length < 16) {
85909
- throw new Error("Random bytes length must be >= 16");
85910
- }
85911
- rnds[6] = rnds[6] & 15 | 64;
85912
- rnds[8] = rnds[8] & 63 | 128;
85913
- if (buf) {
85914
- offset = offset || 0;
85915
- if (offset < 0 || offset + 16 > buf.length) {
85916
- throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
85917
- }
85918
- for (let i = 0;i < 16; ++i) {
85919
- buf[offset + i] = rnds[i];
85920
- }
85921
- return buf;
85922
- }
85923
- return unsafeStringify(rnds);
85924
- }
85925
- var v4_default = v4;
85926
85922
  // ../../node_modules/.bun/mustache@4.2.0/node_modules/mustache/mustache.mjs
85927
85923
  /*!
85928
85924
  * mustache.js - Logic-less {{mustache}} templates with JavaScript
@@ -89293,28 +89289,55 @@ function popTraceIdForRun(runId) {
89293
89289
  }
89294
89290
  return traceId;
89295
89291
  }
89296
- function _initializeLangfuse() {
89297
- const enabled = Boolean(process.env.LANGFUSE_PUBLIC_KEY && process.env.LANGFUSE_SECRET_KEY);
89298
- if (!enabled) {
89299
- return { enabled: false };
89292
+ function recordErrorTrace(params) {
89293
+ if (!langfuse.enabled || !langfuse.client)
89294
+ return;
89295
+ try {
89296
+ const trace2 = langfuse.client.trace({
89297
+ id: params.runId,
89298
+ name: "use-ai-error",
89299
+ sessionId: params.sessionId,
89300
+ input: { threadId: params.threadId, errorCategory: params.errorCategory },
89301
+ output: { error: params.errorMessage },
89302
+ metadata: {
89303
+ errorCategory: params.errorCategory,
89304
+ ipAddress: params.ipAddress,
89305
+ source: "use-ai-server",
89306
+ ...params.metadata
89307
+ },
89308
+ tags: ["error", params.errorCategory]
89309
+ });
89310
+ trace2.span({
89311
+ name: params.errorCategory,
89312
+ level: "ERROR",
89313
+ statusMessage: params.errorMessage,
89314
+ input: { threadId: params.threadId, errorCategory: params.errorCategory },
89315
+ output: { error: params.errorMessage }
89316
+ });
89317
+ } catch (error) {
89318
+ logger2.debug("Failed to record error trace in Langfuse", {
89319
+ error: error instanceof Error ? error.message : String(error),
89320
+ runId: params.runId
89321
+ });
89300
89322
  }
89301
- const baseUrl = process.env.LANGFUSE_BASE_URL || "https://cloud.langfuse.com";
89302
- const release = process.env.LANGFUSE_RELEASE || "use-ai-test";
89303
- const langfuseClient = new Langfuse({
89304
- publicKey: process.env.LANGFUSE_PUBLIC_KEY,
89305
- secretKey: process.env.LANGFUSE_SECRET_KEY,
89306
- baseUrl,
89307
- release
89308
- });
89323
+ }
89324
+ var _tracingEnabled = false;
89325
+ function isTracingEnabled() {
89326
+ return _tracingEnabled;
89327
+ }
89328
+ var _tracingStarted = false;
89329
+ var _spanProcessors = [];
89330
+ async function flushTracing() {
89331
+ await Promise.all(_spanProcessors.map((p) => p.forceFlush()));
89332
+ }
89333
+ function startTracing(customProcessors = []) {
89334
+ if (_tracingStarted)
89335
+ return;
89336
+ _tracingStarted = true;
89337
+ if (!langfuse.enabled && customProcessors.length === 0)
89338
+ return;
89309
89339
  try {
89310
89340
  const { NodeSDK } = require_src32();
89311
- const { LangfuseSpanProcessor } = require_dist5();
89312
- const langfuseSpanProcessor = new LangfuseSpanProcessor({
89313
- publicKey: process.env.LANGFUSE_PUBLIC_KEY,
89314
- secretKey: process.env.LANGFUSE_SECRET_KEY,
89315
- baseUrl,
89316
- release
89317
- });
89318
89341
  const traceIdCaptureProcessor = {
89319
89342
  onStart(span) {
89320
89343
  const runId = span.attributes?.["ai.telemetry.metadata.runId"];
@@ -89330,33 +89353,101 @@ function _initializeLangfuse() {
89330
89353
  return Promise.resolve();
89331
89354
  }
89332
89355
  };
89333
- const sdk = new NodeSDK({
89334
- spanProcessors: [traceIdCaptureProcessor, langfuseSpanProcessor]
89335
- });
89356
+ const spanProcessors = [traceIdCaptureProcessor];
89357
+ let langfuseSpanProcessor;
89358
+ if (langfuse.enabled) {
89359
+ const { LangfuseSpanProcessor } = require_dist5();
89360
+ langfuseSpanProcessor = new LangfuseSpanProcessor({
89361
+ publicKey: process.env.LANGFUSE_PUBLIC_KEY,
89362
+ secretKey: process.env.LANGFUSE_SECRET_KEY,
89363
+ baseUrl: process.env.LANGFUSE_BASE_URL || "https://cloud.langfuse.com",
89364
+ release: process.env.LANGFUSE_RELEASE || "use-ai"
89365
+ });
89366
+ spanProcessors.push(langfuseSpanProcessor);
89367
+ }
89368
+ spanProcessors.push(...customProcessors);
89369
+ const sdk = new NodeSDK({ spanProcessors });
89336
89370
  sdk.start();
89337
- logger2.info("Langfuse observability initialized", { baseUrl, release });
89338
- return {
89339
- enabled: true,
89340
- client: langfuseClient,
89341
- flush: async () => {
89342
- await langfuseSpanProcessor.forceFlush();
89343
- await langfuseClient.flushAsync();
89344
- }
89345
- };
89371
+ _tracingEnabled = true;
89372
+ _spanProcessors = spanProcessors;
89373
+ logger2.info("OpenTelemetry tracing started", {
89374
+ langfuseEnabled: langfuse.enabled,
89375
+ customProcessorCount: customProcessors.length
89376
+ });
89346
89377
  } catch (error) {
89347
- logger2.warn("Failed to initialize Langfuse OTEL. Install @langfuse/otel and @opentelemetry/sdk-node for tracing.", {
89378
+ logger2.warn("Failed to start OpenTelemetry tracing. Install @opentelemetry/sdk-node for tracing.", {
89348
89379
  error: error instanceof Error ? error.message : "Unknown error"
89349
89380
  });
89350
- return {
89351
- enabled: true,
89352
- client: langfuseClient,
89353
- flush: async () => {
89354
- await langfuseClient.flushAsync();
89355
- }
89356
- };
89357
89381
  }
89358
89382
  }
89383
+ function _initializeLangfuse() {
89384
+ const enabled = Boolean(process.env.LANGFUSE_PUBLIC_KEY && process.env.LANGFUSE_SECRET_KEY);
89385
+ if (!enabled) {
89386
+ return { enabled: false };
89387
+ }
89388
+ const baseUrl = process.env.LANGFUSE_BASE_URL || "https://cloud.langfuse.com";
89389
+ const release = process.env.LANGFUSE_RELEASE || "use-ai";
89390
+ const client = new Langfuse({
89391
+ publicKey: process.env.LANGFUSE_PUBLIC_KEY,
89392
+ secretKey: process.env.LANGFUSE_SECRET_KEY,
89393
+ baseUrl,
89394
+ release
89395
+ });
89396
+ return {
89397
+ enabled: true,
89398
+ client
89399
+ };
89400
+ }
89401
+ // ../../node_modules/.bun/uuid@11.1.0/node_modules/uuid/dist/esm/native.js
89402
+ import { randomUUID } from "crypto";
89403
+ var native_default = { randomUUID };
89404
+
89405
+ // ../../node_modules/.bun/uuid@11.1.0/node_modules/uuid/dist/esm/rng.js
89406
+ import { randomFillSync } from "crypto";
89407
+ var rnds8Pool = new Uint8Array(256);
89408
+ var poolPtr = rnds8Pool.length;
89409
+ function rng() {
89410
+ if (poolPtr > rnds8Pool.length - 16) {
89411
+ randomFillSync(rnds8Pool);
89412
+ poolPtr = 0;
89413
+ }
89414
+ return rnds8Pool.slice(poolPtr, poolPtr += 16);
89415
+ }
89359
89416
 
89417
+ // ../../node_modules/.bun/uuid@11.1.0/node_modules/uuid/dist/esm/stringify.js
89418
+ var byteToHex = [];
89419
+ for (let i = 0;i < 256; ++i) {
89420
+ byteToHex.push((i + 256).toString(16).slice(1));
89421
+ }
89422
+ function unsafeStringify(arr, offset = 0) {
89423
+ return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
89424
+ }
89425
+
89426
+ // ../../node_modules/.bun/uuid@11.1.0/node_modules/uuid/dist/esm/v4.js
89427
+ function v4(options, buf, offset) {
89428
+ if (native_default.randomUUID && !buf && !options) {
89429
+ return native_default.randomUUID();
89430
+ }
89431
+ options = options || {};
89432
+ const rnds = options.random ?? options.rng?.() ?? rng();
89433
+ if (rnds.length < 16) {
89434
+ throw new Error("Random bytes length must be >= 16");
89435
+ }
89436
+ rnds[6] = rnds[6] & 15 | 64;
89437
+ rnds[8] = rnds[8] & 63 | 128;
89438
+ if (buf) {
89439
+ offset = offset || 0;
89440
+ if (offset < 0 || offset + 16 > buf.length) {
89441
+ throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
89442
+ }
89443
+ for (let i = 0;i < 16; ++i) {
89444
+ buf[offset + i] = rnds[i];
89445
+ }
89446
+ return buf;
89447
+ }
89448
+ return unsafeStringify(rnds);
89449
+ }
89450
+ var v4_default = v4;
89360
89451
  // src/plugins/FeedbackPlugin.ts
89361
89452
  class FeedbackPlugin {
89362
89453
  langfuseClient = null;
@@ -89446,6 +89537,30 @@ function findMatch(str, patternMap) {
89446
89537
  return;
89447
89538
  }
89448
89539
 
89540
+ // src/utils/toolFilters.ts
89541
+ function isRemoteTool(tool) {
89542
+ return tool._remote !== undefined;
89543
+ }
89544
+ function isServerTool(tool) {
89545
+ return tool._server !== undefined;
89546
+ }
89547
+ function and(...filters) {
89548
+ return (tool) => filters.every((f) => f(tool));
89549
+ }
89550
+ function or(...filters) {
89551
+ return (tool) => filters.some((f) => f(tool));
89552
+ }
89553
+ function not(filter) {
89554
+ return (tool) => !filter(tool);
89555
+ }
89556
+ function createGlobFilter(patterns) {
89557
+ return (tool) => {
89558
+ if (patterns.length === 0)
89559
+ return false;
89560
+ return patterns.some((pattern) => matchesPattern(tool.name, pattern));
89561
+ };
89562
+ }
89563
+
89449
89564
  // src/mcp/RemoteMcpToolsProvider.ts
89450
89565
  class RemoteMcpToolsProvider {
89451
89566
  url;
@@ -89622,6 +89737,136 @@ class RemoteMcpToolsProvider {
89622
89737
  return Object.entries(headers).map(([key, value]) => `${key}: ${isDebug ? value : "*".repeat(value.length)}`).join(", ");
89623
89738
  }
89624
89739
  }
89740
+ // src/utils/toolConverter.ts
89741
+ function createClientToolExecutor(session) {
89742
+ return async (args, { toolCallId }) => {
89743
+ const result = await new Promise((resolve, reject) => {
89744
+ if (session.abortController?.signal.aborted) {
89745
+ reject(new Error("Run aborted"));
89746
+ return;
89747
+ }
89748
+ session.pendingToolCalls.set(toolCallId, resolve);
89749
+ session.abortController?.signal.addEventListener("abort", () => {
89750
+ session.pendingToolCalls.delete(toolCallId);
89751
+ reject(new Error("Run aborted"));
89752
+ }, { once: true });
89753
+ });
89754
+ return JSON.parse(result);
89755
+ };
89756
+ }
89757
+ // src/utils/toolAnnotations.ts
89758
+ function getToolAnnotations(tool) {
89759
+ if (!tool) {
89760
+ return;
89761
+ }
89762
+ if (tool.annotations) {
89763
+ return tool.annotations;
89764
+ }
89765
+ if (isRemoteTool(tool)) {
89766
+ return tool._remote.annotations;
89767
+ }
89768
+ return;
89769
+ }
89770
+ // src/agents/toolApproval.ts
89771
+ function toolNeedsApproval(toolDef) {
89772
+ const annotations = getToolAnnotations(toolDef);
89773
+ return annotations?.destructiveHint === true;
89774
+ }
89775
+ function waitForApproval(session, toolCallId) {
89776
+ return new Promise((resolve, reject) => {
89777
+ if (session.abortController?.signal.aborted) {
89778
+ reject(new Error("Run aborted"));
89779
+ return;
89780
+ }
89781
+ session.pendingToolApprovals.set(toolCallId, resolve);
89782
+ session.abortController?.signal.addEventListener("abort", () => {
89783
+ session.pendingToolApprovals.delete(toolCallId);
89784
+ reject(new Error("Run aborted"));
89785
+ }, { once: true });
89786
+ });
89787
+ }
89788
+ function createApprovalWrapper(toolDef, session, events, actualExecutor) {
89789
+ return async (args, options) => {
89790
+ const annotations = getToolAnnotations(toolDef);
89791
+ logger2.info("Tool requires approval", {
89792
+ toolCallId: options.toolCallId,
89793
+ toolName: toolDef.name
89794
+ });
89795
+ events.emit({
89796
+ type: TOOL_APPROVAL_REQUEST,
89797
+ toolCallId: options.toolCallId,
89798
+ toolCallName: toolDef.name,
89799
+ toolCallArgs: args,
89800
+ annotations,
89801
+ timestamp: Date.now()
89802
+ });
89803
+ const approvalResult = await waitForApproval(session, options.toolCallId);
89804
+ if (approvalResult.approved) {
89805
+ logger2.info("Tool approved by user", { toolCallId: options.toolCallId });
89806
+ return actualExecutor(args, options);
89807
+ } else {
89808
+ logger2.info("Tool rejected by user", {
89809
+ toolCallId: options.toolCallId,
89810
+ reason: approvalResult.reason
89811
+ });
89812
+ return {
89813
+ error: true,
89814
+ message: `Tool execution denied by user: ${approvalResult.reason || "Action was rejected"}`
89815
+ };
89816
+ }
89817
+ };
89818
+ }
89819
+
89820
+ // src/mcp/mcpConfirmation.ts
89821
+ async function handleMcpConfirmation(confirmation, toolCallId, toolCallName, originalToolName, originalArgs, provider, session, events, mcpHeaders) {
89822
+ const { message, metadata, additional_columns } = confirmation._use_ai_metadata;
89823
+ logger2.info("[MCP] Tool returned confirmation_required", {
89824
+ toolCallId,
89825
+ toolCallName,
89826
+ message,
89827
+ originalToolName
89828
+ });
89829
+ events.emit({
89830
+ type: TOOL_APPROVAL_REQUEST,
89831
+ toolCallId,
89832
+ toolCallName,
89833
+ toolCallArgs: originalArgs,
89834
+ message,
89835
+ metadata,
89836
+ timestamp: Date.now()
89837
+ });
89838
+ const approvalResult = await waitForApproval(session, toolCallId);
89839
+ if (!approvalResult.approved) {
89840
+ logger2.info("[MCP] Confirmation rejected by user", {
89841
+ toolCallId,
89842
+ reason: approvalResult.reason
89843
+ });
89844
+ return {
89845
+ error: true,
89846
+ message: `Tool execution denied by user: ${approvalResult.reason || "Action was rejected"}`
89847
+ };
89848
+ }
89849
+ const phase2Args = additional_columns ? { ...originalArgs, ...additional_columns } : originalArgs;
89850
+ logger2.info("[MCP] Confirmation approved, executing phase 2", {
89851
+ toolCallId,
89852
+ originalToolName
89853
+ });
89854
+ try {
89855
+ const result = await provider.executeTool(originalToolName, phase2Args, mcpHeaders);
89856
+ return result;
89857
+ } catch (error) {
89858
+ const errorMsg = error instanceof Error ? error.message : String(error);
89859
+ logger2.error("[MCP] Phase 2 execution failed", {
89860
+ toolCallId,
89861
+ originalToolName,
89862
+ error: errorMsg
89863
+ });
89864
+ return {
89865
+ error: true,
89866
+ message: `MCP confirmation execution failed: ${errorMsg}`
89867
+ };
89868
+ }
89869
+ }
89625
89870
  // src/runtime/detection.ts
89626
89871
  function detectRuntime() {
89627
89872
  if (typeof globalThis !== "undefined" && "Bun" in globalThis) {
@@ -89680,8 +89925,10 @@ class UseAIServer {
89680
89925
  plugins = [];
89681
89926
  messageHandlers = new Map;
89682
89927
  mcpEndpoints = [];
89928
+ serverTools = [];
89683
89929
  clientIpTracker;
89684
89930
  constructor(config) {
89931
+ startTracing(config.spanProcessors);
89685
89932
  this.config = {
89686
89933
  port: config.port ?? 8081,
89687
89934
  rateLimitMaxRequests: config.rateLimitMaxRequests ?? 0,
@@ -89712,6 +89959,21 @@ class UseAIServer {
89712
89959
  endpoints: this.mcpEndpoints.map((e) => e.getUrl())
89713
89960
  });
89714
89961
  }
89962
+ if (config.tools) {
89963
+ this.serverTools = Object.entries(config.tools).map(([name, toolConfig]) => ({
89964
+ name,
89965
+ description: toolConfig.description,
89966
+ parameters: toolConfig.parameters,
89967
+ annotations: toolConfig.annotations,
89968
+ _server: {
89969
+ execute: toolConfig.execute
89970
+ }
89971
+ }));
89972
+ logger2.info("[Server Tools] Registered server tools", {
89973
+ count: this.serverTools.length,
89974
+ names: this.serverTools.map((t) => t.name)
89975
+ });
89976
+ }
89715
89977
  this.plugins = config.plugins ?? [];
89716
89978
  this.initializePlugins();
89717
89979
  this.runtimeAdapter = createRuntimeAdapter(config.runtime ?? "auto");
@@ -89812,6 +90074,19 @@ class UseAIServer {
89812
90074
  error: error instanceof Error ? error.message : "Unknown error",
89813
90075
  clientId
89814
90076
  });
90077
+ if (message.type === "run_agent") {
90078
+ const runAgentData = message.data;
90079
+ const unhandledForwardedProps = runAgentData?.forwardedProps;
90080
+ recordErrorTrace({
90081
+ runId: runAgentData?.runId || socket.id,
90082
+ errorCategory: "unhandled_error",
90083
+ errorMessage: error instanceof Error ? error.message : "Unknown error",
90084
+ sessionId: clientId,
90085
+ threadId: runAgentData?.threadId,
90086
+ ipAddress: session?.ipAddress,
90087
+ metadata: { ...unhandledForwardedProps?.telemetryMetadata }
90088
+ });
90089
+ }
89815
90090
  this.sendEvent(socket, {
89816
90091
  type: export_EventType.RUN_ERROR,
89817
90092
  message: error instanceof Error ? error.message : "Unknown error",
@@ -89821,6 +90096,7 @@ class UseAIServer {
89821
90096
  });
89822
90097
  socket.on("disconnect", () => {
89823
90098
  logger2.info("Client disconnected", { clientId, ipAddress });
90099
+ session.abortController?.abort();
89824
90100
  this.clientIpTracker.removePollingConnection(conn.id);
89825
90101
  for (const plugin of this.plugins) {
89826
90102
  plugin.onClientDisconnect?.(session);
@@ -89873,6 +90149,15 @@ class UseAIServer {
89873
90149
  requested: requestedAgent,
89874
90150
  available: availableAgents
89875
90151
  });
90152
+ recordErrorTrace({
90153
+ runId,
90154
+ errorCategory: "agent_not_found",
90155
+ errorMessage: `Agent "${requestedAgent}" not found`,
90156
+ sessionId: session.clientId,
90157
+ threadId,
90158
+ ipAddress: session.ipAddress,
90159
+ metadata: { requestedAgent, availableAgents, ...forwardedProps?.telemetryMetadata }
90160
+ });
89876
90161
  this.sendEvent(session.socket, {
89877
90162
  type: export_EventType.RUN_ERROR,
89878
90163
  message: `Agent "${requestedAgent}" not found. Available agents: ${availableAgents.join(", ")}`,
@@ -89884,6 +90169,15 @@ class UseAIServer {
89884
90169
  const rateLimitCheck = this.rateLimiter.checkLimit(session.ipAddress);
89885
90170
  if (!rateLimitCheck.allowed) {
89886
90171
  const retryAfterSeconds = Math.ceil((rateLimitCheck.retryAfterMs || 0) / 1000);
90172
+ recordErrorTrace({
90173
+ runId,
90174
+ errorCategory: "rate_limit_exceeded",
90175
+ errorMessage: "Rate limit exceeded",
90176
+ sessionId: session.clientId,
90177
+ threadId,
90178
+ ipAddress: session.ipAddress,
90179
+ metadata: { retryAfterSeconds, ...forwardedProps?.telemetryMetadata }
90180
+ });
89887
90181
  this.sendEvent(session.socket, {
89888
90182
  type: export_EventType.RUN_ERROR,
89889
90183
  message: `Rate limit exceeded. Please try again in ${retryAfterSeconds} seconds.`,
@@ -89900,6 +90194,7 @@ class UseAIServer {
89900
90194
  }
89901
90195
  session.threadId = threadId;
89902
90196
  session.currentRunId = runId;
90197
+ session.abortController = new AbortController;
89903
90198
  session.currentMcpHeaders = mcpHeaders;
89904
90199
  const clientTools = tools.map((t) => ({
89905
90200
  ...t,
@@ -89909,11 +90204,12 @@ class UseAIServer {
89909
90204
  if (this.mcpEndpoints.length > 0) {
89910
90205
  mcpTools = await this.getMcpToolsForSession(session, mcpHeaders);
89911
90206
  }
89912
- session.tools = [...clientTools, ...mcpTools];
89913
- if (mcpTools.length > 0) {
89914
- logger2.debug("[MCP] Merged tools", {
90207
+ session.tools = [...clientTools, ...mcpTools, ...this.serverTools];
90208
+ if (mcpTools.length > 0 || this.serverTools.length > 0) {
90209
+ logger2.debug("Merged tools", {
89915
90210
  clientTools: clientTools.length,
89916
90211
  mcpTools: mcpTools.length,
90212
+ serverTools: this.serverTools.length,
89917
90213
  total: session.tools.length
89918
90214
  });
89919
90215
  }
@@ -90039,19 +90335,37 @@ ${block.text}`
90039
90335
  }
90040
90336
  }
90041
90337
  buildSystemPrompt(session, state) {
90042
- const parts = [];
90043
- if (state) {
90044
- parts.push("You are interacting with a web application. Here is the current state:");
90045
- parts.push("");
90046
- parts.push(JSON.stringify(state, null, 2));
90047
- parts.push("");
90048
- parts.push("Use the available tools to interact with and modify the UI based on user requests.");
90049
- }
90050
- return parts.length > 0 ? parts.join(`
90051
- `) : undefined;
90338
+ if (!state)
90339
+ return;
90340
+ return "You are interacting with a web application. Use the available tools to interact with and modify the UI based on user requests.";
90052
90341
  }
90053
90342
  handleToolResult(session, message) {
90054
- const { toolCallId, content } = message.data;
90343
+ const { toolCallId, content, forwardedProps } = message.data;
90344
+ const tools = forwardedProps?.tools;
90345
+ const state = forwardedProps?.state;
90346
+ if (tools && tools.length > 0) {
90347
+ const existingRemoteTools = session.tools.filter(isRemoteTool);
90348
+ const existingServerTools = session.tools.filter(isServerTool);
90349
+ const updatedClientTools = tools.map((t) => ({
90350
+ ...t,
90351
+ parameters: t.parameters || { type: "object", properties: {}, required: [] }
90352
+ }));
90353
+ session.tools = [...updatedClientTools, ...existingRemoteTools, ...existingServerTools];
90354
+ logger2.debug("Tools updated mid-run", {
90355
+ clientId: session.clientId,
90356
+ toolCount: session.tools.length,
90357
+ clientToolCount: updatedClientTools.length,
90358
+ mcpToolCount: existingRemoteTools.length,
90359
+ serverToolCount: existingServerTools.length,
90360
+ toolNames: session.tools.map((t) => t.name)
90361
+ });
90362
+ }
90363
+ if (state !== undefined) {
90364
+ session.state = state;
90365
+ logger2.debug("State updated mid-run", {
90366
+ clientId: session.clientId
90367
+ });
90368
+ }
90055
90369
  const resolver = session.pendingToolCalls.get(toolCallId);
90056
90370
  if (resolver) {
90057
90371
  resolver(content);
@@ -90079,6 +90393,7 @@ ${block.text}`
90079
90393
  }
90080
90394
  handleAbortRun(session, message) {
90081
90395
  const { runId } = message.data;
90396
+ session.abortController?.abort();
90082
90397
  session.pendingToolCalls.clear();
90083
90398
  session.pendingToolApprovals.clear();
90084
90399
  session.currentRunId = undefined;
@@ -90171,6 +90486,7 @@ ${block.text}`
90171
90486
  async close() {
90172
90487
  clearInterval(this.cleanupInterval);
90173
90488
  this.mcpEndpoints.forEach((endpoint) => endpoint.destroy());
90489
+ await Promise.all(Object.values(this.agents).map((agent) => agent.flushTelemetry?.()));
90174
90490
  await Promise.all(this.plugins.map((plugin) => plugin.close?.()));
90175
90491
  this.io.close();
90176
90492
  if (this.serverHandle) {
@@ -113489,34 +113805,113 @@ var marker142 = `vercel.ai.error.${name142}`;
113489
113805
  var symbol142 = Symbol.for(marker142);
113490
113806
  var _a142;
113491
113807
  _a142 = symbol142;
113492
- // src/utils/toolConverter.ts
113493
- function createClientToolExecutor(session) {
113494
- return async (args, { toolCallId }) => {
113495
- const result = await new Promise((resolve2) => {
113496
- session.pendingToolCalls.set(toolCallId, resolve2);
113497
- });
113498
- return JSON.parse(result);
113499
- };
113500
- }
113501
113808
 
113502
- // src/utils/toolFilters.ts
113503
- function isRemoteTool(tool2) {
113504
- return tool2._remote !== undefined;
113505
- }
113506
- function and(...filters) {
113507
- return (tool2) => filters.every((f) => f(tool2));
113508
- }
113509
- function or(...filters) {
113510
- return (tool2) => filters.some((f) => f(tool2));
113809
+ // src/telemetry.ts
113810
+ var import_api4 = __toESM(require_src2(), 1);
113811
+ function startRunSpan(config2) {
113812
+ const { runId, sessionId } = config2;
113813
+ if (!langfuse.enabled && !isTracingEnabled()) {
113814
+ return {
113815
+ active: false,
113816
+ wrap: (fn) => fn(),
113817
+ setInput: () => {},
113818
+ setOutput: () => {},
113819
+ end: () => {
113820
+ popTraceIdForRun(runId);
113821
+ },
113822
+ endWithError: () => {
113823
+ popTraceIdForRun(runId);
113824
+ },
113825
+ popTraceId: () => popTraceIdForRun(runId),
113826
+ recordError: () => {}
113827
+ };
113828
+ }
113829
+ const parentSpan = import_api4.trace.getTracer("use-ai").startSpan("use-ai.agent.run", {
113830
+ attributes: {
113831
+ "ai.telemetry.functionId": "use-ai",
113832
+ "ai.telemetry.metadata.runId": runId,
113833
+ "ai.telemetry.metadata.sessionId": sessionId,
113834
+ ...config2.attributes
113835
+ }
113836
+ });
113837
+ const parentOtelContext = import_api4.trace.setSpan(import_api4.context.active(), parentSpan);
113838
+ return {
113839
+ active: true,
113840
+ wrap(fn) {
113841
+ return import_api4.context.with(parentOtelContext, fn);
113842
+ },
113843
+ setInput(value) {
113844
+ parentSpan.setAttribute("langfuse.observation.input", typeof value === "string" ? value : JSON.stringify(value));
113845
+ },
113846
+ setOutput(value) {
113847
+ parentSpan.setAttribute("langfuse.observation.output", typeof value === "string" ? value : JSON.stringify(value));
113848
+ },
113849
+ end() {
113850
+ parentSpan.setStatus({ code: import_api4.SpanStatusCode.OK });
113851
+ parentSpan.end();
113852
+ popTraceIdForRun(runId);
113853
+ },
113854
+ endWithError(message) {
113855
+ parentSpan.setStatus({ code: import_api4.SpanStatusCode.ERROR, message });
113856
+ parentSpan.end();
113857
+ popTraceIdForRun(runId);
113858
+ },
113859
+ popTraceId() {
113860
+ return popTraceIdForRun(runId);
113861
+ },
113862
+ recordError(params) {
113863
+ recordErrorTrace(params);
113864
+ }
113865
+ };
113511
113866
  }
113512
- function not(filter2) {
113513
- return (tool2) => !filter2(tool2);
113867
+ async function flushTelemetry() {
113868
+ await flushTracing();
113869
+ await langfuse.client?.flushAsync();
113514
113870
  }
113515
- function createGlobFilter(patterns) {
113516
- return (tool2) => {
113517
- if (patterns.length === 0)
113518
- return false;
113519
- return patterns.some((pattern) => matchesPattern(tool2.name, pattern));
113871
+ // src/tools/serverToolExecutor.ts
113872
+ function createServerToolExecutor(serverTool, session, events) {
113873
+ return async (args, { toolCallId }) => {
113874
+ logger2.info("[Server Tool] Executing", {
113875
+ toolName: serverTool.name,
113876
+ toolCallId
113877
+ });
113878
+ const context = {
113879
+ session,
113880
+ state: session.state,
113881
+ runId: session.currentRunId || "",
113882
+ toolCallId,
113883
+ requestApproval: async ({ message, metadata }) => {
113884
+ const approvalId = `${toolCallId}-approval-${Date.now()}`;
113885
+ logger2.info("[Server Tool] Runtime approval requested", {
113886
+ toolName: serverTool.name,
113887
+ toolCallId,
113888
+ approvalId,
113889
+ message
113890
+ });
113891
+ events.emit({
113892
+ type: TOOL_APPROVAL_REQUEST,
113893
+ toolCallId: approvalId,
113894
+ toolCallName: serverTool.name,
113895
+ toolCallArgs: args,
113896
+ timestamp: Date.now(),
113897
+ message,
113898
+ metadata
113899
+ });
113900
+ return waitForApproval(session, approvalId);
113901
+ }
113902
+ };
113903
+ try {
113904
+ const result = await serverTool._server.execute(args, context);
113905
+ return result;
113906
+ } catch (error40) {
113907
+ const errorMsg = error40 instanceof Error ? error40.message : String(error40);
113908
+ logger2.error("[Server Tool] Execution failed", {
113909
+ toolName: serverTool.name,
113910
+ toolCallId,
113911
+ error: errorMsg
113912
+ });
113913
+ throw error40;
113914
+ }
113520
113915
  };
113521
113916
  }
113522
113917
 
@@ -113566,73 +113961,21 @@ function applyCacheBreakpoints(messages, cacheBreakpoint, model) {
113566
113961
  }
113567
113962
  return result;
113568
113963
  }
113569
- // src/utils/toolAnnotations.ts
113570
- function getToolAnnotations(tool2) {
113571
- if (!tool2) {
113572
- return;
113573
- }
113574
- if (tool2.annotations) {
113575
- return tool2.annotations;
113576
- }
113577
- if (isRemoteTool(tool2)) {
113578
- return tool2._remote.annotations;
113579
- }
113580
- return;
113581
- }
113582
- // src/agents/toolApproval.ts
113583
- function toolNeedsApproval(toolDef) {
113584
- const annotations = getToolAnnotations(toolDef);
113585
- return annotations?.destructiveHint === true;
113586
- }
113587
- function waitForApproval(session, toolCallId) {
113588
- return new Promise((resolve2) => {
113589
- session.pendingToolApprovals.set(toolCallId, resolve2);
113590
- });
113591
- }
113592
- function createApprovalWrapper(toolDef, session, events, actualExecutor) {
113593
- return async (args, options) => {
113594
- const annotations = getToolAnnotations(toolDef);
113595
- logger2.info("Tool requires approval", {
113596
- toolCallId: options.toolCallId,
113597
- toolName: toolDef.name
113598
- });
113599
- events.emit({
113600
- type: TOOL_APPROVAL_REQUEST,
113601
- toolCallId: options.toolCallId,
113602
- toolCallName: toolDef.name,
113603
- toolCallArgs: args,
113604
- annotations,
113605
- timestamp: Date.now()
113606
- });
113607
- const approvalResult = await waitForApproval(session, options.toolCallId);
113608
- if (approvalResult.approved) {
113609
- logger2.info("Tool approved by user", { toolCallId: options.toolCallId });
113610
- return actualExecutor(args, options);
113611
- } else {
113612
- logger2.info("Tool rejected by user", {
113613
- toolCallId: options.toolCallId,
113614
- reason: approvalResult.reason
113615
- });
113616
- return {
113617
- error: true,
113618
- message: `Tool execution denied by user: ${approvalResult.reason || "Action was rejected"}`
113619
- };
113620
- }
113621
- };
113622
- }
113623
113964
 
113624
113965
  // src/agents/AISDKAgent.ts
113625
113966
  var DEFAULT_MAX_OUTPUT_TOKENS = 4096;
113967
+ var DEFAULT_MAX_STEPS = 10;
113626
113968
 
113627
113969
  class AISDKAgent {
113628
113970
  model;
113629
113971
  name;
113630
113972
  annotation;
113631
- langfuse;
113632
113973
  toolFilter;
113633
113974
  systemPrompt;
113634
113975
  cacheBreakpoint;
113635
113976
  maxOutputTokens;
113977
+ temperature;
113978
+ maxSteps;
113636
113979
  constructor(config2) {
113637
113980
  this.model = config2.model;
113638
113981
  this.name = config2.name || "ai-sdk";
@@ -113641,7 +113984,8 @@ class AISDKAgent {
113641
113984
  this.systemPrompt = config2.systemPrompt;
113642
113985
  this.cacheBreakpoint = config2.cacheBreakpoint;
113643
113986
  this.maxOutputTokens = config2.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
113644
- this.langfuse = langfuse;
113987
+ this.temperature = config2.temperature;
113988
+ this.maxSteps = config2.maxSteps ?? DEFAULT_MAX_STEPS;
113645
113989
  }
113646
113990
  getName() {
113647
113991
  return this.name;
@@ -113650,14 +113994,15 @@ class AISDKAgent {
113650
113994
  return this.annotation;
113651
113995
  }
113652
113996
  async flushTelemetry() {
113653
- if (this.langfuse.flush) {
113654
- await this.langfuse.flush();
113655
- }
113997
+ await flushTelemetry();
113656
113998
  }
113657
113999
  async run(input, events) {
113658
114000
  const { session, runId, messages, tools, state, systemPrompt: runtimeSystemPrompt, originalInput } = input;
114001
+ if (session.tools.length === 0 && tools.length > 0) {
114002
+ session.tools = tools;
114003
+ }
113659
114004
  const configSystemPrompt = await this.resolveSystemPrompt();
113660
- const systemMessages = this.buildSystemMessages(configSystemPrompt, runtimeSystemPrompt);
114005
+ const staticSystemMessages = this.buildStaticSystemMessages(configSystemPrompt, runtimeSystemPrompt);
113661
114006
  events.emit({
113662
114007
  type: export_EventType.RUN_STARTED,
113663
114008
  threadId: session.threadId,
@@ -113675,6 +114020,12 @@ class AISDKAgent {
113675
114020
  snapshot: state,
113676
114021
  timestamp: Date.now()
113677
114022
  });
114023
+ let streamTextStarted = false;
114024
+ const span = startRunSpan({ runId, sessionId: session.clientId });
114025
+ const lastUserMessage = [...messages].reverse().find((m) => m.role === "user");
114026
+ if (lastUserMessage) {
114027
+ span.setInput(lastUserMessage.content);
114028
+ }
113678
114029
  try {
113679
114030
  logger2.info("Sending to AI SDK model (streaming)", {
113680
114031
  clientId: session.clientId,
@@ -113682,10 +114033,7 @@ class AISDKAgent {
113682
114033
  toolCount: tools.length
113683
114034
  });
113684
114035
  const sanitizedInputMessages = this.sanitizeMessages(messages);
113685
- const messagesWithSystem = [
113686
- ...systemMessages || [],
113687
- ...sanitizedInputMessages
113688
- ];
114036
+ let currentMessages = [...sanitizedInputMessages];
113689
114037
  logger2.apiRequest({
113690
114038
  tools: tools.map((t) => t.name),
113691
114039
  messageCount: messages.length,
@@ -113693,147 +114041,187 @@ class AISDKAgent {
113693
114041
  role: msg.role,
113694
114042
  preview: typeof msg.content === "string" ? msg.content.substring(0, 80) + (msg.content.length > 80 ? "..." : "") : Array.isArray(msg.content) ? `${msg.content.length} content blocks` : "complex content"
113695
114043
  })),
113696
- systemMessages: systemMessages?.map((m) => m.content.substring(0, 80) + (m.content.length > 80 ? "..." : ""))
113697
- });
113698
- const messagesWithCache = applyCacheBreakpoints(messagesWithSystem, this.cacheBreakpoint, this.model);
113699
- const stream = streamText({
113700
- model: this.model,
113701
- messages: messagesWithCache,
113702
- tools: tools.length > 0 ? this.sanitizeToolsForAPI(this.filterTools(tools), session, events) : undefined,
113703
- stopWhen: stepCountIs(10),
113704
- maxOutputTokens: this.maxOutputTokens,
113705
- abortSignal: session.abortController?.signal,
113706
- experimental_telemetry: this.langfuse?.enabled ? {
113707
- isEnabled: true,
113708
- functionId: "use-ai",
113709
- metadata: {
113710
- sessionId: session.clientId,
113711
- threadId: session.threadId,
113712
- runId,
113713
- ipAddress: session.ipAddress,
113714
- toolCount: tools.length,
113715
- ...originalInput.forwardedProps?.telemetryMetadata || {}
113716
- }
113717
- } : undefined,
113718
- onStepFinish: ({ usage, finishReason }) => {
113719
- logger2.debug("Step finished", { usage, finishReason });
113720
- }
114044
+ systemMessages: staticSystemMessages?.map((m) => m.content.substring(0, 80) + (m.content.length > 80 ? "..." : ""))
113721
114045
  });
113722
114046
  let messageId = null;
113723
114047
  let hasEmittedTextStart = false;
113724
114048
  let finalText = "";
113725
114049
  let currentStepNumber = 0;
113726
114050
  let hasAnyContent = false;
113727
- const activeToolCalls = new Map;
113728
- for await (const chunk of stream.fullStream) {
113729
- switch (chunk.type) {
113730
- case "start-step": {
113731
- events.emit({
113732
- type: export_EventType.STEP_STARTED,
113733
- stepName: `step-${currentStepNumber++}`,
113734
- timestamp: Date.now()
113735
- });
113736
- break;
114051
+ let response = null;
114052
+ const allResponseMessages = [];
114053
+ for (let stepIteration = 0;stepIteration < this.maxSteps; stepIteration++) {
114054
+ const currentTools = session.tools;
114055
+ logger2.debug("Starting step iteration", {
114056
+ stepIteration,
114057
+ toolCount: currentTools.length,
114058
+ toolNames: currentTools.map((t) => t.name)
114059
+ });
114060
+ const stateMessage = this.buildStateMessage(session.state);
114061
+ const messagesForStep = [
114062
+ ...staticSystemMessages || [],
114063
+ ...stateMessage ? [stateMessage] : [],
114064
+ ...currentMessages
114065
+ ];
114066
+ const messagesWithCache = applyCacheBreakpoints(messagesForStep, this.cacheBreakpoint, this.model);
114067
+ streamTextStarted = true;
114068
+ const createStream = () => streamText({
114069
+ model: this.model,
114070
+ messages: messagesWithCache,
114071
+ tools: currentTools.length > 0 ? this.sanitizeToolsForAPI(this.filterTools(currentTools), session, events) : undefined,
114072
+ stopWhen: stepCountIs(1),
114073
+ maxOutputTokens: this.maxOutputTokens,
114074
+ temperature: this.temperature,
114075
+ abortSignal: session.abortController?.signal,
114076
+ experimental_telemetry: span.active ? {
114077
+ isEnabled: true,
114078
+ functionId: "use-ai",
114079
+ metadata: {
114080
+ sessionId: session.clientId,
114081
+ threadId: session.threadId,
114082
+ runId,
114083
+ ipAddress: session.ipAddress,
114084
+ toolCount: currentTools.length,
114085
+ stepIteration,
114086
+ ...originalInput.forwardedProps?.telemetryMetadata || {}
114087
+ }
114088
+ } : undefined,
114089
+ onStepFinish: ({ usage, finishReason }) => {
114090
+ logger2.debug("Step finished", { usage, finishReason, stepIteration });
113737
114091
  }
113738
- case "text-delta": {
113739
- hasAnyContent = true;
113740
- if (!hasEmittedTextStart) {
113741
- messageId = v4_default();
114092
+ });
114093
+ const stream = span.wrap(createStream);
114094
+ const activeToolCalls = new Map;
114095
+ let stepHadToolCalls = false;
114096
+ for await (const chunk of stream.fullStream) {
114097
+ switch (chunk.type) {
114098
+ case "start-step": {
114099
+ events.emit({
114100
+ type: export_EventType.STEP_STARTED,
114101
+ stepName: `step-${currentStepNumber++}`,
114102
+ timestamp: Date.now()
114103
+ });
114104
+ break;
114105
+ }
114106
+ case "text-delta": {
114107
+ hasAnyContent = true;
114108
+ if (!hasEmittedTextStart) {
114109
+ messageId = v4_default();
114110
+ events.emit({
114111
+ type: export_EventType.TEXT_MESSAGE_START,
114112
+ messageId,
114113
+ role: "assistant",
114114
+ timestamp: Date.now()
114115
+ });
114116
+ hasEmittedTextStart = true;
114117
+ }
113742
114118
  events.emit({
113743
- type: export_EventType.TEXT_MESSAGE_START,
114119
+ type: export_EventType.TEXT_MESSAGE_CONTENT,
113744
114120
  messageId,
113745
- role: "assistant",
114121
+ delta: chunk.text,
113746
114122
  timestamp: Date.now()
113747
114123
  });
113748
- hasEmittedTextStart = true;
114124
+ finalText += chunk.text;
114125
+ break;
113749
114126
  }
113750
- events.emit({
113751
- type: export_EventType.TEXT_MESSAGE_CONTENT,
113752
- messageId,
113753
- delta: chunk.text,
113754
- timestamp: Date.now()
113755
- });
113756
- finalText += chunk.text;
113757
- break;
113758
- }
113759
- case "reasoning-delta": {
113760
- logger2.debug("Reasoning", { text: chunk.text });
113761
- break;
113762
- }
113763
- case "tool-input-start": {
113764
- hasAnyContent = true;
113765
- const toolDef = tools.find((t) => t.name === chunk.toolName);
113766
- const annotations = getToolAnnotations(toolDef);
113767
- const toolCallStartEvent = {
113768
- type: export_EventType.TOOL_CALL_START,
113769
- toolCallId: chunk.id,
113770
- toolCallName: chunk.toolName,
113771
- parentMessageId: messageId ?? v4_default(),
113772
- timestamp: Date.now()
113773
- };
113774
- if (annotations) {
113775
- toolCallStartEvent.annotations = annotations;
114127
+ case "reasoning-delta": {
114128
+ logger2.debug("Reasoning", { text: chunk.text });
114129
+ break;
113776
114130
  }
113777
- events.emit(toolCallStartEvent);
113778
- activeToolCalls.set(chunk.id, { name: chunk.toolName, args: "" });
113779
- break;
113780
- }
113781
- case "tool-input-delta": {
113782
- const toolCall = activeToolCalls.get(chunk.id);
113783
- if (toolCall) {
113784
- toolCall.args += chunk.delta;
113785
- events.emit({
113786
- type: export_EventType.TOOL_CALL_ARGS,
114131
+ case "tool-input-start": {
114132
+ hasAnyContent = true;
114133
+ stepHadToolCalls = true;
114134
+ const toolDef = currentTools.find((t) => t.name === chunk.toolName);
114135
+ const annotations = getToolAnnotations(toolDef);
114136
+ const toolCallStartEvent = {
114137
+ type: export_EventType.TOOL_CALL_START,
113787
114138
  toolCallId: chunk.id,
113788
- delta: chunk.delta,
114139
+ toolCallName: chunk.toolName,
114140
+ parentMessageId: messageId ?? v4_default(),
113789
114141
  timestamp: Date.now()
113790
- });
114142
+ };
114143
+ if (annotations) {
114144
+ toolCallStartEvent.annotations = annotations;
114145
+ }
114146
+ events.emit(toolCallStartEvent);
114147
+ activeToolCalls.set(chunk.id, { name: chunk.toolName, args: "" });
114148
+ break;
113791
114149
  }
113792
- break;
113793
- }
113794
- case "tool-call": {
113795
- const toolCall = activeToolCalls.get(chunk.toolCallId);
113796
- const finalArgs = JSON.stringify(chunk.input);
113797
- if (toolCall && toolCall.args.length === 0) {
114150
+ case "tool-input-delta": {
114151
+ const toolCall = activeToolCalls.get(chunk.id);
114152
+ if (toolCall) {
114153
+ toolCall.args += chunk.delta;
114154
+ events.emit({
114155
+ type: export_EventType.TOOL_CALL_ARGS,
114156
+ toolCallId: chunk.id,
114157
+ delta: chunk.delta,
114158
+ timestamp: Date.now()
114159
+ });
114160
+ }
114161
+ break;
114162
+ }
114163
+ case "tool-call": {
114164
+ stepHadToolCalls = true;
114165
+ const toolCall = activeToolCalls.get(chunk.toolCallId);
114166
+ const finalArgs = JSON.stringify(chunk.input);
114167
+ if (toolCall && toolCall.args.length === 0) {
114168
+ events.emit({
114169
+ type: export_EventType.TOOL_CALL_ARGS,
114170
+ toolCallId: chunk.toolCallId,
114171
+ delta: finalArgs,
114172
+ timestamp: Date.now()
114173
+ });
114174
+ toolCall.args = finalArgs;
114175
+ }
113798
114176
  events.emit({
113799
- type: export_EventType.TOOL_CALL_ARGS,
114177
+ type: export_EventType.TOOL_CALL_END,
113800
114178
  toolCallId: chunk.toolCallId,
113801
- delta: finalArgs,
113802
114179
  timestamp: Date.now()
113803
114180
  });
113804
- toolCall.args = finalArgs;
114181
+ break;
114182
+ }
114183
+ case "tool-result": {
114184
+ logger2.toolResult(chunk.toolName, JSON.stringify(chunk.output));
114185
+ break;
114186
+ }
114187
+ case "finish-step": {
114188
+ events.emit({
114189
+ type: export_EventType.STEP_FINISHED,
114190
+ stepName: `step-${currentStepNumber - 1}`,
114191
+ timestamp: Date.now()
114192
+ });
114193
+ break;
114194
+ }
114195
+ case "error": {
114196
+ throw chunk.error;
113805
114197
  }
113806
- events.emit({
113807
- type: export_EventType.TOOL_CALL_END,
113808
- toolCallId: chunk.toolCallId,
113809
- timestamp: Date.now()
113810
- });
113811
- break;
113812
- }
113813
- case "tool-result": {
113814
- logger2.toolResult(chunk.toolName, JSON.stringify(chunk.output));
113815
- break;
113816
- }
113817
- case "finish-step": {
113818
- events.emit({
113819
- type: export_EventType.STEP_FINISHED,
113820
- stepName: `step-${currentStepNumber - 1}`,
113821
- timestamp: Date.now()
113822
- });
113823
- break;
113824
- }
113825
- case "error": {
113826
- throw chunk.error;
113827
114198
  }
113828
114199
  }
113829
- }
113830
- if (session.abortController?.signal.aborted) {
113831
- events.emit({
113832
- type: export_EventType.RUN_ERROR,
113833
- message: "Run aborted by user",
113834
- timestamp: Date.now()
114200
+ if (session.abortController?.signal.aborted) {
114201
+ span.endWithError("Run aborted by user");
114202
+ events.emit({
114203
+ type: export_EventType.RUN_ERROR,
114204
+ message: "Run aborted by user",
114205
+ timestamp: Date.now()
114206
+ });
114207
+ return { success: false, error: "Run aborted", conversationHistory: session.conversationHistory };
114208
+ }
114209
+ response = await stream.response;
114210
+ const stepMessages = this.sanitizeMessages(response.messages);
114211
+ allResponseMessages.push(...stepMessages);
114212
+ if (!stepHadToolCalls) {
114213
+ logger2.debug("Step had no tool calls, finishing run", { stepIteration });
114214
+ break;
114215
+ }
114216
+ currentMessages = [
114217
+ ...currentMessages,
114218
+ ...stepMessages
114219
+ ];
114220
+ logger2.debug("Continuing to next step after tool calls", {
114221
+ stepIteration,
114222
+ newMessageCount: currentMessages.length,
114223
+ updatedToolCount: session.tools.length
113835
114224
  });
113836
- return { success: false, error: "Run aborted", conversationHistory: session.conversationHistory };
113837
114225
  }
113838
114226
  if (hasEmittedTextStart && messageId) {
113839
114227
  events.emit({
@@ -113843,6 +114231,7 @@ class AISDKAgent {
113843
114231
  });
113844
114232
  }
113845
114233
  if (!hasAnyContent) {
114234
+ span.endWithError("Empty response from AI");
113846
114235
  events.emit({
113847
114236
  type: export_EventType.RUN_ERROR,
113848
114237
  message: "AI returned an empty response. This may be due to an ambiguous request. Please try being more specific.",
@@ -113854,23 +114243,16 @@ class AISDKAgent {
113854
114243
  conversationHistory: messages
113855
114244
  };
113856
114245
  }
113857
- const response = await stream.response;
113858
- const responseMessages = response.messages;
113859
- const firstResponseMsg = responseMessages[0];
113860
- const lastInputMsg = sanitizedInputMessages[sanitizedInputMessages.length - 1];
113861
- let includesInputMessages = false;
113862
- if (firstResponseMsg && lastInputMsg) {
113863
- const firstMsg = firstResponseMsg;
113864
- const lastMsg = lastInputMsg;
113865
- includesInputMessages = firstMsg.role === "user" && lastMsg.role === "user" && typeof firstMsg.content === "string" && typeof lastMsg.content === "string" && firstMsg.content === lastMsg.content;
113866
- }
113867
- const newMessages = includesInputMessages ? responseMessages.slice(session.conversationHistory.length) : responseMessages;
113868
- const sanitizedMessages = this.sanitizeMessages(newMessages);
113869
- session.conversationHistory.push(...sanitizedMessages);
114246
+ if (!response) {
114247
+ throw new Error("No response from AI SDK");
114248
+ }
114249
+ session.conversationHistory.push(...allResponseMessages);
113870
114250
  if (finalText) {
113871
114251
  logger2.aiResponse([finalText]);
113872
114252
  }
113873
- const traceId = popTraceIdForRun(runId);
114253
+ span.setOutput(finalText);
114254
+ const traceId = span.popTraceId();
114255
+ span.end();
113874
114256
  events.emit({
113875
114257
  type: export_EventType.RUN_FINISHED,
113876
114258
  threadId: session.threadId,
@@ -113883,6 +114265,7 @@ class AISDKAgent {
113883
114265
  conversationHistory: session.conversationHistory
113884
114266
  };
113885
114267
  } catch (error40) {
114268
+ span.endWithError(error40 instanceof Error ? error40.message : String(error40));
113886
114269
  logger2.error("Error calling AI SDK model", {
113887
114270
  error: error40 instanceof Error ? error40.message : "Unknown error",
113888
114271
  clientId: session.clientId
@@ -113902,6 +114285,18 @@ class AISDKAgent {
113902
114285
  errorCode = ErrorCode.RATE_LIMITED;
113903
114286
  }
113904
114287
  }
114288
+ if (!streamTextStarted) {
114289
+ const telemetryMetadata = originalInput.forwardedProps?.telemetryMetadata;
114290
+ span.recordError({
114291
+ runId,
114292
+ errorCategory: "pre_stream_error",
114293
+ errorMessage,
114294
+ sessionId: session.clientId,
114295
+ threadId: session.threadId,
114296
+ ipAddress: session.ipAddress,
114297
+ metadata: { errorCode, toolCount: tools.length, messageCount: messages.length, ...telemetryMetadata }
114298
+ });
114299
+ }
113905
114300
  events.emit({
113906
114301
  type: export_EventType.RUN_ERROR,
113907
114302
  message: errorCode,
@@ -113924,7 +114319,7 @@ class AISDKAgent {
113924
114319
  const result = await this.systemPrompt();
113925
114320
  return result || undefined;
113926
114321
  }
113927
- buildSystemMessages(configPrompt, runtimePrompt) {
114322
+ buildStaticSystemMessages(configPrompt, runtimePrompt) {
113928
114323
  const messages = [];
113929
114324
  if (configPrompt) {
113930
114325
  messages.push({ role: "system", content: configPrompt });
@@ -113934,6 +114329,16 @@ class AISDKAgent {
113934
114329
  }
113935
114330
  return messages.length > 0 ? messages : undefined;
113936
114331
  }
114332
+ buildStateMessage(state) {
114333
+ if (!state)
114334
+ return;
114335
+ return {
114336
+ role: "system",
114337
+ content: `Current application state:
114338
+
114339
+ ${JSON.stringify(state, null, 2)}`
114340
+ };
114341
+ }
113937
114342
  filterTools(tools) {
113938
114343
  if (!this.toolFilter) {
113939
114344
  return tools;
@@ -113951,7 +114356,7 @@ class AISDKAgent {
113951
114356
  }
113952
114357
  return filteredTools;
113953
114358
  }
113954
- createMcpToolExecutor(remoteTool, session) {
114359
+ createMcpToolExecutor(remoteTool, session, events) {
113955
114360
  return async (args, { toolCallId }) => {
113956
114361
  logger2.info("[MCP] Executing remote tool", {
113957
114362
  toolName: remoteTool.name,
@@ -113959,6 +114364,20 @@ class AISDKAgent {
113959
114364
  });
113960
114365
  try {
113961
114366
  const result = await remoteTool._remote.provider.executeTool(remoteTool._remote.originalName, args, session.currentMcpHeaders);
114367
+ if (isUseAIInternalResponse(result)) {
114368
+ switch (result._use_ai_type) {
114369
+ case "confirmation_required":
114370
+ if (isMcpConfirmationResponse(result)) {
114371
+ return handleMcpConfirmation(result, toolCallId, remoteTool.name, remoteTool._remote.originalName, args, remoteTool._remote.provider, session, events, session.currentMcpHeaders);
114372
+ }
114373
+ break;
114374
+ default:
114375
+ logger2.warn("[MCP] Unknown _use_ai_type, returning as-is", {
114376
+ toolCallId,
114377
+ type: result._use_ai_type
114378
+ });
114379
+ }
114380
+ }
113962
114381
  return result;
113963
114382
  } catch (error40) {
113964
114383
  const errorMsg = error40 instanceof Error ? error40.message : String(error40);
@@ -113977,7 +114396,14 @@ class AISDKAgent {
113977
114396
  for (const toolDef of tools) {
113978
114397
  const rawParams = toolDef.parameters;
113979
114398
  const inputSchema = rawParams && typeof rawParams === "object" ? { ...rawParams, type: rawParams.type || "object" } : { type: "object", properties: {} };
113980
- const baseExecutor = isRemoteTool(toolDef) ? this.createMcpToolExecutor(toolDef, session) : clientToolExecutor;
114399
+ let baseExecutor;
114400
+ if (isRemoteTool(toolDef)) {
114401
+ baseExecutor = this.createMcpToolExecutor(toolDef, session, events);
114402
+ } else if (isServerTool(toolDef)) {
114403
+ baseExecutor = createServerToolExecutor(toolDef, session, events);
114404
+ } else {
114405
+ baseExecutor = clientToolExecutor;
114406
+ }
113981
114407
  const execute = toolNeedsApproval(toolDef) ? createApprovalWrapper(toolDef, session, events, baseExecutor) : baseExecutor;
113982
114408
  toolsObject[toolDef.name] = {
113983
114409
  description: toolDef.description,
@@ -114055,12 +114481,1287 @@ ${val.text}`
114055
114481
  }
114056
114482
  }
114057
114483
  }
114484
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/Options.js
114485
+ var ignoreOverride2 = Symbol("Let zodToJsonSchema decide on which parser to use");
114486
+ var defaultOptions2 = {
114487
+ name: undefined,
114488
+ $refStrategy: "root",
114489
+ basePath: ["#"],
114490
+ effectStrategy: "input",
114491
+ pipeStrategy: "all",
114492
+ dateStrategy: "format:date-time",
114493
+ mapStrategy: "entries",
114494
+ removeAdditionalStrategy: "passthrough",
114495
+ allowedAdditionalProperties: true,
114496
+ rejectedAdditionalProperties: false,
114497
+ definitionPath: "definitions",
114498
+ target: "jsonSchema7",
114499
+ strictUnions: false,
114500
+ definitions: {},
114501
+ errorMessages: false,
114502
+ markdownDescription: false,
114503
+ patternStrategy: "escape",
114504
+ applyRegexFlags: false,
114505
+ emailStrategy: "format:email",
114506
+ base64Strategy: "contentEncoding:base64",
114507
+ nameStrategy: "ref",
114508
+ openAiAnyTypeName: "OpenAiAnyType"
114509
+ };
114510
+ var getDefaultOptions2 = (options) => typeof options === "string" ? {
114511
+ ...defaultOptions2,
114512
+ name: options
114513
+ } : {
114514
+ ...defaultOptions2,
114515
+ ...options
114516
+ };
114517
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/Refs.js
114518
+ var getRefs2 = (options) => {
114519
+ const _options = getDefaultOptions2(options);
114520
+ const currentPath = _options.name !== undefined ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
114521
+ return {
114522
+ ..._options,
114523
+ flags: { hasReferencedOpenAiAnyType: false },
114524
+ currentPath,
114525
+ propertyPath: undefined,
114526
+ seen: new Map(Object.entries(_options.definitions).map(([name15, def]) => [
114527
+ def._def,
114528
+ {
114529
+ def: def._def,
114530
+ path: [..._options.basePath, _options.definitionPath, name15],
114531
+ jsonSchema: undefined
114532
+ }
114533
+ ]))
114534
+ };
114535
+ };
114536
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
114537
+ function addErrorMessage(res, key, errorMessage, refs) {
114538
+ if (!refs?.errorMessages)
114539
+ return;
114540
+ if (errorMessage) {
114541
+ res.errorMessage = {
114542
+ ...res.errorMessage,
114543
+ [key]: errorMessage
114544
+ };
114545
+ }
114546
+ }
114547
+ function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
114548
+ res[key] = value;
114549
+ addErrorMessage(res, key, errorMessage, refs);
114550
+ }
114551
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
114552
+ var getRelativePath2 = (pathA, pathB) => {
114553
+ let i = 0;
114554
+ for (;i < pathA.length && i < pathB.length; i++) {
114555
+ if (pathA[i] !== pathB[i])
114556
+ break;
114557
+ }
114558
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
114559
+ };
114560
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/any.js
114561
+ function parseAnyDef2(refs) {
114562
+ if (refs.target !== "openAi") {
114563
+ return {};
114564
+ }
114565
+ const anyDefinitionPath = [
114566
+ ...refs.basePath,
114567
+ refs.definitionPath,
114568
+ refs.openAiAnyTypeName
114569
+ ];
114570
+ refs.flags.hasReferencedOpenAiAnyType = true;
114571
+ return {
114572
+ $ref: refs.$refStrategy === "relative" ? getRelativePath2(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/")
114573
+ };
114574
+ }
114575
+
114576
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
114577
+ function parseArrayDef2(def, refs) {
114578
+ const res = {
114579
+ type: "array"
114580
+ };
114581
+ if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
114582
+ res.items = parseDef2(def.type._def, {
114583
+ ...refs,
114584
+ currentPath: [...refs.currentPath, "items"]
114585
+ });
114586
+ }
114587
+ if (def.minLength) {
114588
+ setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
114589
+ }
114590
+ if (def.maxLength) {
114591
+ setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
114592
+ }
114593
+ if (def.exactLength) {
114594
+ setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
114595
+ setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
114596
+ }
114597
+ return res;
114598
+ }
114599
+
114600
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
114601
+ function parseBigintDef2(def, refs) {
114602
+ const res = {
114603
+ type: "integer",
114604
+ format: "int64"
114605
+ };
114606
+ if (!def.checks)
114607
+ return res;
114608
+ for (const check2 of def.checks) {
114609
+ switch (check2.kind) {
114610
+ case "min":
114611
+ if (refs.target === "jsonSchema7") {
114612
+ if (check2.inclusive) {
114613
+ setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);
114614
+ } else {
114615
+ setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs);
114616
+ }
114617
+ } else {
114618
+ if (!check2.inclusive) {
114619
+ res.exclusiveMinimum = true;
114620
+ }
114621
+ setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);
114622
+ }
114623
+ break;
114624
+ case "max":
114625
+ if (refs.target === "jsonSchema7") {
114626
+ if (check2.inclusive) {
114627
+ setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);
114628
+ } else {
114629
+ setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs);
114630
+ }
114631
+ } else {
114632
+ if (!check2.inclusive) {
114633
+ res.exclusiveMaximum = true;
114634
+ }
114635
+ setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);
114636
+ }
114637
+ break;
114638
+ case "multipleOf":
114639
+ setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs);
114640
+ break;
114641
+ }
114642
+ }
114643
+ return res;
114644
+ }
114645
+
114646
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
114647
+ function parseBooleanDef2() {
114648
+ return {
114649
+ type: "boolean"
114650
+ };
114651
+ }
114652
+
114653
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
114654
+ function parseBrandedDef2(_def, refs) {
114655
+ return parseDef2(_def.type._def, refs);
114656
+ }
114657
+
114658
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
114659
+ var parseCatchDef2 = (def, refs) => {
114660
+ return parseDef2(def.innerType._def, refs);
114661
+ };
114662
+
114663
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/date.js
114664
+ function parseDateDef2(def, refs, overrideDateStrategy) {
114665
+ const strategy = overrideDateStrategy ?? refs.dateStrategy;
114666
+ if (Array.isArray(strategy)) {
114667
+ return {
114668
+ anyOf: strategy.map((item, i) => parseDateDef2(def, refs, item))
114669
+ };
114670
+ }
114671
+ switch (strategy) {
114672
+ case "string":
114673
+ case "format:date-time":
114674
+ return {
114675
+ type: "string",
114676
+ format: "date-time"
114677
+ };
114678
+ case "format:date":
114679
+ return {
114680
+ type: "string",
114681
+ format: "date"
114682
+ };
114683
+ case "integer":
114684
+ return integerDateParser2(def, refs);
114685
+ }
114686
+ }
114687
+ var integerDateParser2 = (def, refs) => {
114688
+ const res = {
114689
+ type: "integer",
114690
+ format: "unix-time"
114691
+ };
114692
+ if (refs.target === "openApi3") {
114693
+ return res;
114694
+ }
114695
+ for (const check2 of def.checks) {
114696
+ switch (check2.kind) {
114697
+ case "min":
114698
+ setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);
114699
+ break;
114700
+ case "max":
114701
+ setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);
114702
+ break;
114703
+ }
114704
+ }
114705
+ return res;
114706
+ };
114707
+
114708
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/default.js
114709
+ function parseDefaultDef2(_def, refs) {
114710
+ return {
114711
+ ...parseDef2(_def.innerType._def, refs),
114712
+ default: _def.defaultValue()
114713
+ };
114714
+ }
114715
+
114716
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
114717
+ function parseEffectsDef2(_def, refs) {
114718
+ return refs.effectStrategy === "input" ? parseDef2(_def.schema._def, refs) : parseAnyDef2(refs);
114719
+ }
114720
+
114721
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
114722
+ function parseEnumDef2(def) {
114723
+ return {
114724
+ type: "string",
114725
+ enum: Array.from(def.values)
114726
+ };
114727
+ }
114728
+
114729
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
114730
+ var isJsonSchema7AllOfType2 = (type) => {
114731
+ if ("type" in type && type.type === "string")
114732
+ return false;
114733
+ return "allOf" in type;
114734
+ };
114735
+ function parseIntersectionDef2(def, refs) {
114736
+ const allOf = [
114737
+ parseDef2(def.left._def, {
114738
+ ...refs,
114739
+ currentPath: [...refs.currentPath, "allOf", "0"]
114740
+ }),
114741
+ parseDef2(def.right._def, {
114742
+ ...refs,
114743
+ currentPath: [...refs.currentPath, "allOf", "1"]
114744
+ })
114745
+ ].filter((x) => !!x);
114746
+ let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : undefined;
114747
+ const mergedAllOf = [];
114748
+ allOf.forEach((schema) => {
114749
+ if (isJsonSchema7AllOfType2(schema)) {
114750
+ mergedAllOf.push(...schema.allOf);
114751
+ if (schema.unevaluatedProperties === undefined) {
114752
+ unevaluatedProperties = undefined;
114753
+ }
114754
+ } else {
114755
+ let nestedSchema = schema;
114756
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
114757
+ const { additionalProperties, ...rest } = schema;
114758
+ nestedSchema = rest;
114759
+ } else {
114760
+ unevaluatedProperties = undefined;
114761
+ }
114762
+ mergedAllOf.push(nestedSchema);
114763
+ }
114764
+ });
114765
+ return mergedAllOf.length ? {
114766
+ allOf: mergedAllOf,
114767
+ ...unevaluatedProperties
114768
+ } : undefined;
114769
+ }
114770
+
114771
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
114772
+ function parseLiteralDef2(def, refs) {
114773
+ const parsedType4 = typeof def.value;
114774
+ if (parsedType4 !== "bigint" && parsedType4 !== "number" && parsedType4 !== "boolean" && parsedType4 !== "string") {
114775
+ return {
114776
+ type: Array.isArray(def.value) ? "array" : "object"
114777
+ };
114778
+ }
114779
+ if (refs.target === "openApi3") {
114780
+ return {
114781
+ type: parsedType4 === "bigint" ? "integer" : parsedType4,
114782
+ enum: [def.value]
114783
+ };
114784
+ }
114785
+ return {
114786
+ type: parsedType4 === "bigint" ? "integer" : parsedType4,
114787
+ const: def.value
114788
+ };
114789
+ }
114790
+
114791
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
114792
+ var emojiRegex3 = undefined;
114793
+ var zodPatterns2 = {
114794
+ cuid: /^[cC][^\s-]{8,}$/,
114795
+ cuid2: /^[0-9a-z]+$/,
114796
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
114797
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
114798
+ emoji: () => {
114799
+ if (emojiRegex3 === undefined) {
114800
+ emojiRegex3 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
114801
+ }
114802
+ return emojiRegex3;
114803
+ },
114804
+ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
114805
+ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
114806
+ ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
114807
+ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
114808
+ ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
114809
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
114810
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
114811
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
114812
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
114813
+ };
114814
+ function parseStringDef2(def, refs) {
114815
+ const res = {
114816
+ type: "string"
114817
+ };
114818
+ if (def.checks) {
114819
+ for (const check2 of def.checks) {
114820
+ switch (check2.kind) {
114821
+ case "min":
114822
+ setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs);
114823
+ break;
114824
+ case "max":
114825
+ setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs);
114826
+ break;
114827
+ case "email":
114828
+ switch (refs.emailStrategy) {
114829
+ case "format:email":
114830
+ addFormat2(res, "email", check2.message, refs);
114831
+ break;
114832
+ case "format:idn-email":
114833
+ addFormat2(res, "idn-email", check2.message, refs);
114834
+ break;
114835
+ case "pattern:zod":
114836
+ addPattern2(res, zodPatterns2.email, check2.message, refs);
114837
+ break;
114838
+ }
114839
+ break;
114840
+ case "url":
114841
+ addFormat2(res, "uri", check2.message, refs);
114842
+ break;
114843
+ case "uuid":
114844
+ addFormat2(res, "uuid", check2.message, refs);
114845
+ break;
114846
+ case "regex":
114847
+ addPattern2(res, check2.regex, check2.message, refs);
114848
+ break;
114849
+ case "cuid":
114850
+ addPattern2(res, zodPatterns2.cuid, check2.message, refs);
114851
+ break;
114852
+ case "cuid2":
114853
+ addPattern2(res, zodPatterns2.cuid2, check2.message, refs);
114854
+ break;
114855
+ case "startsWith":
114856
+ addPattern2(res, RegExp(`^${escapeLiteralCheckValue2(check2.value, refs)}`), check2.message, refs);
114857
+ break;
114858
+ case "endsWith":
114859
+ addPattern2(res, RegExp(`${escapeLiteralCheckValue2(check2.value, refs)}$`), check2.message, refs);
114860
+ break;
114861
+ case "datetime":
114862
+ addFormat2(res, "date-time", check2.message, refs);
114863
+ break;
114864
+ case "date":
114865
+ addFormat2(res, "date", check2.message, refs);
114866
+ break;
114867
+ case "time":
114868
+ addFormat2(res, "time", check2.message, refs);
114869
+ break;
114870
+ case "duration":
114871
+ addFormat2(res, "duration", check2.message, refs);
114872
+ break;
114873
+ case "length":
114874
+ setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs);
114875
+ setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs);
114876
+ break;
114877
+ case "includes": {
114878
+ addPattern2(res, RegExp(escapeLiteralCheckValue2(check2.value, refs)), check2.message, refs);
114879
+ break;
114880
+ }
114881
+ case "ip": {
114882
+ if (check2.version !== "v6") {
114883
+ addFormat2(res, "ipv4", check2.message, refs);
114884
+ }
114885
+ if (check2.version !== "v4") {
114886
+ addFormat2(res, "ipv6", check2.message, refs);
114887
+ }
114888
+ break;
114889
+ }
114890
+ case "base64url":
114891
+ addPattern2(res, zodPatterns2.base64url, check2.message, refs);
114892
+ break;
114893
+ case "jwt":
114894
+ addPattern2(res, zodPatterns2.jwt, check2.message, refs);
114895
+ break;
114896
+ case "cidr": {
114897
+ if (check2.version !== "v6") {
114898
+ addPattern2(res, zodPatterns2.ipv4Cidr, check2.message, refs);
114899
+ }
114900
+ if (check2.version !== "v4") {
114901
+ addPattern2(res, zodPatterns2.ipv6Cidr, check2.message, refs);
114902
+ }
114903
+ break;
114904
+ }
114905
+ case "emoji":
114906
+ addPattern2(res, zodPatterns2.emoji(), check2.message, refs);
114907
+ break;
114908
+ case "ulid": {
114909
+ addPattern2(res, zodPatterns2.ulid, check2.message, refs);
114910
+ break;
114911
+ }
114912
+ case "base64": {
114913
+ switch (refs.base64Strategy) {
114914
+ case "format:binary": {
114915
+ addFormat2(res, "binary", check2.message, refs);
114916
+ break;
114917
+ }
114918
+ case "contentEncoding:base64": {
114919
+ setResponseValueAndErrors(res, "contentEncoding", "base64", check2.message, refs);
114920
+ break;
114921
+ }
114922
+ case "pattern:zod": {
114923
+ addPattern2(res, zodPatterns2.base64, check2.message, refs);
114924
+ break;
114925
+ }
114926
+ }
114927
+ break;
114928
+ }
114929
+ case "nanoid": {
114930
+ addPattern2(res, zodPatterns2.nanoid, check2.message, refs);
114931
+ }
114932
+ case "toLowerCase":
114933
+ case "toUpperCase":
114934
+ case "trim":
114935
+ break;
114936
+ default:
114937
+ ((_) => {})(check2);
114938
+ }
114939
+ }
114940
+ }
114941
+ return res;
114942
+ }
114943
+ function escapeLiteralCheckValue2(literal2, refs) {
114944
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric2(literal2) : literal2;
114945
+ }
114946
+ var ALPHA_NUMERIC2 = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
114947
+ function escapeNonAlphaNumeric2(source) {
114948
+ let result = "";
114949
+ for (let i = 0;i < source.length; i++) {
114950
+ if (!ALPHA_NUMERIC2.has(source[i])) {
114951
+ result += "\\";
114952
+ }
114953
+ result += source[i];
114954
+ }
114955
+ return result;
114956
+ }
114957
+ function addFormat2(schema, value, message, refs) {
114958
+ if (schema.format || schema.anyOf?.some((x) => x.format)) {
114959
+ if (!schema.anyOf) {
114960
+ schema.anyOf = [];
114961
+ }
114962
+ if (schema.format) {
114963
+ schema.anyOf.push({
114964
+ format: schema.format,
114965
+ ...schema.errorMessage && refs.errorMessages && {
114966
+ errorMessage: { format: schema.errorMessage.format }
114967
+ }
114968
+ });
114969
+ delete schema.format;
114970
+ if (schema.errorMessage) {
114971
+ delete schema.errorMessage.format;
114972
+ if (Object.keys(schema.errorMessage).length === 0) {
114973
+ delete schema.errorMessage;
114974
+ }
114975
+ }
114976
+ }
114977
+ schema.anyOf.push({
114978
+ format: value,
114979
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
114980
+ });
114981
+ } else {
114982
+ setResponseValueAndErrors(schema, "format", value, message, refs);
114983
+ }
114984
+ }
114985
+ function addPattern2(schema, regex, message, refs) {
114986
+ if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
114987
+ if (!schema.allOf) {
114988
+ schema.allOf = [];
114989
+ }
114990
+ if (schema.pattern) {
114991
+ schema.allOf.push({
114992
+ pattern: schema.pattern,
114993
+ ...schema.errorMessage && refs.errorMessages && {
114994
+ errorMessage: { pattern: schema.errorMessage.pattern }
114995
+ }
114996
+ });
114997
+ delete schema.pattern;
114998
+ if (schema.errorMessage) {
114999
+ delete schema.errorMessage.pattern;
115000
+ if (Object.keys(schema.errorMessage).length === 0) {
115001
+ delete schema.errorMessage;
115002
+ }
115003
+ }
115004
+ }
115005
+ schema.allOf.push({
115006
+ pattern: stringifyRegExpWithFlags2(regex, refs),
115007
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
115008
+ });
115009
+ } else {
115010
+ setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags2(regex, refs), message, refs);
115011
+ }
115012
+ }
115013
+ function stringifyRegExpWithFlags2(regex, refs) {
115014
+ if (!refs.applyRegexFlags || !regex.flags) {
115015
+ return regex.source;
115016
+ }
115017
+ const flags = {
115018
+ i: regex.flags.includes("i"),
115019
+ m: regex.flags.includes("m"),
115020
+ s: regex.flags.includes("s")
115021
+ };
115022
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
115023
+ let pattern = "";
115024
+ let isEscaped = false;
115025
+ let inCharGroup = false;
115026
+ let inCharRange = false;
115027
+ for (let i = 0;i < source.length; i++) {
115028
+ if (isEscaped) {
115029
+ pattern += source[i];
115030
+ isEscaped = false;
115031
+ continue;
115032
+ }
115033
+ if (flags.i) {
115034
+ if (inCharGroup) {
115035
+ if (source[i].match(/[a-z]/)) {
115036
+ if (inCharRange) {
115037
+ pattern += source[i];
115038
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
115039
+ inCharRange = false;
115040
+ } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
115041
+ pattern += source[i];
115042
+ inCharRange = true;
115043
+ } else {
115044
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
115045
+ }
115046
+ continue;
115047
+ }
115048
+ } else if (source[i].match(/[a-z]/)) {
115049
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
115050
+ continue;
115051
+ }
115052
+ }
115053
+ if (flags.m) {
115054
+ if (source[i] === "^") {
115055
+ pattern += `(^|(?<=[\r
115056
+ ]))`;
115057
+ continue;
115058
+ } else if (source[i] === "$") {
115059
+ pattern += `($|(?=[\r
115060
+ ]))`;
115061
+ continue;
115062
+ }
115063
+ }
115064
+ if (flags.s && source[i] === ".") {
115065
+ pattern += inCharGroup ? `${source[i]}\r
115066
+ ` : `[${source[i]}\r
115067
+ ]`;
115068
+ continue;
115069
+ }
115070
+ pattern += source[i];
115071
+ if (source[i] === "\\") {
115072
+ isEscaped = true;
115073
+ } else if (inCharGroup && source[i] === "]") {
115074
+ inCharGroup = false;
115075
+ } else if (!inCharGroup && source[i] === "[") {
115076
+ inCharGroup = true;
115077
+ }
115078
+ }
115079
+ try {
115080
+ new RegExp(pattern);
115081
+ } catch {
115082
+ console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
115083
+ return regex.source;
115084
+ }
115085
+ return pattern;
115086
+ }
115087
+
115088
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
115089
+ function parseRecordDef2(def, refs) {
115090
+ if (refs.target === "openAi") {
115091
+ console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
115092
+ }
115093
+ if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
115094
+ return {
115095
+ type: "object",
115096
+ required: def.keyType._def.values,
115097
+ properties: def.keyType._def.values.reduce((acc, key) => ({
115098
+ ...acc,
115099
+ [key]: parseDef2(def.valueType._def, {
115100
+ ...refs,
115101
+ currentPath: [...refs.currentPath, "properties", key]
115102
+ }) ?? parseAnyDef2(refs)
115103
+ }), {}),
115104
+ additionalProperties: refs.rejectedAdditionalProperties
115105
+ };
115106
+ }
115107
+ const schema = {
115108
+ type: "object",
115109
+ additionalProperties: parseDef2(def.valueType._def, {
115110
+ ...refs,
115111
+ currentPath: [...refs.currentPath, "additionalProperties"]
115112
+ }) ?? refs.allowedAdditionalProperties
115113
+ };
115114
+ if (refs.target === "openApi3") {
115115
+ return schema;
115116
+ }
115117
+ if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
115118
+ const { type, ...keyType } = parseStringDef2(def.keyType._def, refs);
115119
+ return {
115120
+ ...schema,
115121
+ propertyNames: keyType
115122
+ };
115123
+ } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
115124
+ return {
115125
+ ...schema,
115126
+ propertyNames: {
115127
+ enum: def.keyType._def.values
115128
+ }
115129
+ };
115130
+ } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
115131
+ const { type, ...keyType } = parseBrandedDef2(def.keyType._def, refs);
115132
+ return {
115133
+ ...schema,
115134
+ propertyNames: keyType
115135
+ };
115136
+ }
115137
+ return schema;
115138
+ }
115139
+
115140
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/map.js
115141
+ function parseMapDef2(def, refs) {
115142
+ if (refs.mapStrategy === "record") {
115143
+ return parseRecordDef2(def, refs);
115144
+ }
115145
+ const keys = parseDef2(def.keyType._def, {
115146
+ ...refs,
115147
+ currentPath: [...refs.currentPath, "items", "items", "0"]
115148
+ }) || parseAnyDef2(refs);
115149
+ const values = parseDef2(def.valueType._def, {
115150
+ ...refs,
115151
+ currentPath: [...refs.currentPath, "items", "items", "1"]
115152
+ }) || parseAnyDef2(refs);
115153
+ return {
115154
+ type: "array",
115155
+ maxItems: 125,
115156
+ items: {
115157
+ type: "array",
115158
+ items: [keys, values],
115159
+ minItems: 2,
115160
+ maxItems: 2
115161
+ }
115162
+ };
115163
+ }
115164
+
115165
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
115166
+ function parseNativeEnumDef2(def) {
115167
+ const object3 = def.values;
115168
+ const actualKeys = Object.keys(def.values).filter((key) => {
115169
+ return typeof object3[object3[key]] !== "number";
115170
+ });
115171
+ const actualValues = actualKeys.map((key) => object3[key]);
115172
+ const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
115173
+ return {
115174
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
115175
+ enum: actualValues
115176
+ };
115177
+ }
115178
+
115179
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/never.js
115180
+ function parseNeverDef2(refs) {
115181
+ return refs.target === "openAi" ? undefined : {
115182
+ not: parseAnyDef2({
115183
+ ...refs,
115184
+ currentPath: [...refs.currentPath, "not"]
115185
+ })
115186
+ };
115187
+ }
115188
+
115189
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/null.js
115190
+ function parseNullDef2(refs) {
115191
+ return refs.target === "openApi3" ? {
115192
+ enum: ["null"],
115193
+ nullable: true
115194
+ } : {
115195
+ type: "null"
115196
+ };
115197
+ }
115198
+
115199
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/union.js
115200
+ var primitiveMappings2 = {
115201
+ ZodString: "string",
115202
+ ZodNumber: "number",
115203
+ ZodBigInt: "integer",
115204
+ ZodBoolean: "boolean",
115205
+ ZodNull: "null"
115206
+ };
115207
+ function parseUnionDef2(def, refs) {
115208
+ if (refs.target === "openApi3")
115209
+ return asAnyOf2(def, refs);
115210
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
115211
+ if (options.every((x) => (x._def.typeName in primitiveMappings2) && (!x._def.checks || !x._def.checks.length))) {
115212
+ const types2 = options.reduce((types3, x) => {
115213
+ const type = primitiveMappings2[x._def.typeName];
115214
+ return type && !types3.includes(type) ? [...types3, type] : types3;
115215
+ }, []);
115216
+ return {
115217
+ type: types2.length > 1 ? types2 : types2[0]
115218
+ };
115219
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
115220
+ const types2 = options.reduce((acc, x) => {
115221
+ const type = typeof x._def.value;
115222
+ switch (type) {
115223
+ case "string":
115224
+ case "number":
115225
+ case "boolean":
115226
+ return [...acc, type];
115227
+ case "bigint":
115228
+ return [...acc, "integer"];
115229
+ case "object":
115230
+ if (x._def.value === null)
115231
+ return [...acc, "null"];
115232
+ case "symbol":
115233
+ case "undefined":
115234
+ case "function":
115235
+ default:
115236
+ return acc;
115237
+ }
115238
+ }, []);
115239
+ if (types2.length === options.length) {
115240
+ const uniqueTypes = types2.filter((x, i, a) => a.indexOf(x) === i);
115241
+ return {
115242
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
115243
+ enum: options.reduce((acc, x) => {
115244
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
115245
+ }, [])
115246
+ };
115247
+ }
115248
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
115249
+ return {
115250
+ type: "string",
115251
+ enum: options.reduce((acc, x) => [
115252
+ ...acc,
115253
+ ...x._def.values.filter((x2) => !acc.includes(x2))
115254
+ ], [])
115255
+ };
115256
+ }
115257
+ return asAnyOf2(def, refs);
115258
+ }
115259
+ var asAnyOf2 = (def, refs) => {
115260
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef2(x._def, {
115261
+ ...refs,
115262
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
115263
+ })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
115264
+ return anyOf.length ? { anyOf } : undefined;
115265
+ };
115266
+
115267
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
115268
+ function parseNullableDef2(def, refs) {
115269
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
115270
+ if (refs.target === "openApi3") {
115271
+ return {
115272
+ type: primitiveMappings2[def.innerType._def.typeName],
115273
+ nullable: true
115274
+ };
115275
+ }
115276
+ return {
115277
+ type: [
115278
+ primitiveMappings2[def.innerType._def.typeName],
115279
+ "null"
115280
+ ]
115281
+ };
115282
+ }
115283
+ if (refs.target === "openApi3") {
115284
+ const base2 = parseDef2(def.innerType._def, {
115285
+ ...refs,
115286
+ currentPath: [...refs.currentPath]
115287
+ });
115288
+ if (base2 && "$ref" in base2)
115289
+ return { allOf: [base2], nullable: true };
115290
+ return base2 && { ...base2, nullable: true };
115291
+ }
115292
+ const base = parseDef2(def.innerType._def, {
115293
+ ...refs,
115294
+ currentPath: [...refs.currentPath, "anyOf", "0"]
115295
+ });
115296
+ return base && { anyOf: [base, { type: "null" }] };
115297
+ }
115298
+
115299
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/number.js
115300
+ function parseNumberDef2(def, refs) {
115301
+ const res = {
115302
+ type: "number"
115303
+ };
115304
+ if (!def.checks)
115305
+ return res;
115306
+ for (const check2 of def.checks) {
115307
+ switch (check2.kind) {
115308
+ case "int":
115309
+ res.type = "integer";
115310
+ addErrorMessage(res, "type", check2.message, refs);
115311
+ break;
115312
+ case "min":
115313
+ if (refs.target === "jsonSchema7") {
115314
+ if (check2.inclusive) {
115315
+ setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);
115316
+ } else {
115317
+ setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs);
115318
+ }
115319
+ } else {
115320
+ if (!check2.inclusive) {
115321
+ res.exclusiveMinimum = true;
115322
+ }
115323
+ setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);
115324
+ }
115325
+ break;
115326
+ case "max":
115327
+ if (refs.target === "jsonSchema7") {
115328
+ if (check2.inclusive) {
115329
+ setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);
115330
+ } else {
115331
+ setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs);
115332
+ }
115333
+ } else {
115334
+ if (!check2.inclusive) {
115335
+ res.exclusiveMaximum = true;
115336
+ }
115337
+ setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);
115338
+ }
115339
+ break;
115340
+ case "multipleOf":
115341
+ setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs);
115342
+ break;
115343
+ }
115344
+ }
115345
+ return res;
115346
+ }
115347
+
115348
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/object.js
115349
+ function parseObjectDef2(def, refs) {
115350
+ const forceOptionalIntoNullable = refs.target === "openAi";
115351
+ const result = {
115352
+ type: "object",
115353
+ properties: {}
115354
+ };
115355
+ const required2 = [];
115356
+ const shape = def.shape();
115357
+ for (const propName in shape) {
115358
+ let propDef = shape[propName];
115359
+ if (propDef === undefined || propDef._def === undefined) {
115360
+ continue;
115361
+ }
115362
+ let propOptional = safeIsOptional2(propDef);
115363
+ if (propOptional && forceOptionalIntoNullable) {
115364
+ if (propDef._def.typeName === "ZodOptional") {
115365
+ propDef = propDef._def.innerType;
115366
+ }
115367
+ if (!propDef.isNullable()) {
115368
+ propDef = propDef.nullable();
115369
+ }
115370
+ propOptional = false;
115371
+ }
115372
+ const parsedDef = parseDef2(propDef._def, {
115373
+ ...refs,
115374
+ currentPath: [...refs.currentPath, "properties", propName],
115375
+ propertyPath: [...refs.currentPath, "properties", propName]
115376
+ });
115377
+ if (parsedDef === undefined) {
115378
+ continue;
115379
+ }
115380
+ result.properties[propName] = parsedDef;
115381
+ if (!propOptional) {
115382
+ required2.push(propName);
115383
+ }
115384
+ }
115385
+ if (required2.length) {
115386
+ result.required = required2;
115387
+ }
115388
+ const additionalProperties = decideAdditionalProperties2(def, refs);
115389
+ if (additionalProperties !== undefined) {
115390
+ result.additionalProperties = additionalProperties;
115391
+ }
115392
+ return result;
115393
+ }
115394
+ function decideAdditionalProperties2(def, refs) {
115395
+ if (def.catchall._def.typeName !== "ZodNever") {
115396
+ return parseDef2(def.catchall._def, {
115397
+ ...refs,
115398
+ currentPath: [...refs.currentPath, "additionalProperties"]
115399
+ });
115400
+ }
115401
+ switch (def.unknownKeys) {
115402
+ case "passthrough":
115403
+ return refs.allowedAdditionalProperties;
115404
+ case "strict":
115405
+ return refs.rejectedAdditionalProperties;
115406
+ case "strip":
115407
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
115408
+ }
115409
+ }
115410
+ function safeIsOptional2(schema) {
115411
+ try {
115412
+ return schema.isOptional();
115413
+ } catch {
115414
+ return true;
115415
+ }
115416
+ }
115417
+
115418
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
115419
+ var parseOptionalDef2 = (def, refs) => {
115420
+ if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
115421
+ return parseDef2(def.innerType._def, refs);
115422
+ }
115423
+ const innerSchema = parseDef2(def.innerType._def, {
115424
+ ...refs,
115425
+ currentPath: [...refs.currentPath, "anyOf", "1"]
115426
+ });
115427
+ return innerSchema ? {
115428
+ anyOf: [
115429
+ {
115430
+ not: parseAnyDef2(refs)
115431
+ },
115432
+ innerSchema
115433
+ ]
115434
+ } : parseAnyDef2(refs);
115435
+ };
115436
+
115437
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
115438
+ var parsePipelineDef2 = (def, refs) => {
115439
+ if (refs.pipeStrategy === "input") {
115440
+ return parseDef2(def.in._def, refs);
115441
+ } else if (refs.pipeStrategy === "output") {
115442
+ return parseDef2(def.out._def, refs);
115443
+ }
115444
+ const a = parseDef2(def.in._def, {
115445
+ ...refs,
115446
+ currentPath: [...refs.currentPath, "allOf", "0"]
115447
+ });
115448
+ const b = parseDef2(def.out._def, {
115449
+ ...refs,
115450
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
115451
+ });
115452
+ return {
115453
+ allOf: [a, b].filter((x) => x !== undefined)
115454
+ };
115455
+ };
115456
+
115457
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
115458
+ function parsePromiseDef2(def, refs) {
115459
+ return parseDef2(def.type._def, refs);
115460
+ }
115461
+
115462
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/set.js
115463
+ function parseSetDef2(def, refs) {
115464
+ const items = parseDef2(def.valueType._def, {
115465
+ ...refs,
115466
+ currentPath: [...refs.currentPath, "items"]
115467
+ });
115468
+ const schema = {
115469
+ type: "array",
115470
+ uniqueItems: true,
115471
+ items
115472
+ };
115473
+ if (def.minSize) {
115474
+ setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
115475
+ }
115476
+ if (def.maxSize) {
115477
+ setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
115478
+ }
115479
+ return schema;
115480
+ }
115481
+
115482
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
115483
+ function parseTupleDef2(def, refs) {
115484
+ if (def.rest) {
115485
+ return {
115486
+ type: "array",
115487
+ minItems: def.items.length,
115488
+ items: def.items.map((x, i) => parseDef2(x._def, {
115489
+ ...refs,
115490
+ currentPath: [...refs.currentPath, "items", `${i}`]
115491
+ })).reduce((acc, x) => x === undefined ? acc : [...acc, x], []),
115492
+ additionalItems: parseDef2(def.rest._def, {
115493
+ ...refs,
115494
+ currentPath: [...refs.currentPath, "additionalItems"]
115495
+ })
115496
+ };
115497
+ } else {
115498
+ return {
115499
+ type: "array",
115500
+ minItems: def.items.length,
115501
+ maxItems: def.items.length,
115502
+ items: def.items.map((x, i) => parseDef2(x._def, {
115503
+ ...refs,
115504
+ currentPath: [...refs.currentPath, "items", `${i}`]
115505
+ })).reduce((acc, x) => x === undefined ? acc : [...acc, x], [])
115506
+ };
115507
+ }
115508
+ }
115509
+
115510
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
115511
+ function parseUndefinedDef2(refs) {
115512
+ return {
115513
+ not: parseAnyDef2(refs)
115514
+ };
115515
+ }
115516
+
115517
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
115518
+ function parseUnknownDef2(refs) {
115519
+ return parseAnyDef2(refs);
115520
+ }
115521
+
115522
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
115523
+ var parseReadonlyDef2 = (def, refs) => {
115524
+ return parseDef2(def.innerType._def, refs);
115525
+ };
115526
+
115527
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/selectParser.js
115528
+ var selectParser2 = (def, typeName, refs) => {
115529
+ switch (typeName) {
115530
+ case ZodFirstPartyTypeKind.ZodString:
115531
+ return parseStringDef2(def, refs);
115532
+ case ZodFirstPartyTypeKind.ZodNumber:
115533
+ return parseNumberDef2(def, refs);
115534
+ case ZodFirstPartyTypeKind.ZodObject:
115535
+ return parseObjectDef2(def, refs);
115536
+ case ZodFirstPartyTypeKind.ZodBigInt:
115537
+ return parseBigintDef2(def, refs);
115538
+ case ZodFirstPartyTypeKind.ZodBoolean:
115539
+ return parseBooleanDef2();
115540
+ case ZodFirstPartyTypeKind.ZodDate:
115541
+ return parseDateDef2(def, refs);
115542
+ case ZodFirstPartyTypeKind.ZodUndefined:
115543
+ return parseUndefinedDef2(refs);
115544
+ case ZodFirstPartyTypeKind.ZodNull:
115545
+ return parseNullDef2(refs);
115546
+ case ZodFirstPartyTypeKind.ZodArray:
115547
+ return parseArrayDef2(def, refs);
115548
+ case ZodFirstPartyTypeKind.ZodUnion:
115549
+ case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
115550
+ return parseUnionDef2(def, refs);
115551
+ case ZodFirstPartyTypeKind.ZodIntersection:
115552
+ return parseIntersectionDef2(def, refs);
115553
+ case ZodFirstPartyTypeKind.ZodTuple:
115554
+ return parseTupleDef2(def, refs);
115555
+ case ZodFirstPartyTypeKind.ZodRecord:
115556
+ return parseRecordDef2(def, refs);
115557
+ case ZodFirstPartyTypeKind.ZodLiteral:
115558
+ return parseLiteralDef2(def, refs);
115559
+ case ZodFirstPartyTypeKind.ZodEnum:
115560
+ return parseEnumDef2(def);
115561
+ case ZodFirstPartyTypeKind.ZodNativeEnum:
115562
+ return parseNativeEnumDef2(def);
115563
+ case ZodFirstPartyTypeKind.ZodNullable:
115564
+ return parseNullableDef2(def, refs);
115565
+ case ZodFirstPartyTypeKind.ZodOptional:
115566
+ return parseOptionalDef2(def, refs);
115567
+ case ZodFirstPartyTypeKind.ZodMap:
115568
+ return parseMapDef2(def, refs);
115569
+ case ZodFirstPartyTypeKind.ZodSet:
115570
+ return parseSetDef2(def, refs);
115571
+ case ZodFirstPartyTypeKind.ZodLazy:
115572
+ return () => def.getter()._def;
115573
+ case ZodFirstPartyTypeKind.ZodPromise:
115574
+ return parsePromiseDef2(def, refs);
115575
+ case ZodFirstPartyTypeKind.ZodNaN:
115576
+ case ZodFirstPartyTypeKind.ZodNever:
115577
+ return parseNeverDef2(refs);
115578
+ case ZodFirstPartyTypeKind.ZodEffects:
115579
+ return parseEffectsDef2(def, refs);
115580
+ case ZodFirstPartyTypeKind.ZodAny:
115581
+ return parseAnyDef2(refs);
115582
+ case ZodFirstPartyTypeKind.ZodUnknown:
115583
+ return parseUnknownDef2(refs);
115584
+ case ZodFirstPartyTypeKind.ZodDefault:
115585
+ return parseDefaultDef2(def, refs);
115586
+ case ZodFirstPartyTypeKind.ZodBranded:
115587
+ return parseBrandedDef2(def, refs);
115588
+ case ZodFirstPartyTypeKind.ZodReadonly:
115589
+ return parseReadonlyDef2(def, refs);
115590
+ case ZodFirstPartyTypeKind.ZodCatch:
115591
+ return parseCatchDef2(def, refs);
115592
+ case ZodFirstPartyTypeKind.ZodPipeline:
115593
+ return parsePipelineDef2(def, refs);
115594
+ case ZodFirstPartyTypeKind.ZodFunction:
115595
+ case ZodFirstPartyTypeKind.ZodVoid:
115596
+ case ZodFirstPartyTypeKind.ZodSymbol:
115597
+ return;
115598
+ default:
115599
+ return ((_) => {
115600
+ return;
115601
+ })(typeName);
115602
+ }
115603
+ };
115604
+
115605
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parseDef.js
115606
+ function parseDef2(def, refs, forceResolution = false) {
115607
+ const seenItem = refs.seen.get(def);
115608
+ if (refs.override) {
115609
+ const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
115610
+ if (overrideResult !== ignoreOverride2) {
115611
+ return overrideResult;
115612
+ }
115613
+ }
115614
+ if (seenItem && !forceResolution) {
115615
+ const seenSchema = get$ref2(seenItem, refs);
115616
+ if (seenSchema !== undefined) {
115617
+ return seenSchema;
115618
+ }
115619
+ }
115620
+ const newItem = { def, path: refs.currentPath, jsonSchema: undefined };
115621
+ refs.seen.set(def, newItem);
115622
+ const jsonSchemaOrGetter = selectParser2(def, def.typeName, refs);
115623
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef2(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
115624
+ if (jsonSchema2) {
115625
+ addMeta2(def, refs, jsonSchema2);
115626
+ }
115627
+ if (refs.postProcess) {
115628
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
115629
+ newItem.jsonSchema = jsonSchema2;
115630
+ return postProcessResult;
115631
+ }
115632
+ newItem.jsonSchema = jsonSchema2;
115633
+ return jsonSchema2;
115634
+ }
115635
+ var get$ref2 = (item, refs) => {
115636
+ switch (refs.$refStrategy) {
115637
+ case "root":
115638
+ return { $ref: item.path.join("/") };
115639
+ case "relative":
115640
+ return { $ref: getRelativePath2(refs.currentPath, item.path) };
115641
+ case "none":
115642
+ case "seen": {
115643
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
115644
+ console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
115645
+ return parseAnyDef2(refs);
115646
+ }
115647
+ return refs.$refStrategy === "seen" ? parseAnyDef2(refs) : undefined;
115648
+ }
115649
+ }
115650
+ };
115651
+ var addMeta2 = (def, refs, jsonSchema2) => {
115652
+ if (def.description) {
115653
+ jsonSchema2.description = def.description;
115654
+ if (refs.markdownDescription) {
115655
+ jsonSchema2.markdownDescription = def.description;
115656
+ }
115657
+ }
115658
+ return jsonSchema2;
115659
+ };
115660
+ // ../../node_modules/.bun/zod-to-json-schema@3.25.1+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
115661
+ var zodToJsonSchema = (schema, options) => {
115662
+ const refs = getRefs2(options);
115663
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name17, schema2]) => ({
115664
+ ...acc,
115665
+ [name17]: parseDef2(schema2._def, {
115666
+ ...refs,
115667
+ currentPath: [...refs.basePath, refs.definitionPath, name17]
115668
+ }, true) ?? parseAnyDef2(refs)
115669
+ }), {}) : undefined;
115670
+ const name15 = typeof options === "string" ? options : options?.nameStrategy === "title" ? undefined : options?.name;
115671
+ const main = parseDef2(schema._def, name15 === undefined ? refs : {
115672
+ ...refs,
115673
+ currentPath: [...refs.basePath, refs.definitionPath, name15]
115674
+ }, false) ?? parseAnyDef2(refs);
115675
+ const title = typeof options === "object" && options.name !== undefined && options.nameStrategy === "title" ? options.name : undefined;
115676
+ if (title !== undefined) {
115677
+ main.title = title;
115678
+ }
115679
+ if (refs.flags.hasReferencedOpenAiAnyType) {
115680
+ if (!definitions) {
115681
+ definitions = {};
115682
+ }
115683
+ if (!definitions[refs.openAiAnyTypeName]) {
115684
+ definitions[refs.openAiAnyTypeName] = {
115685
+ type: ["string", "number", "integer", "boolean", "array", "null"],
115686
+ items: {
115687
+ $ref: refs.$refStrategy === "relative" ? "1" : [
115688
+ ...refs.basePath,
115689
+ refs.definitionPath,
115690
+ refs.openAiAnyTypeName
115691
+ ].join("/")
115692
+ }
115693
+ };
115694
+ }
115695
+ }
115696
+ const combined = name15 === undefined ? definitions ? {
115697
+ ...main,
115698
+ [refs.definitionPath]: definitions
115699
+ } : main : {
115700
+ $ref: [
115701
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
115702
+ refs.definitionPath,
115703
+ name15
115704
+ ].join("/"),
115705
+ [refs.definitionPath]: {
115706
+ ...definitions,
115707
+ [name15]: main
115708
+ }
115709
+ };
115710
+ if (refs.target === "jsonSchema7") {
115711
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
115712
+ } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
115713
+ combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
115714
+ }
115715
+ if (refs.target === "openAi" && (("anyOf" in combined) || ("oneOf" in combined) || ("allOf" in combined) || ("type" in combined) && Array.isArray(combined.type))) {
115716
+ console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
115717
+ }
115718
+ return combined;
115719
+ };
115720
+ // src/tools/defineServerTool.ts
115721
+ function defineServerTool(description, schemaOrExecute, executeOrOptions, options) {
115722
+ const isNoParamForm = typeof schemaOrExecute === "function";
115723
+ let parameters;
115724
+ let execute;
115725
+ let actualOptions;
115726
+ if (isNoParamForm) {
115727
+ parameters = { type: "object", properties: {} };
115728
+ execute = schemaOrExecute;
115729
+ actualOptions = executeOrOptions || {};
115730
+ } else {
115731
+ const schema = schemaOrExecute;
115732
+ const jsonSchema2 = zodToJsonSchema(schema, { target: "openApi3" });
115733
+ parameters = {
115734
+ type: "object",
115735
+ properties: jsonSchema2.properties || {}
115736
+ };
115737
+ if (jsonSchema2.required && jsonSchema2.required.length > 0) {
115738
+ parameters.required = jsonSchema2.required;
115739
+ }
115740
+ execute = executeOrOptions;
115741
+ actualOptions = options || {};
115742
+ }
115743
+ const config2 = {
115744
+ description,
115745
+ parameters,
115746
+ execute
115747
+ };
115748
+ if (actualOptions.annotations) {
115749
+ config2.annotations = actualOptions.annotations;
115750
+ }
115751
+ return config2;
115752
+ }
114058
115753
  export {
115754
+ startRunSpan,
114059
115755
  or,
114060
115756
  not,
114061
115757
  logger2 as logger,
115758
+ isUseAIInternalResponse,
115759
+ isServerTool,
114062
115760
  isRemoteTool,
115761
+ isMcpConfirmationResponse,
114063
115762
  getToolAnnotations,
115763
+ flushTelemetry,
115764
+ defineServerTool,
114064
115765
  createGlobFilter,
114065
115766
  createClientToolExecutor,
114066
115767
  and,