@mcpjam/inspector 0.9.21 → 0.9.25

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.
@@ -1,7 +1,7 @@
1
1
  // index.ts
2
2
  import { serve } from "@hono/node-server";
3
3
  import fixPath from "fix-path";
4
- import { Hono as Hono10 } from "hono";
4
+ import { Hono as Hono11 } from "hono";
5
5
  import { cors } from "hono/cors";
6
6
  import { logger } from "hono/logger";
7
7
  import { serveStatic } from "@hono/node-server/serve-static";
@@ -9,7 +9,7 @@ import { readFileSync } from "fs";
9
9
  import { join } from "path";
10
10
 
11
11
  // routes/mcp/index.ts
12
- import { Hono as Hono9 } from "hono";
12
+ import { Hono as Hono10 } from "hono";
13
13
 
14
14
  // routes/mcp/connect.ts
15
15
  import { Hono } from "hono";
@@ -186,242 +186,204 @@ var servers_default = servers;
186
186
  // routes/mcp/tools.ts
187
187
  import { Hono as Hono3 } from "hono";
188
188
  import { zodToJsonSchema } from "zod-to-json-schema";
189
- import { TextEncoder as TextEncoder2 } from "util";
190
189
  var tools = new Hono3();
191
- var pendingElicitations = /* @__PURE__ */ new Map();
192
- tools.post("/", async (c) => {
193
- let action;
194
- let toolName;
190
+ var activeExecution = null;
191
+ function nowIso() {
192
+ return (/* @__PURE__ */ new Date()).toISOString();
193
+ }
194
+ function takeNextElicitation(state) {
195
+ if (state.queue.length > 0) {
196
+ return Promise.resolve(state.queue.shift());
197
+ }
198
+ return new Promise((resolve) => {
199
+ state.waiters.push(resolve);
200
+ });
201
+ }
202
+ tools.post("/list", async (c) => {
195
203
  try {
196
- const requestData = await c.req.json();
197
- action = requestData.action;
198
- toolName = requestData.toolName;
199
- const { serverConfig, parameters, requestId, response } = requestData;
200
- if (!action || !["list", "execute", "respond"].includes(action)) {
201
- return c.json(
202
- {
203
- success: false,
204
- error: "Action must be 'list', 'execute', or 'respond'"
205
- },
206
- 400
207
- );
204
+ const { serverId } = await c.req.json();
205
+ if (!serverId) {
206
+ return c.json({ error: "serverId is required" }, 400);
208
207
  }
209
- if (action === "respond") {
210
- if (!requestId) {
211
- return c.json(
212
- {
213
- success: false,
214
- error: "requestId is required for respond action"
215
- },
216
- 400
217
- );
218
- }
219
- const mcpJamClientManager2 = c.mcpJamClientManager;
220
- const success = mcpJamClientManager2.respondToElicitation(
221
- requestId,
222
- response
223
- );
224
- if (!success) {
225
- const pending = pendingElicitations.get(requestId);
226
- if (pending) {
227
- pending.resolve(response);
228
- pendingElicitations.delete(requestId);
229
- return c.json({ success: true });
230
- }
231
- return c.json(
232
- {
233
- success: false,
234
- error: "No pending elicitation found for this requestId"
235
- },
236
- 404
237
- );
208
+ const mcp2 = c.mcpJamClientManager;
209
+ const status = mcp2.getConnectionStatus(serverId);
210
+ if (status !== "connected") {
211
+ return c.json({ error: `Server '${serverId}' is not connected` }, 400);
212
+ }
213
+ const flattenedTools = await mcp2.getToolsetsForServer(serverId);
214
+ const toolsWithJsonSchema = {};
215
+ for (const [name17, tool] of Object.entries(flattenedTools)) {
216
+ let inputSchema = tool.inputSchema;
217
+ try {
218
+ inputSchema = zodToJsonSchema(inputSchema);
219
+ } catch {
238
220
  }
239
- return c.json({ success: true });
221
+ toolsWithJsonSchema[name17] = {
222
+ name: name17,
223
+ description: tool.description,
224
+ inputSchema,
225
+ outputSchema: tool.outputSchema
226
+ };
240
227
  }
241
- const encoder = new TextEncoder2();
242
- const readableStream = new ReadableStream({
243
- async start(controller) {
244
- try {
245
- if (!serverConfig) {
246
- controller.enqueue(
247
- encoder.encode(
248
- `data: ${JSON.stringify({ type: "tool_error", error: "serverConfig is required" })}
249
-
250
- `
251
- )
252
- );
253
- controller.enqueue(encoder.encode(`data: [DONE]
254
-
255
- `));
256
- controller.close();
257
- return;
258
- }
259
- const mcpJamClientManager2 = c.mcpJamClientManager;
260
- const serverId = serverConfig.name || serverConfig.id || "server";
261
- await mcpJamClientManager2.connectToServer(serverId, serverConfig);
262
- mcpJamClientManager2.setElicitationCallback(async (request) => {
263
- const { requestId: requestId2, message, schema } = request;
264
- controller.enqueue(
265
- encoder.encode(
266
- `data: ${JSON.stringify({
267
- type: "elicitation_request",
268
- requestId: requestId2,
269
- message,
270
- schema,
271
- toolName: toolName || "unknown",
272
- timestamp: /* @__PURE__ */ new Date()
273
- })}
274
-
275
- `
276
- )
277
- );
278
- return new Promise((resolve, reject) => {
279
- pendingElicitations.set(requestId2, {
280
- resolve: (response2) => {
281
- resolve(response2);
282
- pendingElicitations.delete(requestId2);
283
- },
284
- reject: (error) => {
285
- reject(error);
286
- pendingElicitations.delete(requestId2);
287
- }
288
- });
289
- setTimeout(() => {
290
- if (pendingElicitations.has(requestId2)) {
291
- pendingElicitations.delete(requestId2);
292
- reject(new Error("Elicitation timeout"));
293
- }
294
- }, 3e5);
295
- });
296
- });
297
- if (action === "list") {
298
- try {
299
- const flattenedTools = await mcpJamClientManager2.getToolsetsForServer(serverId);
300
- const toolsWithJsonSchema = {};
301
- for (const [name, tool] of Object.entries(flattenedTools)) {
302
- let inputSchema = tool.inputSchema;
303
- try {
304
- inputSchema = zodToJsonSchema(inputSchema);
305
- } catch {
306
- }
307
- toolsWithJsonSchema[name] = {
308
- name,
309
- description: tool.description,
310
- inputSchema,
311
- outputSchema: tool.outputSchema
312
- };
313
- }
314
- controller.enqueue(
315
- encoder.encode(
316
- `data: ${JSON.stringify({ type: "tools_list", tools: toolsWithJsonSchema })}
317
-
318
- `
319
- )
320
- );
321
- controller.enqueue(encoder.encode(`data: [DONE]
322
-
323
- `));
324
- controller.close();
325
- return;
326
- } catch (err) {
327
- controller.enqueue(
328
- encoder.encode(
329
- `data: ${JSON.stringify({ type: "tool_error", error: err instanceof Error ? err.message : String(err) })}
330
-
331
- `
332
- )
333
- );
334
- controller.enqueue(encoder.encode(`data: [DONE]
335
-
336
- `));
337
- controller.close();
338
- return;
339
- }
340
- }
341
- if (action === "execute") {
342
- if (!toolName) {
343
- controller.enqueue(
344
- encoder.encode(
345
- `data: ${JSON.stringify({ type: "tool_error", error: "Tool name is required for execution" })}
346
-
347
- `
348
- )
349
- );
350
- controller.enqueue(encoder.encode(`data: [DONE]
351
-
352
- `));
353
- controller.close();
354
- return;
355
- }
356
- controller.enqueue(
357
- encoder.encode(
358
- `data: ${JSON.stringify({ type: "tool_executing", toolName, parameters: parameters || {}, message: "Executing tool..." })}
359
-
360
- `
361
- )
362
- );
363
- const exec = await mcpJamClientManager2.executeToolDirect(
364
- toolName,
365
- parameters || {}
366
- );
367
- controller.enqueue(
368
- encoder.encode(
369
- `data: ${JSON.stringify({ type: "tool_result", toolName, result: exec.result })}
370
-
371
- `
372
- )
373
- );
374
- controller.enqueue(
375
- encoder.encode(
376
- `data: ${JSON.stringify({ type: "elicitation_complete", toolName })}
377
-
378
- `
379
- )
380
- );
381
- controller.enqueue(encoder.encode(`data: [DONE]
382
-
383
- `));
384
- controller.close();
385
- return;
386
- }
387
- } catch (err) {
388
- controller.enqueue(
389
- encoder.encode(
390
- `data: ${JSON.stringify({ type: "tool_error", error: err instanceof Error ? err.message : String(err) })}
391
-
392
- `
393
- )
394
- );
395
- controller.enqueue(encoder.encode(`data: [DONE]
396
-
397
- `));
398
- controller.close();
399
- } finally {
400
- const mcpJamClientManager2 = c.mcpJamClientManager;
401
- if (mcpJamClientManager2) {
402
- mcpJamClientManager2.clearElicitationCallback();
403
- }
404
- }
228
+ return c.json({ tools: toolsWithJsonSchema });
229
+ } catch (err) {
230
+ const msg = err instanceof Error ? err.message : String(err);
231
+ return c.json({ error: msg }, 500);
232
+ }
233
+ });
234
+ tools.post("/execute", async (c) => {
235
+ try {
236
+ const { serverId, toolName, parameters } = await c.req.json();
237
+ if (!serverId) return c.json({ error: "serverId is required" }, 400);
238
+ if (!toolName) return c.json({ error: "toolName is required" }, 400);
239
+ if (activeExecution) {
240
+ return c.json({ error: "Another execution is already in progress" }, 409);
241
+ }
242
+ const mcp2 = c.mcpJamClientManager;
243
+ const status = mcp2.getConnectionStatus(serverId);
244
+ if (status !== "connected") {
245
+ return c.json({ error: `Server '${serverId}' is not connected` }, 400);
246
+ }
247
+ const executionId = `exec_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
248
+ const state = {
249
+ id: executionId,
250
+ serverId,
251
+ toolName,
252
+ execPromise: Promise.resolve().then(
253
+ () => mcp2.executeToolDirect(toolName, parameters || {})
254
+ ),
255
+ completed: false,
256
+ queue: [],
257
+ waiters: []
258
+ };
259
+ activeExecution = state;
260
+ mcp2.setElicitationCallback(async ({ requestId, message, schema }) => {
261
+ if (!activeExecution) {
262
+ throw new Error("No active execution");
405
263
  }
406
- });
407
- return new Response(readableStream, {
408
- headers: {
409
- "Content-Type": "text/event-stream",
410
- "Cache-Control": "no-cache",
411
- Connection: "keep-alive"
264
+ const event = {
265
+ requestId,
266
+ message,
267
+ schema,
268
+ toolName,
269
+ timestamp: nowIso()
270
+ };
271
+ if (activeExecution.waiters.length > 0) {
272
+ const waiter = activeExecution.waiters.shift();
273
+ waiter(event);
274
+ } else {
275
+ activeExecution.queue.push(event);
412
276
  }
277
+ return new Promise((resolve, reject) => {
278
+ const timeout = setTimeout(
279
+ () => reject(new Error("Elicitation timeout")),
280
+ 3e5
281
+ );
282
+ mcp2.getPendingElicitations().set(requestId, {
283
+ resolve: (response) => {
284
+ clearTimeout(timeout);
285
+ resolve(response);
286
+ },
287
+ reject: (error) => {
288
+ clearTimeout(timeout);
289
+ reject(error);
290
+ }
291
+ });
292
+ });
413
293
  });
414
- } catch (error) {
415
- const errorMsg = error instanceof Error ? error.message : "Unknown error";
294
+ const race = await Promise.race([
295
+ state.execPromise.then((res) => ({ kind: "done", res })),
296
+ takeNextElicitation(state).then(
297
+ (ev) => ({ kind: "elicit", ev })
298
+ )
299
+ ]);
300
+ if (race.kind === "done") {
301
+ state.completed = true;
302
+ state.result = race.res;
303
+ activeExecution = null;
304
+ mcp2.clearElicitationCallback();
305
+ return c.json(
306
+ { status: "completed", toolName, result: race.res.result },
307
+ 200
308
+ );
309
+ }
416
310
  return c.json(
417
311
  {
418
- success: false,
419
- error: errorMsg
312
+ status: "elicitation_required",
313
+ executionId,
314
+ requestId: race.ev.requestId,
315
+ toolName,
316
+ message: race.ev.message,
317
+ schema: race.ev.schema,
318
+ timestamp: race.ev.timestamp
420
319
  },
421
- 500
320
+ 202
422
321
  );
322
+ } catch (err) {
323
+ const msg = err instanceof Error ? err.message : String(err);
324
+ return c.json({ error: msg }, 500);
325
+ }
326
+ });
327
+ tools.post("/respond", async (c) => {
328
+ try {
329
+ const { requestId, response } = await c.req.json();
330
+ if (!requestId) return c.json({ error: "requestId is required" }, 400);
331
+ if (!activeExecution) return c.json({ error: "No active execution" }, 404);
332
+ const mcp2 = c.mcpJamClientManager;
333
+ const ok = mcp2.respondToElicitation(requestId, response);
334
+ if (!ok)
335
+ return c.json({ error: "No pending elicitation for requestId" }, 404);
336
+ const state = activeExecution;
337
+ try {
338
+ const race = await Promise.race([
339
+ state.execPromise.then((res) => ({ kind: "done", res })),
340
+ takeNextElicitation(state).then(
341
+ (ev) => ({ kind: "elicit", ev })
342
+ )
343
+ ]);
344
+ if (race.kind === "done") {
345
+ state.completed = true;
346
+ state.result = race.res;
347
+ activeExecution = null;
348
+ mcp2.clearElicitationCallback();
349
+ return c.json(
350
+ {
351
+ status: "completed",
352
+ toolName: state.toolName,
353
+ result: race.res.result
354
+ },
355
+ 200
356
+ );
357
+ }
358
+ return c.json(
359
+ {
360
+ status: "elicitation_required",
361
+ executionId: state.id,
362
+ requestId: race.ev.requestId,
363
+ toolName: state.toolName,
364
+ message: race.ev.message,
365
+ schema: race.ev.schema,
366
+ timestamp: race.ev.timestamp
367
+ },
368
+ 202
369
+ );
370
+ } catch (e) {
371
+ const msg = e instanceof Error ? e.message : String(e);
372
+ return c.json({ error: msg }, 500);
373
+ }
374
+ } catch (err) {
375
+ const msg = err instanceof Error ? err.message : String(err);
376
+ return c.json({ error: msg }, 500);
423
377
  }
424
378
  });
379
+ tools.post("/", async () => {
380
+ return new Response(
381
+ JSON.stringify({
382
+ error: "Endpoint migrated. Use /list, /execute, or /respond."
383
+ }),
384
+ { status: 410, headers: { "Content-Type": "application/json" } }
385
+ );
386
+ });
425
387
  var tools_default = tools;
426
388
 
427
389
  // routes/mcp/resources.ts
@@ -503,11 +465,11 @@ prompts.post("/list", async (c) => {
503
465
  });
504
466
  prompts.post("/get", async (c) => {
505
467
  try {
506
- const { serverId, name, args } = await c.req.json();
468
+ const { serverId, name: name17, args } = await c.req.json();
507
469
  if (!serverId) {
508
470
  return c.json({ success: false, error: "serverId is required" }, 400);
509
471
  }
510
- if (!name) {
472
+ if (!name17) {
511
473
  return c.json(
512
474
  {
513
475
  success: false,
@@ -518,7 +480,7 @@ prompts.post("/get", async (c) => {
518
480
  }
519
481
  const mcpJamClientManager2 = c.mcpJamClientManager;
520
482
  const content = await mcpJamClientManager2.getPrompt(
521
- name,
483
+ name17,
522
484
  serverId,
523
485
  args || {}
524
486
  );
@@ -539,11 +501,7 @@ var prompts_default = prompts;
539
501
  // routes/mcp/chat.ts
540
502
  import { Hono as Hono6 } from "hono";
541
503
  import { Agent } from "@mastra/core/agent";
542
- import { createAnthropic } from "@ai-sdk/anthropic";
543
- import { createOpenAI } from "@ai-sdk/openai";
544
- import { createGoogleGenerativeAI } from "@ai-sdk/google";
545
- import { createOllama } from "ollama-ai-provider";
546
- import { TextEncoder as TextEncoder3 } from "util";
504
+ import { TextEncoder as TextEncoder2 } from "util";
547
505
 
548
506
  // ../client/src/lib/chat-utils.ts
549
507
  import { clsx } from "clsx";
@@ -562,19 +520,2592 @@ function getDefaultTemperatureByProvider(provider) {
562
520
  }
563
521
  }
564
522
 
565
- // routes/mcp/chat.ts
566
- var DEBUG_ENABLED = process.env.MCP_DEBUG !== "false";
567
- var ELICITATION_TIMEOUT = 3e5;
568
- var MAX_AGENT_STEPS = 10;
569
- var dbg = (...args) => {
570
- if (DEBUG_ENABLED) console.log("[mcp/chat]", ...args);
571
- };
572
- try {
573
- process.setMaxListeners?.(50);
574
- } catch {
575
- }
576
- var pendingElicitations2 = /* @__PURE__ */ new Map();
577
- var chat = new Hono6();
523
+ // node_modules/ai-v5/node_modules/@ai-sdk/provider/dist/index.mjs
524
+ var marker = "vercel.ai.error";
525
+ var symbol = Symbol.for(marker);
526
+ var _a;
527
+ var _AISDKError = class _AISDKError2 extends Error {
528
+ /**
529
+ * Creates an AI SDK Error.
530
+ *
531
+ * @param {Object} params - The parameters for creating the error.
532
+ * @param {string} params.name - The name of the error.
533
+ * @param {string} params.message - The error message.
534
+ * @param {unknown} [params.cause] - The underlying cause of the error.
535
+ */
536
+ constructor({
537
+ name: name143,
538
+ message,
539
+ cause
540
+ }) {
541
+ super(message);
542
+ this[_a] = true;
543
+ this.name = name143;
544
+ this.cause = cause;
545
+ }
546
+ /**
547
+ * Checks if the given error is an AI SDK Error.
548
+ * @param {unknown} error - The error to check.
549
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
550
+ */
551
+ static isInstance(error) {
552
+ return _AISDKError2.hasMarker(error, marker);
553
+ }
554
+ static hasMarker(error, marker153) {
555
+ const markerSymbol = Symbol.for(marker153);
556
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
557
+ }
558
+ };
559
+ _a = symbol;
560
+ var AISDKError = _AISDKError;
561
+ var name = "AI_APICallError";
562
+ var marker2 = `vercel.ai.error.${name}`;
563
+ var symbol2 = Symbol.for(marker2);
564
+ var _a2;
565
+ _a2 = symbol2;
566
+ var name2 = "AI_EmptyResponseBodyError";
567
+ var marker3 = `vercel.ai.error.${name2}`;
568
+ var symbol3 = Symbol.for(marker3);
569
+ var _a3;
570
+ _a3 = symbol3;
571
+ function getErrorMessage(error) {
572
+ if (error == null) {
573
+ return "unknown error";
574
+ }
575
+ if (typeof error === "string") {
576
+ return error;
577
+ }
578
+ if (error instanceof Error) {
579
+ return error.message;
580
+ }
581
+ return JSON.stringify(error);
582
+ }
583
+ var name3 = "AI_InvalidArgumentError";
584
+ var marker4 = `vercel.ai.error.${name3}`;
585
+ var symbol4 = Symbol.for(marker4);
586
+ var _a4;
587
+ var InvalidArgumentError = class extends AISDKError {
588
+ constructor({
589
+ message,
590
+ cause,
591
+ argument
592
+ }) {
593
+ super({ name: name3, message, cause });
594
+ this[_a4] = true;
595
+ this.argument = argument;
596
+ }
597
+ static isInstance(error) {
598
+ return AISDKError.hasMarker(error, marker4);
599
+ }
600
+ };
601
+ _a4 = symbol4;
602
+ var name4 = "AI_InvalidPromptError";
603
+ var marker5 = `vercel.ai.error.${name4}`;
604
+ var symbol5 = Symbol.for(marker5);
605
+ var _a5;
606
+ _a5 = symbol5;
607
+ var name5 = "AI_InvalidResponseDataError";
608
+ var marker6 = `vercel.ai.error.${name5}`;
609
+ var symbol6 = Symbol.for(marker6);
610
+ var _a6;
611
+ _a6 = symbol6;
612
+ var name6 = "AI_JSONParseError";
613
+ var marker7 = `vercel.ai.error.${name6}`;
614
+ var symbol7 = Symbol.for(marker7);
615
+ var _a7;
616
+ var JSONParseError = class extends AISDKError {
617
+ constructor({ text: text2, cause }) {
618
+ super({
619
+ name: name6,
620
+ message: `JSON parsing failed: Text: ${text2}.
621
+ Error message: ${getErrorMessage(cause)}`,
622
+ cause
623
+ });
624
+ this[_a7] = true;
625
+ this.text = text2;
626
+ }
627
+ static isInstance(error) {
628
+ return AISDKError.hasMarker(error, marker7);
629
+ }
630
+ };
631
+ _a7 = symbol7;
632
+ var name7 = "AI_LoadAPIKeyError";
633
+ var marker8 = `vercel.ai.error.${name7}`;
634
+ var symbol8 = Symbol.for(marker8);
635
+ var _a8;
636
+ _a8 = symbol8;
637
+ var name8 = "AI_LoadSettingError";
638
+ var marker9 = `vercel.ai.error.${name8}`;
639
+ var symbol9 = Symbol.for(marker9);
640
+ var _a9;
641
+ _a9 = symbol9;
642
+ var name9 = "AI_NoContentGeneratedError";
643
+ var marker10 = `vercel.ai.error.${name9}`;
644
+ var symbol10 = Symbol.for(marker10);
645
+ var _a10;
646
+ _a10 = symbol10;
647
+ var name10 = "AI_NoSuchModelError";
648
+ var marker11 = `vercel.ai.error.${name10}`;
649
+ var symbol11 = Symbol.for(marker11);
650
+ var _a11;
651
+ _a11 = symbol11;
652
+ var name11 = "AI_TooManyEmbeddingValuesForCallError";
653
+ var marker12 = `vercel.ai.error.${name11}`;
654
+ var symbol12 = Symbol.for(marker12);
655
+ var _a12;
656
+ _a12 = symbol12;
657
+ var name12 = "AI_TypeValidationError";
658
+ var marker13 = `vercel.ai.error.${name12}`;
659
+ var symbol13 = Symbol.for(marker13);
660
+ var _a13;
661
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
662
+ constructor({ value, cause }) {
663
+ super({
664
+ name: name12,
665
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
666
+ Error message: ${getErrorMessage(cause)}`,
667
+ cause
668
+ });
669
+ this[_a13] = true;
670
+ this.value = value;
671
+ }
672
+ static isInstance(error) {
673
+ return AISDKError.hasMarker(error, marker13);
674
+ }
675
+ /**
676
+ * Wraps an error into a TypeValidationError.
677
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
678
+ * Otherwise, it creates a new TypeValidationError.
679
+ *
680
+ * @param {Object} params - The parameters for wrapping the error.
681
+ * @param {unknown} params.value - The value that failed validation.
682
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
683
+ * @returns {TypeValidationError} A TypeValidationError instance.
684
+ */
685
+ static wrap({
686
+ value,
687
+ cause
688
+ }) {
689
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
690
+ }
691
+ };
692
+ _a13 = symbol13;
693
+ var TypeValidationError = _TypeValidationError;
694
+ var name13 = "AI_UnsupportedFunctionalityError";
695
+ var marker14 = `vercel.ai.error.${name13}`;
696
+ var symbol14 = Symbol.for(marker14);
697
+ var _a14;
698
+ _a14 = symbol14;
699
+
700
+ // node_modules/ai-v5/node_modules/@ai-sdk/provider-utils/dist/index.mjs
701
+ import * as z4 from "zod/v4";
702
+ import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
703
+ import { ZodFirstPartyTypeKind } from "zod/v3";
704
+ import {
705
+ ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2
706
+ } from "zod/v3";
707
+ var createIdGenerator = ({
708
+ prefix,
709
+ size = 16,
710
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
711
+ separator = "-"
712
+ } = {}) => {
713
+ const generator = () => {
714
+ const alphabetLength = alphabet.length;
715
+ const chars = new Array(size);
716
+ for (let i = 0; i < size; i++) {
717
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
718
+ }
719
+ return chars.join("");
720
+ };
721
+ if (prefix == null) {
722
+ return generator;
723
+ }
724
+ if (alphabet.includes(separator)) {
725
+ throw new InvalidArgumentError({
726
+ argument: "separator",
727
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
728
+ });
729
+ }
730
+ return () => `${prefix}${separator}${generator()}`;
731
+ };
732
+ var generateId = createIdGenerator();
733
+ var suspectProtoRx = /"__proto__"\s*:/;
734
+ var suspectConstructorRx = /"constructor"\s*:/;
735
+ function _parse(text2) {
736
+ const obj = JSON.parse(text2);
737
+ if (obj === null || typeof obj !== "object") {
738
+ return obj;
739
+ }
740
+ if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) {
741
+ return obj;
742
+ }
743
+ return filter(obj);
744
+ }
745
+ function filter(obj) {
746
+ let next = [obj];
747
+ while (next.length) {
748
+ const nodes = next;
749
+ next = [];
750
+ for (const node of nodes) {
751
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
752
+ throw new SyntaxError("Object contains forbidden prototype property");
753
+ }
754
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
755
+ throw new SyntaxError("Object contains forbidden prototype property");
756
+ }
757
+ for (const key in node) {
758
+ const value = node[key];
759
+ if (value && typeof value === "object") {
760
+ next.push(value);
761
+ }
762
+ }
763
+ }
764
+ }
765
+ return obj;
766
+ }
767
+ function secureJsonParse(text2) {
768
+ const { stackTraceLimit } = Error;
769
+ Error.stackTraceLimit = 0;
770
+ try {
771
+ return _parse(text2);
772
+ } finally {
773
+ Error.stackTraceLimit = stackTraceLimit;
774
+ }
775
+ }
776
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
777
+ function validator(validate) {
778
+ return { [validatorSymbol]: true, validate };
779
+ }
780
+ function isValidator(value) {
781
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
782
+ }
783
+ function asValidator(value) {
784
+ return isValidator(value) ? value : standardSchemaValidator(value);
785
+ }
786
+ function standardSchemaValidator(standardSchema) {
787
+ return validator(async (value) => {
788
+ const result = await standardSchema["~standard"].validate(value);
789
+ return result.issues == null ? { success: true, value: result.value } : {
790
+ success: false,
791
+ error: new TypeValidationError({
792
+ value,
793
+ cause: result.issues
794
+ })
795
+ };
796
+ });
797
+ }
798
+ async function safeValidateTypes({
799
+ value,
800
+ schema
801
+ }) {
802
+ const validator2 = asValidator(schema);
803
+ try {
804
+ if (validator2.validate == null) {
805
+ return { success: true, value, rawValue: value };
806
+ }
807
+ const result = await validator2.validate(value);
808
+ if (result.success) {
809
+ return { success: true, value: result.value, rawValue: value };
810
+ }
811
+ return {
812
+ success: false,
813
+ error: TypeValidationError.wrap({ value, cause: result.error }),
814
+ rawValue: value
815
+ };
816
+ } catch (error) {
817
+ return {
818
+ success: false,
819
+ error: TypeValidationError.wrap({ value, cause: error }),
820
+ rawValue: value
821
+ };
822
+ }
823
+ }
824
+ async function safeParseJSON({
825
+ text: text2,
826
+ schema
827
+ }) {
828
+ try {
829
+ const value = secureJsonParse(text2);
830
+ if (schema == null) {
831
+ return { success: true, value, rawValue: value };
832
+ }
833
+ return await safeValidateTypes({ value, schema });
834
+ } catch (error) {
835
+ return {
836
+ success: false,
837
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text: text2, cause: error }),
838
+ rawValue: void 0
839
+ };
840
+ }
841
+ }
842
+ var getRelativePath = (pathA, pathB) => {
843
+ let i = 0;
844
+ for (; i < pathA.length && i < pathB.length; i++) {
845
+ if (pathA[i] !== pathB[i])
846
+ break;
847
+ }
848
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
849
+ };
850
+ var ignoreOverride = Symbol(
851
+ "Let zodToJsonSchema decide on which parser to use"
852
+ );
853
+ var defaultOptions = {
854
+ name: void 0,
855
+ $refStrategy: "root",
856
+ basePath: ["#"],
857
+ effectStrategy: "input",
858
+ pipeStrategy: "all",
859
+ dateStrategy: "format:date-time",
860
+ mapStrategy: "entries",
861
+ removeAdditionalStrategy: "passthrough",
862
+ allowedAdditionalProperties: true,
863
+ rejectedAdditionalProperties: false,
864
+ definitionPath: "definitions",
865
+ strictUnions: false,
866
+ definitions: {},
867
+ errorMessages: false,
868
+ patternStrategy: "escape",
869
+ applyRegexFlags: false,
870
+ emailStrategy: "format:email",
871
+ base64Strategy: "contentEncoding:base64",
872
+ nameStrategy: "ref"
873
+ };
874
+ var getDefaultOptions = (options) => typeof options === "string" ? {
875
+ ...defaultOptions,
876
+ name: options
877
+ } : {
878
+ ...defaultOptions,
879
+ ...options
880
+ };
881
+ function parseAnyDef() {
882
+ return {};
883
+ }
884
+ function parseArrayDef(def, refs) {
885
+ var _a17, _b, _c;
886
+ const res = {
887
+ type: "array"
888
+ };
889
+ if (((_a17 = def.type) == null ? void 0 : _a17._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
890
+ res.items = parseDef(def.type._def, {
891
+ ...refs,
892
+ currentPath: [...refs.currentPath, "items"]
893
+ });
894
+ }
895
+ if (def.minLength) {
896
+ res.minItems = def.minLength.value;
897
+ }
898
+ if (def.maxLength) {
899
+ res.maxItems = def.maxLength.value;
900
+ }
901
+ if (def.exactLength) {
902
+ res.minItems = def.exactLength.value;
903
+ res.maxItems = def.exactLength.value;
904
+ }
905
+ return res;
906
+ }
907
+ function parseBigintDef(def) {
908
+ const res = {
909
+ type: "integer",
910
+ format: "int64"
911
+ };
912
+ if (!def.checks)
913
+ return res;
914
+ for (const check of def.checks) {
915
+ switch (check.kind) {
916
+ case "min":
917
+ if (check.inclusive) {
918
+ res.minimum = check.value;
919
+ } else {
920
+ res.exclusiveMinimum = check.value;
921
+ }
922
+ break;
923
+ case "max":
924
+ if (check.inclusive) {
925
+ res.maximum = check.value;
926
+ } else {
927
+ res.exclusiveMaximum = check.value;
928
+ }
929
+ break;
930
+ case "multipleOf":
931
+ res.multipleOf = check.value;
932
+ break;
933
+ }
934
+ }
935
+ return res;
936
+ }
937
+ function parseBooleanDef() {
938
+ return { type: "boolean" };
939
+ }
940
+ function parseBrandedDef(_def, refs) {
941
+ return parseDef(_def.type._def, refs);
942
+ }
943
+ var parseCatchDef = (def, refs) => {
944
+ return parseDef(def.innerType._def, refs);
945
+ };
946
+ function parseDateDef(def, refs, overrideDateStrategy) {
947
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
948
+ if (Array.isArray(strategy)) {
949
+ return {
950
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
951
+ };
952
+ }
953
+ switch (strategy) {
954
+ case "string":
955
+ case "format:date-time":
956
+ return {
957
+ type: "string",
958
+ format: "date-time"
959
+ };
960
+ case "format:date":
961
+ return {
962
+ type: "string",
963
+ format: "date"
964
+ };
965
+ case "integer":
966
+ return integerDateParser(def);
967
+ }
968
+ }
969
+ var integerDateParser = (def) => {
970
+ const res = {
971
+ type: "integer",
972
+ format: "unix-time"
973
+ };
974
+ for (const check of def.checks) {
975
+ switch (check.kind) {
976
+ case "min":
977
+ res.minimum = check.value;
978
+ break;
979
+ case "max":
980
+ res.maximum = check.value;
981
+ break;
982
+ }
983
+ }
984
+ return res;
985
+ };
986
+ function parseDefaultDef(_def, refs) {
987
+ return {
988
+ ...parseDef(_def.innerType._def, refs),
989
+ default: _def.defaultValue()
990
+ };
991
+ }
992
+ function parseEffectsDef(_def, refs) {
993
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
994
+ }
995
+ function parseEnumDef(def) {
996
+ return {
997
+ type: "string",
998
+ enum: Array.from(def.values)
999
+ };
1000
+ }
1001
+ var isJsonSchema7AllOfType = (type) => {
1002
+ if ("type" in type && type.type === "string")
1003
+ return false;
1004
+ return "allOf" in type;
1005
+ };
1006
+ function parseIntersectionDef(def, refs) {
1007
+ const allOf = [
1008
+ parseDef(def.left._def, {
1009
+ ...refs,
1010
+ currentPath: [...refs.currentPath, "allOf", "0"]
1011
+ }),
1012
+ parseDef(def.right._def, {
1013
+ ...refs,
1014
+ currentPath: [...refs.currentPath, "allOf", "1"]
1015
+ })
1016
+ ].filter((x) => !!x);
1017
+ const mergedAllOf = [];
1018
+ allOf.forEach((schema) => {
1019
+ if (isJsonSchema7AllOfType(schema)) {
1020
+ mergedAllOf.push(...schema.allOf);
1021
+ } else {
1022
+ let nestedSchema = schema;
1023
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
1024
+ const { additionalProperties, ...rest } = schema;
1025
+ nestedSchema = rest;
1026
+ }
1027
+ mergedAllOf.push(nestedSchema);
1028
+ }
1029
+ });
1030
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
1031
+ }
1032
+ function parseLiteralDef(def) {
1033
+ const parsedType = typeof def.value;
1034
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
1035
+ return {
1036
+ type: Array.isArray(def.value) ? "array" : "object"
1037
+ };
1038
+ }
1039
+ return {
1040
+ type: parsedType === "bigint" ? "integer" : parsedType,
1041
+ const: def.value
1042
+ };
1043
+ }
1044
+ var emojiRegex = void 0;
1045
+ var zodPatterns = {
1046
+ /**
1047
+ * `c` was changed to `[cC]` to replicate /i flag
1048
+ */
1049
+ cuid: /^[cC][^\s-]{8,}$/,
1050
+ cuid2: /^[0-9a-z]+$/,
1051
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
1052
+ /**
1053
+ * `a-z` was added to replicate /i flag
1054
+ */
1055
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
1056
+ /**
1057
+ * Constructed a valid Unicode RegExp
1058
+ *
1059
+ * Lazily instantiate since this type of regex isn't supported
1060
+ * in all envs (e.g. React Native).
1061
+ *
1062
+ * See:
1063
+ * https://github.com/colinhacks/zod/issues/2433
1064
+ * Fix in Zod:
1065
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
1066
+ */
1067
+ emoji: () => {
1068
+ if (emojiRegex === void 0) {
1069
+ emojiRegex = RegExp(
1070
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
1071
+ "u"
1072
+ );
1073
+ }
1074
+ return emojiRegex;
1075
+ },
1076
+ /**
1077
+ * Unused
1078
+ */
1079
+ 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}$/,
1080
+ /**
1081
+ * Unused
1082
+ */
1083
+ 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])$/,
1084
+ 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])$/,
1085
+ /**
1086
+ * Unused
1087
+ */
1088
+ 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})))$/,
1089
+ 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])$/,
1090
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
1091
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
1092
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
1093
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1094
+ };
1095
+ function parseStringDef(def, refs) {
1096
+ const res = {
1097
+ type: "string"
1098
+ };
1099
+ if (def.checks) {
1100
+ for (const check of def.checks) {
1101
+ switch (check.kind) {
1102
+ case "min":
1103
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1104
+ break;
1105
+ case "max":
1106
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1107
+ break;
1108
+ case "email":
1109
+ switch (refs.emailStrategy) {
1110
+ case "format:email":
1111
+ addFormat(res, "email", check.message, refs);
1112
+ break;
1113
+ case "format:idn-email":
1114
+ addFormat(res, "idn-email", check.message, refs);
1115
+ break;
1116
+ case "pattern:zod":
1117
+ addPattern(res, zodPatterns.email, check.message, refs);
1118
+ break;
1119
+ }
1120
+ break;
1121
+ case "url":
1122
+ addFormat(res, "uri", check.message, refs);
1123
+ break;
1124
+ case "uuid":
1125
+ addFormat(res, "uuid", check.message, refs);
1126
+ break;
1127
+ case "regex":
1128
+ addPattern(res, check.regex, check.message, refs);
1129
+ break;
1130
+ case "cuid":
1131
+ addPattern(res, zodPatterns.cuid, check.message, refs);
1132
+ break;
1133
+ case "cuid2":
1134
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
1135
+ break;
1136
+ case "startsWith":
1137
+ addPattern(
1138
+ res,
1139
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
1140
+ check.message,
1141
+ refs
1142
+ );
1143
+ break;
1144
+ case "endsWith":
1145
+ addPattern(
1146
+ res,
1147
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
1148
+ check.message,
1149
+ refs
1150
+ );
1151
+ break;
1152
+ case "datetime":
1153
+ addFormat(res, "date-time", check.message, refs);
1154
+ break;
1155
+ case "date":
1156
+ addFormat(res, "date", check.message, refs);
1157
+ break;
1158
+ case "time":
1159
+ addFormat(res, "time", check.message, refs);
1160
+ break;
1161
+ case "duration":
1162
+ addFormat(res, "duration", check.message, refs);
1163
+ break;
1164
+ case "length":
1165
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1166
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1167
+ break;
1168
+ case "includes": {
1169
+ addPattern(
1170
+ res,
1171
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
1172
+ check.message,
1173
+ refs
1174
+ );
1175
+ break;
1176
+ }
1177
+ case "ip": {
1178
+ if (check.version !== "v6") {
1179
+ addFormat(res, "ipv4", check.message, refs);
1180
+ }
1181
+ if (check.version !== "v4") {
1182
+ addFormat(res, "ipv6", check.message, refs);
1183
+ }
1184
+ break;
1185
+ }
1186
+ case "base64url":
1187
+ addPattern(res, zodPatterns.base64url, check.message, refs);
1188
+ break;
1189
+ case "jwt":
1190
+ addPattern(res, zodPatterns.jwt, check.message, refs);
1191
+ break;
1192
+ case "cidr": {
1193
+ if (check.version !== "v6") {
1194
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1195
+ }
1196
+ if (check.version !== "v4") {
1197
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1198
+ }
1199
+ break;
1200
+ }
1201
+ case "emoji":
1202
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
1203
+ break;
1204
+ case "ulid": {
1205
+ addPattern(res, zodPatterns.ulid, check.message, refs);
1206
+ break;
1207
+ }
1208
+ case "base64": {
1209
+ switch (refs.base64Strategy) {
1210
+ case "format:binary": {
1211
+ addFormat(res, "binary", check.message, refs);
1212
+ break;
1213
+ }
1214
+ case "contentEncoding:base64": {
1215
+ res.contentEncoding = "base64";
1216
+ break;
1217
+ }
1218
+ case "pattern:zod": {
1219
+ addPattern(res, zodPatterns.base64, check.message, refs);
1220
+ break;
1221
+ }
1222
+ }
1223
+ break;
1224
+ }
1225
+ case "nanoid": {
1226
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
1227
+ }
1228
+ case "toLowerCase":
1229
+ case "toUpperCase":
1230
+ case "trim":
1231
+ break;
1232
+ default:
1233
+ /* @__PURE__ */ ((_) => {
1234
+ })(check);
1235
+ }
1236
+ }
1237
+ }
1238
+ return res;
1239
+ }
1240
+ function escapeLiteralCheckValue(literal, refs) {
1241
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1242
+ }
1243
+ var ALPHA_NUMERIC = new Set(
1244
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1245
+ );
1246
+ function escapeNonAlphaNumeric(source) {
1247
+ let result = "";
1248
+ for (let i = 0; i < source.length; i++) {
1249
+ if (!ALPHA_NUMERIC.has(source[i])) {
1250
+ result += "\\";
1251
+ }
1252
+ result += source[i];
1253
+ }
1254
+ return result;
1255
+ }
1256
+ function addFormat(schema, value, message, refs) {
1257
+ var _a17;
1258
+ if (schema.format || ((_a17 = schema.anyOf) == null ? void 0 : _a17.some((x) => x.format))) {
1259
+ if (!schema.anyOf) {
1260
+ schema.anyOf = [];
1261
+ }
1262
+ if (schema.format) {
1263
+ schema.anyOf.push({
1264
+ format: schema.format
1265
+ });
1266
+ delete schema.format;
1267
+ }
1268
+ schema.anyOf.push({
1269
+ format: value,
1270
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
1271
+ });
1272
+ } else {
1273
+ schema.format = value;
1274
+ }
1275
+ }
1276
+ function addPattern(schema, regex, message, refs) {
1277
+ var _a17;
1278
+ if (schema.pattern || ((_a17 = schema.allOf) == null ? void 0 : _a17.some((x) => x.pattern))) {
1279
+ if (!schema.allOf) {
1280
+ schema.allOf = [];
1281
+ }
1282
+ if (schema.pattern) {
1283
+ schema.allOf.push({
1284
+ pattern: schema.pattern
1285
+ });
1286
+ delete schema.pattern;
1287
+ }
1288
+ schema.allOf.push({
1289
+ pattern: stringifyRegExpWithFlags(regex, refs),
1290
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
1291
+ });
1292
+ } else {
1293
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
1294
+ }
1295
+ }
1296
+ function stringifyRegExpWithFlags(regex, refs) {
1297
+ var _a17;
1298
+ if (!refs.applyRegexFlags || !regex.flags) {
1299
+ return regex.source;
1300
+ }
1301
+ const flags = {
1302
+ i: regex.flags.includes("i"),
1303
+ // Case-insensitive
1304
+ m: regex.flags.includes("m"),
1305
+ // `^` and `$` matches adjacent to newline characters
1306
+ s: regex.flags.includes("s")
1307
+ // `.` matches newlines
1308
+ };
1309
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
1310
+ let pattern = "";
1311
+ let isEscaped = false;
1312
+ let inCharGroup = false;
1313
+ let inCharRange = false;
1314
+ for (let i = 0; i < source.length; i++) {
1315
+ if (isEscaped) {
1316
+ pattern += source[i];
1317
+ isEscaped = false;
1318
+ continue;
1319
+ }
1320
+ if (flags.i) {
1321
+ if (inCharGroup) {
1322
+ if (source[i].match(/[a-z]/)) {
1323
+ if (inCharRange) {
1324
+ pattern += source[i];
1325
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1326
+ inCharRange = false;
1327
+ } else if (source[i + 1] === "-" && ((_a17 = source[i + 2]) == null ? void 0 : _a17.match(/[a-z]/))) {
1328
+ pattern += source[i];
1329
+ inCharRange = true;
1330
+ } else {
1331
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1332
+ }
1333
+ continue;
1334
+ }
1335
+ } else if (source[i].match(/[a-z]/)) {
1336
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1337
+ continue;
1338
+ }
1339
+ }
1340
+ if (flags.m) {
1341
+ if (source[i] === "^") {
1342
+ pattern += `(^|(?<=[\r
1343
+ ]))`;
1344
+ continue;
1345
+ } else if (source[i] === "$") {
1346
+ pattern += `($|(?=[\r
1347
+ ]))`;
1348
+ continue;
1349
+ }
1350
+ }
1351
+ if (flags.s && source[i] === ".") {
1352
+ pattern += inCharGroup ? `${source[i]}\r
1353
+ ` : `[${source[i]}\r
1354
+ ]`;
1355
+ continue;
1356
+ }
1357
+ pattern += source[i];
1358
+ if (source[i] === "\\") {
1359
+ isEscaped = true;
1360
+ } else if (inCharGroup && source[i] === "]") {
1361
+ inCharGroup = false;
1362
+ } else if (!inCharGroup && source[i] === "[") {
1363
+ inCharGroup = true;
1364
+ }
1365
+ }
1366
+ try {
1367
+ new RegExp(pattern);
1368
+ } catch (e) {
1369
+ console.warn(
1370
+ `Could not convert regex pattern at ${refs.currentPath.join(
1371
+ "/"
1372
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
1373
+ );
1374
+ return regex.source;
1375
+ }
1376
+ return pattern;
1377
+ }
1378
+ function parseRecordDef(def, refs) {
1379
+ var _a17, _b, _c, _d, _e, _f;
1380
+ const schema = {
1381
+ type: "object",
1382
+ additionalProperties: (_a17 = parseDef(def.valueType._def, {
1383
+ ...refs,
1384
+ currentPath: [...refs.currentPath, "additionalProperties"]
1385
+ })) != null ? _a17 : refs.allowedAdditionalProperties
1386
+ };
1387
+ if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1388
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1389
+ return {
1390
+ ...schema,
1391
+ propertyNames: keyType
1392
+ };
1393
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1394
+ return {
1395
+ ...schema,
1396
+ propertyNames: {
1397
+ enum: def.keyType._def.values
1398
+ }
1399
+ };
1400
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1401
+ const { type, ...keyType } = parseBrandedDef(
1402
+ def.keyType._def,
1403
+ refs
1404
+ );
1405
+ return {
1406
+ ...schema,
1407
+ propertyNames: keyType
1408
+ };
1409
+ }
1410
+ return schema;
1411
+ }
1412
+ function parseMapDef(def, refs) {
1413
+ if (refs.mapStrategy === "record") {
1414
+ return parseRecordDef(def, refs);
1415
+ }
1416
+ const keys = parseDef(def.keyType._def, {
1417
+ ...refs,
1418
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1419
+ }) || parseAnyDef();
1420
+ const values = parseDef(def.valueType._def, {
1421
+ ...refs,
1422
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1423
+ }) || parseAnyDef();
1424
+ return {
1425
+ type: "array",
1426
+ maxItems: 125,
1427
+ items: {
1428
+ type: "array",
1429
+ items: [keys, values],
1430
+ minItems: 2,
1431
+ maxItems: 2
1432
+ }
1433
+ };
1434
+ }
1435
+ function parseNativeEnumDef(def) {
1436
+ const object2 = def.values;
1437
+ const actualKeys = Object.keys(def.values).filter((key) => {
1438
+ return typeof object2[object2[key]] !== "number";
1439
+ });
1440
+ const actualValues = actualKeys.map((key) => object2[key]);
1441
+ const parsedTypes = Array.from(
1442
+ new Set(actualValues.map((values) => typeof values))
1443
+ );
1444
+ return {
1445
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1446
+ enum: actualValues
1447
+ };
1448
+ }
1449
+ function parseNeverDef() {
1450
+ return { not: parseAnyDef() };
1451
+ }
1452
+ function parseNullDef() {
1453
+ return {
1454
+ type: "null"
1455
+ };
1456
+ }
1457
+ var primitiveMappings = {
1458
+ ZodString: "string",
1459
+ ZodNumber: "number",
1460
+ ZodBigInt: "integer",
1461
+ ZodBoolean: "boolean",
1462
+ ZodNull: "null"
1463
+ };
1464
+ function parseUnionDef(def, refs) {
1465
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1466
+ if (options.every(
1467
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1468
+ )) {
1469
+ const types = options.reduce((types2, x) => {
1470
+ const type = primitiveMappings[x._def.typeName];
1471
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1472
+ }, []);
1473
+ return {
1474
+ type: types.length > 1 ? types : types[0]
1475
+ };
1476
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1477
+ const types = options.reduce(
1478
+ (acc, x) => {
1479
+ const type = typeof x._def.value;
1480
+ switch (type) {
1481
+ case "string":
1482
+ case "number":
1483
+ case "boolean":
1484
+ return [...acc, type];
1485
+ case "bigint":
1486
+ return [...acc, "integer"];
1487
+ case "object":
1488
+ if (x._def.value === null)
1489
+ return [...acc, "null"];
1490
+ case "symbol":
1491
+ case "undefined":
1492
+ case "function":
1493
+ default:
1494
+ return acc;
1495
+ }
1496
+ },
1497
+ []
1498
+ );
1499
+ if (types.length === options.length) {
1500
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1501
+ return {
1502
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1503
+ enum: options.reduce(
1504
+ (acc, x) => {
1505
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1506
+ },
1507
+ []
1508
+ )
1509
+ };
1510
+ }
1511
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1512
+ return {
1513
+ type: "string",
1514
+ enum: options.reduce(
1515
+ (acc, x) => [
1516
+ ...acc,
1517
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1518
+ ],
1519
+ []
1520
+ )
1521
+ };
1522
+ }
1523
+ return asAnyOf(def, refs);
1524
+ }
1525
+ var asAnyOf = (def, refs) => {
1526
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1527
+ (x, i) => parseDef(x._def, {
1528
+ ...refs,
1529
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1530
+ })
1531
+ ).filter(
1532
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1533
+ );
1534
+ return anyOf.length ? { anyOf } : void 0;
1535
+ };
1536
+ function parseNullableDef(def, refs) {
1537
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1538
+ def.innerType._def.typeName
1539
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1540
+ return {
1541
+ type: [
1542
+ primitiveMappings[def.innerType._def.typeName],
1543
+ "null"
1544
+ ]
1545
+ };
1546
+ }
1547
+ const base = parseDef(def.innerType._def, {
1548
+ ...refs,
1549
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1550
+ });
1551
+ return base && { anyOf: [base, { type: "null" }] };
1552
+ }
1553
+ function parseNumberDef(def) {
1554
+ const res = {
1555
+ type: "number"
1556
+ };
1557
+ if (!def.checks)
1558
+ return res;
1559
+ for (const check of def.checks) {
1560
+ switch (check.kind) {
1561
+ case "int":
1562
+ res.type = "integer";
1563
+ break;
1564
+ case "min":
1565
+ if (check.inclusive) {
1566
+ res.minimum = check.value;
1567
+ } else {
1568
+ res.exclusiveMinimum = check.value;
1569
+ }
1570
+ break;
1571
+ case "max":
1572
+ if (check.inclusive) {
1573
+ res.maximum = check.value;
1574
+ } else {
1575
+ res.exclusiveMaximum = check.value;
1576
+ }
1577
+ break;
1578
+ case "multipleOf":
1579
+ res.multipleOf = check.value;
1580
+ break;
1581
+ }
1582
+ }
1583
+ return res;
1584
+ }
1585
+ function parseObjectDef(def, refs) {
1586
+ const result = {
1587
+ type: "object",
1588
+ properties: {}
1589
+ };
1590
+ const required = [];
1591
+ const shape = def.shape();
1592
+ for (const propName in shape) {
1593
+ let propDef = shape[propName];
1594
+ if (propDef === void 0 || propDef._def === void 0) {
1595
+ continue;
1596
+ }
1597
+ const propOptional = safeIsOptional(propDef);
1598
+ const parsedDef = parseDef(propDef._def, {
1599
+ ...refs,
1600
+ currentPath: [...refs.currentPath, "properties", propName],
1601
+ propertyPath: [...refs.currentPath, "properties", propName]
1602
+ });
1603
+ if (parsedDef === void 0) {
1604
+ continue;
1605
+ }
1606
+ result.properties[propName] = parsedDef;
1607
+ if (!propOptional) {
1608
+ required.push(propName);
1609
+ }
1610
+ }
1611
+ if (required.length) {
1612
+ result.required = required;
1613
+ }
1614
+ const additionalProperties = decideAdditionalProperties(def, refs);
1615
+ if (additionalProperties !== void 0) {
1616
+ result.additionalProperties = additionalProperties;
1617
+ }
1618
+ return result;
1619
+ }
1620
+ function decideAdditionalProperties(def, refs) {
1621
+ if (def.catchall._def.typeName !== "ZodNever") {
1622
+ return parseDef(def.catchall._def, {
1623
+ ...refs,
1624
+ currentPath: [...refs.currentPath, "additionalProperties"]
1625
+ });
1626
+ }
1627
+ switch (def.unknownKeys) {
1628
+ case "passthrough":
1629
+ return refs.allowedAdditionalProperties;
1630
+ case "strict":
1631
+ return refs.rejectedAdditionalProperties;
1632
+ case "strip":
1633
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1634
+ }
1635
+ }
1636
+ function safeIsOptional(schema) {
1637
+ try {
1638
+ return schema.isOptional();
1639
+ } catch (e) {
1640
+ return true;
1641
+ }
1642
+ }
1643
+ var parseOptionalDef = (def, refs) => {
1644
+ var _a17;
1645
+ if (refs.currentPath.toString() === ((_a17 = refs.propertyPath) == null ? void 0 : _a17.toString())) {
1646
+ return parseDef(def.innerType._def, refs);
1647
+ }
1648
+ const innerSchema = parseDef(def.innerType._def, {
1649
+ ...refs,
1650
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1651
+ });
1652
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1653
+ };
1654
+ var parsePipelineDef = (def, refs) => {
1655
+ if (refs.pipeStrategy === "input") {
1656
+ return parseDef(def.in._def, refs);
1657
+ } else if (refs.pipeStrategy === "output") {
1658
+ return parseDef(def.out._def, refs);
1659
+ }
1660
+ const a = parseDef(def.in._def, {
1661
+ ...refs,
1662
+ currentPath: [...refs.currentPath, "allOf", "0"]
1663
+ });
1664
+ const b = parseDef(def.out._def, {
1665
+ ...refs,
1666
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1667
+ });
1668
+ return {
1669
+ allOf: [a, b].filter((x) => x !== void 0)
1670
+ };
1671
+ };
1672
+ function parsePromiseDef(def, refs) {
1673
+ return parseDef(def.type._def, refs);
1674
+ }
1675
+ function parseSetDef(def, refs) {
1676
+ const items = parseDef(def.valueType._def, {
1677
+ ...refs,
1678
+ currentPath: [...refs.currentPath, "items"]
1679
+ });
1680
+ const schema = {
1681
+ type: "array",
1682
+ uniqueItems: true,
1683
+ items
1684
+ };
1685
+ if (def.minSize) {
1686
+ schema.minItems = def.minSize.value;
1687
+ }
1688
+ if (def.maxSize) {
1689
+ schema.maxItems = def.maxSize.value;
1690
+ }
1691
+ return schema;
1692
+ }
1693
+ function parseTupleDef(def, refs) {
1694
+ if (def.rest) {
1695
+ return {
1696
+ type: "array",
1697
+ minItems: def.items.length,
1698
+ items: def.items.map(
1699
+ (x, i) => parseDef(x._def, {
1700
+ ...refs,
1701
+ currentPath: [...refs.currentPath, "items", `${i}`]
1702
+ })
1703
+ ).reduce(
1704
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1705
+ []
1706
+ ),
1707
+ additionalItems: parseDef(def.rest._def, {
1708
+ ...refs,
1709
+ currentPath: [...refs.currentPath, "additionalItems"]
1710
+ })
1711
+ };
1712
+ } else {
1713
+ return {
1714
+ type: "array",
1715
+ minItems: def.items.length,
1716
+ maxItems: def.items.length,
1717
+ items: def.items.map(
1718
+ (x, i) => parseDef(x._def, {
1719
+ ...refs,
1720
+ currentPath: [...refs.currentPath, "items", `${i}`]
1721
+ })
1722
+ ).reduce(
1723
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1724
+ []
1725
+ )
1726
+ };
1727
+ }
1728
+ }
1729
+ function parseUndefinedDef() {
1730
+ return {
1731
+ not: parseAnyDef()
1732
+ };
1733
+ }
1734
+ function parseUnknownDef() {
1735
+ return parseAnyDef();
1736
+ }
1737
+ var parseReadonlyDef = (def, refs) => {
1738
+ return parseDef(def.innerType._def, refs);
1739
+ };
1740
+ var selectParser = (def, typeName, refs) => {
1741
+ switch (typeName) {
1742
+ case ZodFirstPartyTypeKind3.ZodString:
1743
+ return parseStringDef(def, refs);
1744
+ case ZodFirstPartyTypeKind3.ZodNumber:
1745
+ return parseNumberDef(def);
1746
+ case ZodFirstPartyTypeKind3.ZodObject:
1747
+ return parseObjectDef(def, refs);
1748
+ case ZodFirstPartyTypeKind3.ZodBigInt:
1749
+ return parseBigintDef(def);
1750
+ case ZodFirstPartyTypeKind3.ZodBoolean:
1751
+ return parseBooleanDef();
1752
+ case ZodFirstPartyTypeKind3.ZodDate:
1753
+ return parseDateDef(def, refs);
1754
+ case ZodFirstPartyTypeKind3.ZodUndefined:
1755
+ return parseUndefinedDef();
1756
+ case ZodFirstPartyTypeKind3.ZodNull:
1757
+ return parseNullDef();
1758
+ case ZodFirstPartyTypeKind3.ZodArray:
1759
+ return parseArrayDef(def, refs);
1760
+ case ZodFirstPartyTypeKind3.ZodUnion:
1761
+ case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1762
+ return parseUnionDef(def, refs);
1763
+ case ZodFirstPartyTypeKind3.ZodIntersection:
1764
+ return parseIntersectionDef(def, refs);
1765
+ case ZodFirstPartyTypeKind3.ZodTuple:
1766
+ return parseTupleDef(def, refs);
1767
+ case ZodFirstPartyTypeKind3.ZodRecord:
1768
+ return parseRecordDef(def, refs);
1769
+ case ZodFirstPartyTypeKind3.ZodLiteral:
1770
+ return parseLiteralDef(def);
1771
+ case ZodFirstPartyTypeKind3.ZodEnum:
1772
+ return parseEnumDef(def);
1773
+ case ZodFirstPartyTypeKind3.ZodNativeEnum:
1774
+ return parseNativeEnumDef(def);
1775
+ case ZodFirstPartyTypeKind3.ZodNullable:
1776
+ return parseNullableDef(def, refs);
1777
+ case ZodFirstPartyTypeKind3.ZodOptional:
1778
+ return parseOptionalDef(def, refs);
1779
+ case ZodFirstPartyTypeKind3.ZodMap:
1780
+ return parseMapDef(def, refs);
1781
+ case ZodFirstPartyTypeKind3.ZodSet:
1782
+ return parseSetDef(def, refs);
1783
+ case ZodFirstPartyTypeKind3.ZodLazy:
1784
+ return () => def.getter()._def;
1785
+ case ZodFirstPartyTypeKind3.ZodPromise:
1786
+ return parsePromiseDef(def, refs);
1787
+ case ZodFirstPartyTypeKind3.ZodNaN:
1788
+ case ZodFirstPartyTypeKind3.ZodNever:
1789
+ return parseNeverDef();
1790
+ case ZodFirstPartyTypeKind3.ZodEffects:
1791
+ return parseEffectsDef(def, refs);
1792
+ case ZodFirstPartyTypeKind3.ZodAny:
1793
+ return parseAnyDef();
1794
+ case ZodFirstPartyTypeKind3.ZodUnknown:
1795
+ return parseUnknownDef();
1796
+ case ZodFirstPartyTypeKind3.ZodDefault:
1797
+ return parseDefaultDef(def, refs);
1798
+ case ZodFirstPartyTypeKind3.ZodBranded:
1799
+ return parseBrandedDef(def, refs);
1800
+ case ZodFirstPartyTypeKind3.ZodReadonly:
1801
+ return parseReadonlyDef(def, refs);
1802
+ case ZodFirstPartyTypeKind3.ZodCatch:
1803
+ return parseCatchDef(def, refs);
1804
+ case ZodFirstPartyTypeKind3.ZodPipeline:
1805
+ return parsePipelineDef(def, refs);
1806
+ case ZodFirstPartyTypeKind3.ZodFunction:
1807
+ case ZodFirstPartyTypeKind3.ZodVoid:
1808
+ case ZodFirstPartyTypeKind3.ZodSymbol:
1809
+ return void 0;
1810
+ default:
1811
+ return /* @__PURE__ */ ((_) => void 0)(typeName);
1812
+ }
1813
+ };
1814
+ function parseDef(def, refs, forceResolution = false) {
1815
+ var _a17;
1816
+ const seenItem = refs.seen.get(def);
1817
+ if (refs.override) {
1818
+ const overrideResult = (_a17 = refs.override) == null ? void 0 : _a17.call(
1819
+ refs,
1820
+ def,
1821
+ refs,
1822
+ seenItem,
1823
+ forceResolution
1824
+ );
1825
+ if (overrideResult !== ignoreOverride) {
1826
+ return overrideResult;
1827
+ }
1828
+ }
1829
+ if (seenItem && !forceResolution) {
1830
+ const seenSchema = get$ref(seenItem, refs);
1831
+ if (seenSchema !== void 0) {
1832
+ return seenSchema;
1833
+ }
1834
+ }
1835
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1836
+ refs.seen.set(def, newItem);
1837
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1838
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1839
+ if (jsonSchema2) {
1840
+ addMeta(def, refs, jsonSchema2);
1841
+ }
1842
+ if (refs.postProcess) {
1843
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1844
+ newItem.jsonSchema = jsonSchema2;
1845
+ return postProcessResult;
1846
+ }
1847
+ newItem.jsonSchema = jsonSchema2;
1848
+ return jsonSchema2;
1849
+ }
1850
+ var get$ref = (item, refs) => {
1851
+ switch (refs.$refStrategy) {
1852
+ case "root":
1853
+ return { $ref: item.path.join("/") };
1854
+ case "relative":
1855
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1856
+ case "none":
1857
+ case "seen": {
1858
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1859
+ console.warn(
1860
+ `Recursive reference detected at ${refs.currentPath.join(
1861
+ "/"
1862
+ )}! Defaulting to any`
1863
+ );
1864
+ return parseAnyDef();
1865
+ }
1866
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1867
+ }
1868
+ }
1869
+ };
1870
+ var addMeta = (def, refs, jsonSchema2) => {
1871
+ if (def.description) {
1872
+ jsonSchema2.description = def.description;
1873
+ }
1874
+ return jsonSchema2;
1875
+ };
1876
+ var getRefs = (options) => {
1877
+ const _options = getDefaultOptions(options);
1878
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1879
+ return {
1880
+ ..._options,
1881
+ currentPath,
1882
+ propertyPath: void 0,
1883
+ seen: new Map(
1884
+ Object.entries(_options.definitions).map(([name17, def]) => [
1885
+ def._def,
1886
+ {
1887
+ def: def._def,
1888
+ path: [..._options.basePath, _options.definitionPath, name17],
1889
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1890
+ jsonSchema: void 0
1891
+ }
1892
+ ])
1893
+ )
1894
+ };
1895
+ };
1896
+ var zodToJsonSchema2 = (schema, options) => {
1897
+ var _a17;
1898
+ const refs = getRefs(options);
1899
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1900
+ (acc, [name23, schema2]) => {
1901
+ var _a23;
1902
+ return {
1903
+ ...acc,
1904
+ [name23]: (_a23 = parseDef(
1905
+ schema2._def,
1906
+ {
1907
+ ...refs,
1908
+ currentPath: [...refs.basePath, refs.definitionPath, name23]
1909
+ },
1910
+ true
1911
+ )) != null ? _a23 : parseAnyDef()
1912
+ };
1913
+ },
1914
+ {}
1915
+ ) : void 0;
1916
+ const name17 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1917
+ const main = (_a17 = parseDef(
1918
+ schema._def,
1919
+ name17 === void 0 ? refs : {
1920
+ ...refs,
1921
+ currentPath: [...refs.basePath, refs.definitionPath, name17]
1922
+ },
1923
+ false
1924
+ )) != null ? _a17 : parseAnyDef();
1925
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1926
+ if (title !== void 0) {
1927
+ main.title = title;
1928
+ }
1929
+ const combined = name17 === void 0 ? definitions ? {
1930
+ ...main,
1931
+ [refs.definitionPath]: definitions
1932
+ } : main : {
1933
+ $ref: [
1934
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1935
+ refs.definitionPath,
1936
+ name17
1937
+ ].join("/"),
1938
+ [refs.definitionPath]: {
1939
+ ...definitions,
1940
+ [name17]: main
1941
+ }
1942
+ };
1943
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1944
+ return combined;
1945
+ };
1946
+ var zod_to_json_schema_default = zodToJsonSchema2;
1947
+ function zod3Schema(zodSchema2, options) {
1948
+ var _a17;
1949
+ const useReferences = (_a17 = options == null ? void 0 : options.useReferences) != null ? _a17 : false;
1950
+ return jsonSchema(
1951
+ zod_to_json_schema_default(zodSchema2, {
1952
+ $refStrategy: useReferences ? "root" : "none"
1953
+ }),
1954
+ {
1955
+ validate: async (value) => {
1956
+ const result = await zodSchema2.safeParseAsync(value);
1957
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1958
+ }
1959
+ }
1960
+ );
1961
+ }
1962
+ function zod4Schema(zodSchema2, options) {
1963
+ var _a17;
1964
+ const useReferences = (_a17 = options == null ? void 0 : options.useReferences) != null ? _a17 : false;
1965
+ const z4JSONSchema = z4.toJSONSchema(zodSchema2, {
1966
+ target: "draft-7",
1967
+ io: "output",
1968
+ reused: useReferences ? "ref" : "inline"
1969
+ });
1970
+ return jsonSchema(z4JSONSchema, {
1971
+ validate: async (value) => {
1972
+ const result = await z4.safeParseAsync(zodSchema2, value);
1973
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1974
+ }
1975
+ });
1976
+ }
1977
+ function isZod4Schema(zodSchema2) {
1978
+ return "_zod" in zodSchema2;
1979
+ }
1980
+ function zodSchema(zodSchema2, options) {
1981
+ if (isZod4Schema(zodSchema2)) {
1982
+ return zod4Schema(zodSchema2, options);
1983
+ } else {
1984
+ return zod3Schema(zodSchema2, options);
1985
+ }
1986
+ }
1987
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
1988
+ function jsonSchema(jsonSchema2, {
1989
+ validate
1990
+ } = {}) {
1991
+ return {
1992
+ [schemaSymbol]: true,
1993
+ _type: void 0,
1994
+ // should never be used directly
1995
+ [validatorSymbol]: true,
1996
+ jsonSchema: jsonSchema2,
1997
+ validate
1998
+ };
1999
+ }
2000
+ function isSchema(value) {
2001
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
2002
+ }
2003
+ function asSchema(schema) {
2004
+ return schema == null ? jsonSchema({
2005
+ properties: {},
2006
+ additionalProperties: false
2007
+ }) : isSchema(schema) ? schema : zodSchema(schema);
2008
+ }
2009
+ var { btoa, atob } = globalThis;
2010
+
2011
+ // node_modules/ai-v5/dist/index.mjs
2012
+ import { z } from "zod/v4";
2013
+ import { z as z6 } from "zod/v4";
2014
+ import { z as z5 } from "zod/v4";
2015
+ import { z as z3 } from "zod/v4";
2016
+ import { z as z2 } from "zod/v4";
2017
+ import { z as z42 } from "zod/v4";
2018
+ import { z as z7 } from "zod/v4";
2019
+ import { z as z9 } from "zod/v4";
2020
+ import { z as z8 } from "zod/v4";
2021
+ import { z as z10 } from "zod/v4";
2022
+ var __defProp = Object.defineProperty;
2023
+ var __export = (target, all) => {
2024
+ for (var name17 in all)
2025
+ __defProp(target, name17, { get: all[name17], enumerable: true });
2026
+ };
2027
+ var name14 = "AI_NoOutputSpecifiedError";
2028
+ var marker15 = `vercel.ai.error.${name14}`;
2029
+ var symbol15 = Symbol.for(marker15);
2030
+ var _a15;
2031
+ _a15 = symbol15;
2032
+ var name22 = "AI_InvalidArgumentError";
2033
+ var marker22 = `vercel.ai.error.${name22}`;
2034
+ var symbol22 = Symbol.for(marker22);
2035
+ var _a22;
2036
+ _a22 = symbol22;
2037
+ var name32 = "AI_InvalidStreamPartError";
2038
+ var marker32 = `vercel.ai.error.${name32}`;
2039
+ var symbol32 = Symbol.for(marker32);
2040
+ var _a32;
2041
+ _a32 = symbol32;
2042
+ var name42 = "AI_InvalidToolInputError";
2043
+ var marker42 = `vercel.ai.error.${name42}`;
2044
+ var symbol42 = Symbol.for(marker42);
2045
+ var _a42;
2046
+ _a42 = symbol42;
2047
+ var name52 = "AI_MCPClientError";
2048
+ var marker52 = `vercel.ai.error.${name52}`;
2049
+ var symbol52 = Symbol.for(marker52);
2050
+ var _a52;
2051
+ _a52 = symbol52;
2052
+ var name62 = "AI_NoImageGeneratedError";
2053
+ var marker62 = `vercel.ai.error.${name62}`;
2054
+ var symbol62 = Symbol.for(marker62);
2055
+ var _a62;
2056
+ _a62 = symbol62;
2057
+ var name72 = "AI_NoObjectGeneratedError";
2058
+ var marker72 = `vercel.ai.error.${name72}`;
2059
+ var symbol72 = Symbol.for(marker72);
2060
+ var _a72;
2061
+ var NoObjectGeneratedError = class extends AISDKError {
2062
+ constructor({
2063
+ message = "No object generated.",
2064
+ cause,
2065
+ text: text2,
2066
+ response,
2067
+ usage,
2068
+ finishReason
2069
+ }) {
2070
+ super({ name: name72, message, cause });
2071
+ this[_a72] = true;
2072
+ this.text = text2;
2073
+ this.response = response;
2074
+ this.usage = usage;
2075
+ this.finishReason = finishReason;
2076
+ }
2077
+ static isInstance(error) {
2078
+ return AISDKError.hasMarker(error, marker72);
2079
+ }
2080
+ };
2081
+ _a72 = symbol72;
2082
+ var name82 = "AI_NoOutputGeneratedError";
2083
+ var marker82 = `vercel.ai.error.${name82}`;
2084
+ var symbol82 = Symbol.for(marker82);
2085
+ var _a82;
2086
+ _a82 = symbol82;
2087
+ var name92 = "AI_NoSuchToolError";
2088
+ var marker92 = `vercel.ai.error.${name92}`;
2089
+ var symbol92 = Symbol.for(marker92);
2090
+ var _a92;
2091
+ _a92 = symbol92;
2092
+ var name102 = "AI_ToolCallRepairError";
2093
+ var marker102 = `vercel.ai.error.${name102}`;
2094
+ var symbol102 = Symbol.for(marker102);
2095
+ var _a102;
2096
+ _a102 = symbol102;
2097
+ var name112 = "AI_InvalidDataContentError";
2098
+ var marker112 = `vercel.ai.error.${name112}`;
2099
+ var symbol112 = Symbol.for(marker112);
2100
+ var _a112;
2101
+ _a112 = symbol112;
2102
+ var name122 = "AI_InvalidMessageRoleError";
2103
+ var marker122 = `vercel.ai.error.${name122}`;
2104
+ var symbol122 = Symbol.for(marker122);
2105
+ var _a122;
2106
+ _a122 = symbol122;
2107
+ var name132 = "AI_MessageConversionError";
2108
+ var marker132 = `vercel.ai.error.${name132}`;
2109
+ var symbol132 = Symbol.for(marker132);
2110
+ var _a132;
2111
+ _a132 = symbol132;
2112
+ var name142 = "AI_DownloadError";
2113
+ var marker142 = `vercel.ai.error.${name142}`;
2114
+ var symbol142 = Symbol.for(marker142);
2115
+ var _a142;
2116
+ _a142 = symbol142;
2117
+ var name15 = "AI_RetryError";
2118
+ var marker152 = `vercel.ai.error.${name15}`;
2119
+ var symbol152 = Symbol.for(marker152);
2120
+ var _a152;
2121
+ _a152 = symbol152;
2122
+ var dataContentSchema = z.union([
2123
+ z.string(),
2124
+ z.instanceof(Uint8Array),
2125
+ z.instanceof(ArrayBuffer),
2126
+ z.custom(
2127
+ // Buffer might not be available in some environments such as CloudFlare:
2128
+ (value) => {
2129
+ var _a17, _b;
2130
+ return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
2131
+ },
2132
+ { message: "Must be a Buffer" }
2133
+ )
2134
+ ]);
2135
+ var jsonValueSchema = z2.lazy(
2136
+ () => z2.union([
2137
+ z2.null(),
2138
+ z2.string(),
2139
+ z2.number(),
2140
+ z2.boolean(),
2141
+ z2.record(z2.string(), jsonValueSchema),
2142
+ z2.array(jsonValueSchema)
2143
+ ])
2144
+ );
2145
+ var providerMetadataSchema = z3.record(
2146
+ z3.string(),
2147
+ z3.record(z3.string(), jsonValueSchema)
2148
+ );
2149
+ var textPartSchema = z42.object({
2150
+ type: z42.literal("text"),
2151
+ text: z42.string(),
2152
+ providerOptions: providerMetadataSchema.optional()
2153
+ });
2154
+ var imagePartSchema = z42.object({
2155
+ type: z42.literal("image"),
2156
+ image: z42.union([dataContentSchema, z42.instanceof(URL)]),
2157
+ mediaType: z42.string().optional(),
2158
+ providerOptions: providerMetadataSchema.optional()
2159
+ });
2160
+ var filePartSchema = z42.object({
2161
+ type: z42.literal("file"),
2162
+ data: z42.union([dataContentSchema, z42.instanceof(URL)]),
2163
+ filename: z42.string().optional(),
2164
+ mediaType: z42.string(),
2165
+ providerOptions: providerMetadataSchema.optional()
2166
+ });
2167
+ var reasoningPartSchema = z42.object({
2168
+ type: z42.literal("reasoning"),
2169
+ text: z42.string(),
2170
+ providerOptions: providerMetadataSchema.optional()
2171
+ });
2172
+ var toolCallPartSchema = z42.object({
2173
+ type: z42.literal("tool-call"),
2174
+ toolCallId: z42.string(),
2175
+ toolName: z42.string(),
2176
+ input: z42.unknown(),
2177
+ providerOptions: providerMetadataSchema.optional(),
2178
+ providerExecuted: z42.boolean().optional()
2179
+ });
2180
+ var outputSchema = z42.discriminatedUnion("type", [
2181
+ z42.object({
2182
+ type: z42.literal("text"),
2183
+ value: z42.string()
2184
+ }),
2185
+ z42.object({
2186
+ type: z42.literal("json"),
2187
+ value: jsonValueSchema
2188
+ }),
2189
+ z42.object({
2190
+ type: z42.literal("error-text"),
2191
+ value: z42.string()
2192
+ }),
2193
+ z42.object({
2194
+ type: z42.literal("error-json"),
2195
+ value: jsonValueSchema
2196
+ }),
2197
+ z42.object({
2198
+ type: z42.literal("content"),
2199
+ value: z42.array(
2200
+ z42.union([
2201
+ z42.object({
2202
+ type: z42.literal("text"),
2203
+ text: z42.string()
2204
+ }),
2205
+ z42.object({
2206
+ type: z42.literal("media"),
2207
+ data: z42.string(),
2208
+ mediaType: z42.string()
2209
+ })
2210
+ ])
2211
+ )
2212
+ })
2213
+ ]);
2214
+ var toolResultPartSchema = z42.object({
2215
+ type: z42.literal("tool-result"),
2216
+ toolCallId: z42.string(),
2217
+ toolName: z42.string(),
2218
+ output: outputSchema,
2219
+ providerOptions: providerMetadataSchema.optional()
2220
+ });
2221
+ var systemModelMessageSchema = z5.object(
2222
+ {
2223
+ role: z5.literal("system"),
2224
+ content: z5.string(),
2225
+ providerOptions: providerMetadataSchema.optional()
2226
+ }
2227
+ );
2228
+ var userModelMessageSchema = z5.object({
2229
+ role: z5.literal("user"),
2230
+ content: z5.union([
2231
+ z5.string(),
2232
+ z5.array(z5.union([textPartSchema, imagePartSchema, filePartSchema]))
2233
+ ]),
2234
+ providerOptions: providerMetadataSchema.optional()
2235
+ });
2236
+ var assistantModelMessageSchema = z5.object({
2237
+ role: z5.literal("assistant"),
2238
+ content: z5.union([
2239
+ z5.string(),
2240
+ z5.array(
2241
+ z5.union([
2242
+ textPartSchema,
2243
+ filePartSchema,
2244
+ reasoningPartSchema,
2245
+ toolCallPartSchema,
2246
+ toolResultPartSchema
2247
+ ])
2248
+ )
2249
+ ]),
2250
+ providerOptions: providerMetadataSchema.optional()
2251
+ });
2252
+ var toolModelMessageSchema = z5.object({
2253
+ role: z5.literal("tool"),
2254
+ content: z5.array(toolResultPartSchema),
2255
+ providerOptions: providerMetadataSchema.optional()
2256
+ });
2257
+ var modelMessageSchema = z5.union([
2258
+ systemModelMessageSchema,
2259
+ userModelMessageSchema,
2260
+ assistantModelMessageSchema,
2261
+ toolModelMessageSchema
2262
+ ]);
2263
+ function stepCountIs(stepCount) {
2264
+ return ({ steps }) => steps.length === stepCount;
2265
+ }
2266
+ var originalGenerateId = createIdGenerator({
2267
+ prefix: "aitxt",
2268
+ size: 24
2269
+ });
2270
+ var JsonToSseTransformStream = class extends TransformStream {
2271
+ constructor() {
2272
+ super({
2273
+ transform(part, controller) {
2274
+ controller.enqueue(`data: ${JSON.stringify(part)}
2275
+
2276
+ `);
2277
+ },
2278
+ flush(controller) {
2279
+ controller.enqueue("data: [DONE]\n\n");
2280
+ }
2281
+ });
2282
+ }
2283
+ };
2284
+ var uiMessageChunkSchema = z7.union([
2285
+ z7.strictObject({
2286
+ type: z7.literal("text-start"),
2287
+ id: z7.string(),
2288
+ providerMetadata: providerMetadataSchema.optional()
2289
+ }),
2290
+ z7.strictObject({
2291
+ type: z7.literal("text-delta"),
2292
+ id: z7.string(),
2293
+ delta: z7.string(),
2294
+ providerMetadata: providerMetadataSchema.optional()
2295
+ }),
2296
+ z7.strictObject({
2297
+ type: z7.literal("text-end"),
2298
+ id: z7.string(),
2299
+ providerMetadata: providerMetadataSchema.optional()
2300
+ }),
2301
+ z7.strictObject({
2302
+ type: z7.literal("error"),
2303
+ errorText: z7.string()
2304
+ }),
2305
+ z7.strictObject({
2306
+ type: z7.literal("tool-input-start"),
2307
+ toolCallId: z7.string(),
2308
+ toolName: z7.string(),
2309
+ providerExecuted: z7.boolean().optional(),
2310
+ dynamic: z7.boolean().optional()
2311
+ }),
2312
+ z7.strictObject({
2313
+ type: z7.literal("tool-input-delta"),
2314
+ toolCallId: z7.string(),
2315
+ inputTextDelta: z7.string()
2316
+ }),
2317
+ z7.strictObject({
2318
+ type: z7.literal("tool-input-available"),
2319
+ toolCallId: z7.string(),
2320
+ toolName: z7.string(),
2321
+ input: z7.unknown(),
2322
+ providerExecuted: z7.boolean().optional(),
2323
+ providerMetadata: providerMetadataSchema.optional(),
2324
+ dynamic: z7.boolean().optional()
2325
+ }),
2326
+ z7.strictObject({
2327
+ type: z7.literal("tool-input-error"),
2328
+ toolCallId: z7.string(),
2329
+ toolName: z7.string(),
2330
+ input: z7.unknown(),
2331
+ providerExecuted: z7.boolean().optional(),
2332
+ providerMetadata: providerMetadataSchema.optional(),
2333
+ dynamic: z7.boolean().optional(),
2334
+ errorText: z7.string()
2335
+ }),
2336
+ z7.strictObject({
2337
+ type: z7.literal("tool-output-available"),
2338
+ toolCallId: z7.string(),
2339
+ output: z7.unknown(),
2340
+ providerExecuted: z7.boolean().optional(),
2341
+ dynamic: z7.boolean().optional(),
2342
+ preliminary: z7.boolean().optional()
2343
+ }),
2344
+ z7.strictObject({
2345
+ type: z7.literal("tool-output-error"),
2346
+ toolCallId: z7.string(),
2347
+ errorText: z7.string(),
2348
+ providerExecuted: z7.boolean().optional(),
2349
+ dynamic: z7.boolean().optional()
2350
+ }),
2351
+ z7.strictObject({
2352
+ type: z7.literal("reasoning"),
2353
+ text: z7.string(),
2354
+ providerMetadata: providerMetadataSchema.optional()
2355
+ }),
2356
+ z7.strictObject({
2357
+ type: z7.literal("reasoning-start"),
2358
+ id: z7.string(),
2359
+ providerMetadata: providerMetadataSchema.optional()
2360
+ }),
2361
+ z7.strictObject({
2362
+ type: z7.literal("reasoning-delta"),
2363
+ id: z7.string(),
2364
+ delta: z7.string(),
2365
+ providerMetadata: providerMetadataSchema.optional()
2366
+ }),
2367
+ z7.strictObject({
2368
+ type: z7.literal("reasoning-end"),
2369
+ id: z7.string(),
2370
+ providerMetadata: providerMetadataSchema.optional()
2371
+ }),
2372
+ z7.strictObject({
2373
+ type: z7.literal("reasoning-part-finish")
2374
+ }),
2375
+ z7.strictObject({
2376
+ type: z7.literal("source-url"),
2377
+ sourceId: z7.string(),
2378
+ url: z7.string(),
2379
+ title: z7.string().optional(),
2380
+ providerMetadata: providerMetadataSchema.optional()
2381
+ }),
2382
+ z7.strictObject({
2383
+ type: z7.literal("source-document"),
2384
+ sourceId: z7.string(),
2385
+ mediaType: z7.string(),
2386
+ title: z7.string(),
2387
+ filename: z7.string().optional(),
2388
+ providerMetadata: providerMetadataSchema.optional()
2389
+ }),
2390
+ z7.strictObject({
2391
+ type: z7.literal("file"),
2392
+ url: z7.string(),
2393
+ mediaType: z7.string(),
2394
+ providerMetadata: providerMetadataSchema.optional()
2395
+ }),
2396
+ z7.strictObject({
2397
+ type: z7.string().startsWith("data-"),
2398
+ id: z7.string().optional(),
2399
+ data: z7.unknown(),
2400
+ transient: z7.boolean().optional()
2401
+ }),
2402
+ z7.strictObject({
2403
+ type: z7.literal("start-step")
2404
+ }),
2405
+ z7.strictObject({
2406
+ type: z7.literal("finish-step")
2407
+ }),
2408
+ z7.strictObject({
2409
+ type: z7.literal("start"),
2410
+ messageId: z7.string().optional(),
2411
+ messageMetadata: z7.unknown().optional()
2412
+ }),
2413
+ z7.strictObject({
2414
+ type: z7.literal("finish"),
2415
+ messageMetadata: z7.unknown().optional()
2416
+ }),
2417
+ z7.strictObject({
2418
+ type: z7.literal("abort")
2419
+ }),
2420
+ z7.strictObject({
2421
+ type: z7.literal("message-metadata"),
2422
+ messageMetadata: z7.unknown()
2423
+ })
2424
+ ]);
2425
+ function fixJson(input) {
2426
+ const stack = ["ROOT"];
2427
+ let lastValidIndex = -1;
2428
+ let literalStart = null;
2429
+ function processValueStart(char, i, swapState) {
2430
+ {
2431
+ switch (char) {
2432
+ case '"': {
2433
+ lastValidIndex = i;
2434
+ stack.pop();
2435
+ stack.push(swapState);
2436
+ stack.push("INSIDE_STRING");
2437
+ break;
2438
+ }
2439
+ case "f":
2440
+ case "t":
2441
+ case "n": {
2442
+ lastValidIndex = i;
2443
+ literalStart = i;
2444
+ stack.pop();
2445
+ stack.push(swapState);
2446
+ stack.push("INSIDE_LITERAL");
2447
+ break;
2448
+ }
2449
+ case "-": {
2450
+ stack.pop();
2451
+ stack.push(swapState);
2452
+ stack.push("INSIDE_NUMBER");
2453
+ break;
2454
+ }
2455
+ case "0":
2456
+ case "1":
2457
+ case "2":
2458
+ case "3":
2459
+ case "4":
2460
+ case "5":
2461
+ case "6":
2462
+ case "7":
2463
+ case "8":
2464
+ case "9": {
2465
+ lastValidIndex = i;
2466
+ stack.pop();
2467
+ stack.push(swapState);
2468
+ stack.push("INSIDE_NUMBER");
2469
+ break;
2470
+ }
2471
+ case "{": {
2472
+ lastValidIndex = i;
2473
+ stack.pop();
2474
+ stack.push(swapState);
2475
+ stack.push("INSIDE_OBJECT_START");
2476
+ break;
2477
+ }
2478
+ case "[": {
2479
+ lastValidIndex = i;
2480
+ stack.pop();
2481
+ stack.push(swapState);
2482
+ stack.push("INSIDE_ARRAY_START");
2483
+ break;
2484
+ }
2485
+ }
2486
+ }
2487
+ }
2488
+ function processAfterObjectValue(char, i) {
2489
+ switch (char) {
2490
+ case ",": {
2491
+ stack.pop();
2492
+ stack.push("INSIDE_OBJECT_AFTER_COMMA");
2493
+ break;
2494
+ }
2495
+ case "}": {
2496
+ lastValidIndex = i;
2497
+ stack.pop();
2498
+ break;
2499
+ }
2500
+ }
2501
+ }
2502
+ function processAfterArrayValue(char, i) {
2503
+ switch (char) {
2504
+ case ",": {
2505
+ stack.pop();
2506
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
2507
+ break;
2508
+ }
2509
+ case "]": {
2510
+ lastValidIndex = i;
2511
+ stack.pop();
2512
+ break;
2513
+ }
2514
+ }
2515
+ }
2516
+ for (let i = 0; i < input.length; i++) {
2517
+ const char = input[i];
2518
+ const currentState = stack[stack.length - 1];
2519
+ switch (currentState) {
2520
+ case "ROOT":
2521
+ processValueStart(char, i, "FINISH");
2522
+ break;
2523
+ case "INSIDE_OBJECT_START": {
2524
+ switch (char) {
2525
+ case '"': {
2526
+ stack.pop();
2527
+ stack.push("INSIDE_OBJECT_KEY");
2528
+ break;
2529
+ }
2530
+ case "}": {
2531
+ lastValidIndex = i;
2532
+ stack.pop();
2533
+ break;
2534
+ }
2535
+ }
2536
+ break;
2537
+ }
2538
+ case "INSIDE_OBJECT_AFTER_COMMA": {
2539
+ switch (char) {
2540
+ case '"': {
2541
+ stack.pop();
2542
+ stack.push("INSIDE_OBJECT_KEY");
2543
+ break;
2544
+ }
2545
+ }
2546
+ break;
2547
+ }
2548
+ case "INSIDE_OBJECT_KEY": {
2549
+ switch (char) {
2550
+ case '"': {
2551
+ stack.pop();
2552
+ stack.push("INSIDE_OBJECT_AFTER_KEY");
2553
+ break;
2554
+ }
2555
+ }
2556
+ break;
2557
+ }
2558
+ case "INSIDE_OBJECT_AFTER_KEY": {
2559
+ switch (char) {
2560
+ case ":": {
2561
+ stack.pop();
2562
+ stack.push("INSIDE_OBJECT_BEFORE_VALUE");
2563
+ break;
2564
+ }
2565
+ }
2566
+ break;
2567
+ }
2568
+ case "INSIDE_OBJECT_BEFORE_VALUE": {
2569
+ processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
2570
+ break;
2571
+ }
2572
+ case "INSIDE_OBJECT_AFTER_VALUE": {
2573
+ processAfterObjectValue(char, i);
2574
+ break;
2575
+ }
2576
+ case "INSIDE_STRING": {
2577
+ switch (char) {
2578
+ case '"': {
2579
+ stack.pop();
2580
+ lastValidIndex = i;
2581
+ break;
2582
+ }
2583
+ case "\\": {
2584
+ stack.push("INSIDE_STRING_ESCAPE");
2585
+ break;
2586
+ }
2587
+ default: {
2588
+ lastValidIndex = i;
2589
+ }
2590
+ }
2591
+ break;
2592
+ }
2593
+ case "INSIDE_ARRAY_START": {
2594
+ switch (char) {
2595
+ case "]": {
2596
+ lastValidIndex = i;
2597
+ stack.pop();
2598
+ break;
2599
+ }
2600
+ default: {
2601
+ lastValidIndex = i;
2602
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
2603
+ break;
2604
+ }
2605
+ }
2606
+ break;
2607
+ }
2608
+ case "INSIDE_ARRAY_AFTER_VALUE": {
2609
+ switch (char) {
2610
+ case ",": {
2611
+ stack.pop();
2612
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
2613
+ break;
2614
+ }
2615
+ case "]": {
2616
+ lastValidIndex = i;
2617
+ stack.pop();
2618
+ break;
2619
+ }
2620
+ default: {
2621
+ lastValidIndex = i;
2622
+ break;
2623
+ }
2624
+ }
2625
+ break;
2626
+ }
2627
+ case "INSIDE_ARRAY_AFTER_COMMA": {
2628
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
2629
+ break;
2630
+ }
2631
+ case "INSIDE_STRING_ESCAPE": {
2632
+ stack.pop();
2633
+ lastValidIndex = i;
2634
+ break;
2635
+ }
2636
+ case "INSIDE_NUMBER": {
2637
+ switch (char) {
2638
+ case "0":
2639
+ case "1":
2640
+ case "2":
2641
+ case "3":
2642
+ case "4":
2643
+ case "5":
2644
+ case "6":
2645
+ case "7":
2646
+ case "8":
2647
+ case "9": {
2648
+ lastValidIndex = i;
2649
+ break;
2650
+ }
2651
+ case "e":
2652
+ case "E":
2653
+ case "-":
2654
+ case ".": {
2655
+ break;
2656
+ }
2657
+ case ",": {
2658
+ stack.pop();
2659
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
2660
+ processAfterArrayValue(char, i);
2661
+ }
2662
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
2663
+ processAfterObjectValue(char, i);
2664
+ }
2665
+ break;
2666
+ }
2667
+ case "}": {
2668
+ stack.pop();
2669
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
2670
+ processAfterObjectValue(char, i);
2671
+ }
2672
+ break;
2673
+ }
2674
+ case "]": {
2675
+ stack.pop();
2676
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
2677
+ processAfterArrayValue(char, i);
2678
+ }
2679
+ break;
2680
+ }
2681
+ default: {
2682
+ stack.pop();
2683
+ break;
2684
+ }
2685
+ }
2686
+ break;
2687
+ }
2688
+ case "INSIDE_LITERAL": {
2689
+ const partialLiteral = input.substring(literalStart, i + 1);
2690
+ if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
2691
+ stack.pop();
2692
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
2693
+ processAfterObjectValue(char, i);
2694
+ } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
2695
+ processAfterArrayValue(char, i);
2696
+ }
2697
+ } else {
2698
+ lastValidIndex = i;
2699
+ }
2700
+ break;
2701
+ }
2702
+ }
2703
+ }
2704
+ let result = input.slice(0, lastValidIndex + 1);
2705
+ for (let i = stack.length - 1; i >= 0; i--) {
2706
+ const state = stack[i];
2707
+ switch (state) {
2708
+ case "INSIDE_STRING": {
2709
+ result += '"';
2710
+ break;
2711
+ }
2712
+ case "INSIDE_OBJECT_KEY":
2713
+ case "INSIDE_OBJECT_AFTER_KEY":
2714
+ case "INSIDE_OBJECT_AFTER_COMMA":
2715
+ case "INSIDE_OBJECT_START":
2716
+ case "INSIDE_OBJECT_BEFORE_VALUE":
2717
+ case "INSIDE_OBJECT_AFTER_VALUE": {
2718
+ result += "}";
2719
+ break;
2720
+ }
2721
+ case "INSIDE_ARRAY_START":
2722
+ case "INSIDE_ARRAY_AFTER_COMMA":
2723
+ case "INSIDE_ARRAY_AFTER_VALUE": {
2724
+ result += "]";
2725
+ break;
2726
+ }
2727
+ case "INSIDE_LITERAL": {
2728
+ const partialLiteral = input.substring(literalStart, input.length);
2729
+ if ("true".startsWith(partialLiteral)) {
2730
+ result += "true".slice(partialLiteral.length);
2731
+ } else if ("false".startsWith(partialLiteral)) {
2732
+ result += "false".slice(partialLiteral.length);
2733
+ } else if ("null".startsWith(partialLiteral)) {
2734
+ result += "null".slice(partialLiteral.length);
2735
+ }
2736
+ }
2737
+ }
2738
+ }
2739
+ return result;
2740
+ }
2741
+ async function parsePartialJson(jsonText) {
2742
+ if (jsonText === void 0) {
2743
+ return { value: void 0, state: "undefined-input" };
2744
+ }
2745
+ let result = await safeParseJSON({ text: jsonText });
2746
+ if (result.success) {
2747
+ return { value: result.value, state: "successful-parse" };
2748
+ }
2749
+ result = await safeParseJSON({ text: fixJson(jsonText) });
2750
+ if (result.success) {
2751
+ return { value: result.value, state: "repaired-parse" };
2752
+ }
2753
+ return { value: void 0, state: "failed-parse" };
2754
+ }
2755
+ var originalGenerateId2 = createIdGenerator({
2756
+ prefix: "aitxt",
2757
+ size: 24
2758
+ });
2759
+ var originalGenerateId3 = createIdGenerator({ prefix: "aiobj", size: 24 });
2760
+ var originalGenerateId4 = createIdGenerator({ prefix: "aiobj", size: 24 });
2761
+ var output_exports = {};
2762
+ __export(output_exports, {
2763
+ object: () => object,
2764
+ text: () => text
2765
+ });
2766
+ var text = () => ({
2767
+ type: "text",
2768
+ responseFormat: { type: "text" },
2769
+ async parsePartial({ text: text2 }) {
2770
+ return { partial: text2 };
2771
+ },
2772
+ async parseOutput({ text: text2 }) {
2773
+ return text2;
2774
+ }
2775
+ });
2776
+ var object = ({
2777
+ schema: inputSchema
2778
+ }) => {
2779
+ const schema = asSchema(inputSchema);
2780
+ return {
2781
+ type: "object",
2782
+ responseFormat: {
2783
+ type: "json",
2784
+ schema: schema.jsonSchema
2785
+ },
2786
+ async parsePartial({ text: text2 }) {
2787
+ const result = await parsePartialJson(text2);
2788
+ switch (result.state) {
2789
+ case "failed-parse":
2790
+ case "undefined-input":
2791
+ return void 0;
2792
+ case "repaired-parse":
2793
+ case "successful-parse":
2794
+ return {
2795
+ // Note: currently no validation of partial results:
2796
+ partial: result.value
2797
+ };
2798
+ default: {
2799
+ const _exhaustiveCheck = result.state;
2800
+ throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
2801
+ }
2802
+ }
2803
+ },
2804
+ async parseOutput({ text: text2 }, context) {
2805
+ const parseResult = await safeParseJSON({ text: text2 });
2806
+ if (!parseResult.success) {
2807
+ throw new NoObjectGeneratedError({
2808
+ message: "No object generated: could not parse the response.",
2809
+ cause: parseResult.error,
2810
+ text: text2,
2811
+ response: context.response,
2812
+ usage: context.usage,
2813
+ finishReason: context.finishReason
2814
+ });
2815
+ }
2816
+ const validationResult = await safeValidateTypes({
2817
+ value: parseResult.value,
2818
+ schema
2819
+ });
2820
+ if (!validationResult.success) {
2821
+ throw new NoObjectGeneratedError({
2822
+ message: "No object generated: response did not match schema.",
2823
+ cause: validationResult.error,
2824
+ text: text2,
2825
+ response: context.response,
2826
+ usage: context.usage,
2827
+ finishReason: context.finishReason
2828
+ });
2829
+ }
2830
+ return validationResult.value;
2831
+ }
2832
+ };
2833
+ };
2834
+ var name16 = "AI_NoSuchProviderError";
2835
+ var marker16 = `vercel.ai.error.${name16}`;
2836
+ var symbol16 = Symbol.for(marker16);
2837
+ var _a16;
2838
+ _a16 = symbol16;
2839
+ var ClientOrServerImplementationSchema = z8.looseObject({
2840
+ name: z8.string(),
2841
+ version: z8.string()
2842
+ });
2843
+ var BaseParamsSchema = z8.looseObject({
2844
+ _meta: z8.optional(z8.object({}).loose())
2845
+ });
2846
+ var ResultSchema = BaseParamsSchema;
2847
+ var RequestSchema = z8.object({
2848
+ method: z8.string(),
2849
+ params: z8.optional(BaseParamsSchema)
2850
+ });
2851
+ var ServerCapabilitiesSchema = z8.looseObject({
2852
+ experimental: z8.optional(z8.object({}).loose()),
2853
+ logging: z8.optional(z8.object({}).loose()),
2854
+ prompts: z8.optional(
2855
+ z8.looseObject({
2856
+ listChanged: z8.optional(z8.boolean())
2857
+ })
2858
+ ),
2859
+ resources: z8.optional(
2860
+ z8.looseObject({
2861
+ subscribe: z8.optional(z8.boolean()),
2862
+ listChanged: z8.optional(z8.boolean())
2863
+ })
2864
+ ),
2865
+ tools: z8.optional(
2866
+ z8.looseObject({
2867
+ listChanged: z8.optional(z8.boolean())
2868
+ })
2869
+ )
2870
+ });
2871
+ var InitializeResultSchema = ResultSchema.extend({
2872
+ protocolVersion: z8.string(),
2873
+ capabilities: ServerCapabilitiesSchema,
2874
+ serverInfo: ClientOrServerImplementationSchema,
2875
+ instructions: z8.optional(z8.string())
2876
+ });
2877
+ var PaginatedResultSchema = ResultSchema.extend({
2878
+ nextCursor: z8.optional(z8.string())
2879
+ });
2880
+ var ToolSchema = z8.object({
2881
+ name: z8.string(),
2882
+ description: z8.optional(z8.string()),
2883
+ inputSchema: z8.object({
2884
+ type: z8.literal("object"),
2885
+ properties: z8.optional(z8.object({}).loose())
2886
+ }).loose()
2887
+ }).loose();
2888
+ var ListToolsResultSchema = PaginatedResultSchema.extend({
2889
+ tools: z8.array(ToolSchema)
2890
+ });
2891
+ var TextContentSchema = z8.object({
2892
+ type: z8.literal("text"),
2893
+ text: z8.string()
2894
+ }).loose();
2895
+ var ImageContentSchema = z8.object({
2896
+ type: z8.literal("image"),
2897
+ data: z8.base64(),
2898
+ mimeType: z8.string()
2899
+ }).loose();
2900
+ var ResourceContentsSchema = z8.object({
2901
+ /**
2902
+ * The URI of this resource.
2903
+ */
2904
+ uri: z8.string(),
2905
+ /**
2906
+ * The MIME type of this resource, if known.
2907
+ */
2908
+ mimeType: z8.optional(z8.string())
2909
+ }).loose();
2910
+ var TextResourceContentsSchema = ResourceContentsSchema.extend({
2911
+ text: z8.string()
2912
+ });
2913
+ var BlobResourceContentsSchema = ResourceContentsSchema.extend({
2914
+ blob: z8.base64()
2915
+ });
2916
+ var EmbeddedResourceSchema = z8.object({
2917
+ type: z8.literal("resource"),
2918
+ resource: z8.union([TextResourceContentsSchema, BlobResourceContentsSchema])
2919
+ }).loose();
2920
+ var CallToolResultSchema = ResultSchema.extend({
2921
+ content: z8.array(
2922
+ z8.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])
2923
+ ),
2924
+ isError: z8.boolean().default(false).optional()
2925
+ }).or(
2926
+ ResultSchema.extend({
2927
+ toolResult: z8.unknown()
2928
+ })
2929
+ );
2930
+ var JSONRPC_VERSION = "2.0";
2931
+ var JSONRPCRequestSchema = z9.object({
2932
+ jsonrpc: z9.literal(JSONRPC_VERSION),
2933
+ id: z9.union([z9.string(), z9.number().int()])
2934
+ }).merge(RequestSchema).strict();
2935
+ var JSONRPCResponseSchema = z9.object({
2936
+ jsonrpc: z9.literal(JSONRPC_VERSION),
2937
+ id: z9.union([z9.string(), z9.number().int()]),
2938
+ result: ResultSchema
2939
+ }).strict();
2940
+ var JSONRPCErrorSchema = z9.object({
2941
+ jsonrpc: z9.literal(JSONRPC_VERSION),
2942
+ id: z9.union([z9.string(), z9.number().int()]),
2943
+ error: z9.object({
2944
+ code: z9.number().int(),
2945
+ message: z9.string(),
2946
+ data: z9.optional(z9.unknown())
2947
+ })
2948
+ }).strict();
2949
+ var JSONRPCNotificationSchema = z9.object({
2950
+ jsonrpc: z9.literal(JSONRPC_VERSION)
2951
+ }).merge(
2952
+ z9.object({
2953
+ method: z9.string(),
2954
+ params: z9.optional(BaseParamsSchema)
2955
+ })
2956
+ ).strict();
2957
+ var JSONRPCMessageSchema = z9.union([
2958
+ JSONRPCRequestSchema,
2959
+ JSONRPCNotificationSchema,
2960
+ JSONRPCResponseSchema,
2961
+ JSONRPCErrorSchema
2962
+ ]);
2963
+ var textUIPartSchema = z10.object({
2964
+ type: z10.literal("text"),
2965
+ text: z10.string(),
2966
+ state: z10.enum(["streaming", "done"]).optional(),
2967
+ providerMetadata: providerMetadataSchema.optional()
2968
+ });
2969
+ var reasoningUIPartSchema = z10.object({
2970
+ type: z10.literal("reasoning"),
2971
+ text: z10.string(),
2972
+ state: z10.enum(["streaming", "done"]).optional(),
2973
+ providerMetadata: providerMetadataSchema.optional()
2974
+ });
2975
+ var sourceUrlUIPartSchema = z10.object({
2976
+ type: z10.literal("source-url"),
2977
+ sourceId: z10.string(),
2978
+ url: z10.string(),
2979
+ title: z10.string().optional(),
2980
+ providerMetadata: providerMetadataSchema.optional()
2981
+ });
2982
+ var sourceDocumentUIPartSchema = z10.object({
2983
+ type: z10.literal("source-document"),
2984
+ sourceId: z10.string(),
2985
+ mediaType: z10.string(),
2986
+ title: z10.string(),
2987
+ filename: z10.string().optional(),
2988
+ providerMetadata: providerMetadataSchema.optional()
2989
+ });
2990
+ var fileUIPartSchema = z10.object({
2991
+ type: z10.literal("file"),
2992
+ mediaType: z10.string(),
2993
+ filename: z10.string().optional(),
2994
+ url: z10.string(),
2995
+ providerMetadata: providerMetadataSchema.optional()
2996
+ });
2997
+ var stepStartUIPartSchema = z10.object({
2998
+ type: z10.literal("step-start")
2999
+ });
3000
+ var dataUIPartSchema = z10.object({
3001
+ type: z10.string().startsWith("data-"),
3002
+ id: z10.string().optional(),
3003
+ data: z10.unknown()
3004
+ });
3005
+ var dynamicToolUIPartSchemas = [
3006
+ z10.object({
3007
+ type: z10.literal("dynamic-tool"),
3008
+ toolName: z10.string(),
3009
+ toolCallId: z10.string(),
3010
+ state: z10.literal("input-streaming"),
3011
+ input: z10.unknown().optional(),
3012
+ output: z10.never().optional(),
3013
+ errorText: z10.never().optional()
3014
+ }),
3015
+ z10.object({
3016
+ type: z10.literal("dynamic-tool"),
3017
+ toolName: z10.string(),
3018
+ toolCallId: z10.string(),
3019
+ state: z10.literal("input-available"),
3020
+ input: z10.unknown(),
3021
+ output: z10.never().optional(),
3022
+ errorText: z10.never().optional(),
3023
+ callProviderMetadata: providerMetadataSchema.optional()
3024
+ }),
3025
+ z10.object({
3026
+ type: z10.literal("dynamic-tool"),
3027
+ toolName: z10.string(),
3028
+ toolCallId: z10.string(),
3029
+ state: z10.literal("output-available"),
3030
+ input: z10.unknown(),
3031
+ output: z10.unknown(),
3032
+ errorText: z10.never().optional(),
3033
+ callProviderMetadata: providerMetadataSchema.optional(),
3034
+ preliminary: z10.boolean().optional()
3035
+ }),
3036
+ z10.object({
3037
+ type: z10.literal("dynamic-tool"),
3038
+ toolName: z10.string(),
3039
+ toolCallId: z10.string(),
3040
+ state: z10.literal("output-error"),
3041
+ input: z10.unknown(),
3042
+ output: z10.never().optional(),
3043
+ errorText: z10.string(),
3044
+ callProviderMetadata: providerMetadataSchema.optional()
3045
+ })
3046
+ ];
3047
+ var toolUIPartSchemas = [
3048
+ z10.object({
3049
+ type: z10.string().startsWith("tool-"),
3050
+ toolCallId: z10.string(),
3051
+ state: z10.literal("input-streaming"),
3052
+ input: z10.unknown().optional(),
3053
+ output: z10.never().optional(),
3054
+ errorText: z10.never().optional()
3055
+ }),
3056
+ z10.object({
3057
+ type: z10.string().startsWith("tool-"),
3058
+ toolCallId: z10.string(),
3059
+ state: z10.literal("input-available"),
3060
+ input: z10.unknown(),
3061
+ output: z10.never().optional(),
3062
+ errorText: z10.never().optional(),
3063
+ callProviderMetadata: providerMetadataSchema.optional()
3064
+ }),
3065
+ z10.object({
3066
+ type: z10.string().startsWith("tool-"),
3067
+ toolCallId: z10.string(),
3068
+ state: z10.literal("output-available"),
3069
+ input: z10.unknown(),
3070
+ output: z10.unknown(),
3071
+ errorText: z10.never().optional(),
3072
+ callProviderMetadata: providerMetadataSchema.optional(),
3073
+ preliminary: z10.boolean().optional()
3074
+ }),
3075
+ z10.object({
3076
+ type: z10.string().startsWith("tool-"),
3077
+ toolCallId: z10.string(),
3078
+ state: z10.literal("output-error"),
3079
+ input: z10.unknown(),
3080
+ output: z10.never().optional(),
3081
+ errorText: z10.string(),
3082
+ callProviderMetadata: providerMetadataSchema.optional()
3083
+ })
3084
+ ];
3085
+ var uiMessageSchema = z10.object({
3086
+ id: z10.string(),
3087
+ role: z10.enum(["system", "user", "assistant"]),
3088
+ metadata: z10.unknown().optional(),
3089
+ parts: z10.array(
3090
+ z10.union([
3091
+ textUIPartSchema,
3092
+ reasoningUIPartSchema,
3093
+ sourceUrlUIPartSchema,
3094
+ sourceDocumentUIPartSchema,
3095
+ fileUIPartSchema,
3096
+ stepStartUIPartSchema,
3097
+ dataUIPartSchema,
3098
+ ...dynamicToolUIPartSchemas,
3099
+ ...toolUIPartSchemas
3100
+ ])
3101
+ )
3102
+ });
3103
+
3104
+ // utils/chat-helpers.ts
3105
+ import { createAnthropic } from "@ai-sdk/anthropic";
3106
+ import { createGoogleGenerativeAI } from "@ai-sdk/google";
3107
+ import { createOpenAI } from "@ai-sdk/openai";
3108
+ import { createOllama } from "ollama-ai-provider";
578
3109
  var createLlmModel = (modelDefinition, apiKey, ollamaBaseUrl) => {
579
3110
  if (!modelDefinition?.id || !modelDefinition?.provider) {
580
3111
  throw new Error(
@@ -605,111 +3136,42 @@ var createLlmModel = (modelDefinition, apiKey, ollamaBaseUrl) => {
605
3136
  );
606
3137
  }
607
3138
  };
608
- var wrapToolsWithStreaming = (tools2, streamingContext) => {
609
- const wrappedTools = {};
610
- for (const [name, tool] of Object.entries(tools2)) {
611
- wrappedTools[name] = {
612
- ...tool,
613
- execute: async (params) => {
614
- const currentToolCallId = ++streamingContext.toolCallId;
615
- const startedAt = Date.now();
616
- if (streamingContext.controller && streamingContext.encoder) {
617
- streamingContext.controller.enqueue(
618
- streamingContext.encoder.encode(
619
- `data: ${JSON.stringify({
620
- type: "tool_call",
621
- toolCall: {
622
- id: currentToolCallId,
623
- name,
624
- parameters: params,
625
- timestamp: /* @__PURE__ */ new Date(),
626
- status: "executing"
627
- }
628
- })}
629
-
630
- `
631
- )
632
- );
633
- }
634
- dbg("Tool executing", { name, currentToolCallId, params });
635
- try {
636
- const result = await tool.execute(params);
637
- dbg("Tool result", {
638
- name,
639
- currentToolCallId,
640
- ms: Date.now() - startedAt
641
- });
642
- if (streamingContext.controller && streamingContext.encoder) {
643
- streamingContext.controller.enqueue(
644
- streamingContext.encoder.encode(
645
- `data: ${JSON.stringify({
646
- type: "tool_result",
647
- toolResult: {
648
- id: currentToolCallId,
649
- toolCallId: currentToolCallId,
650
- result,
651
- timestamp: /* @__PURE__ */ new Date()
652
- }
653
- })}
654
3139
 
655
- `
656
- )
657
- );
658
- }
659
- return result;
660
- } catch (error) {
661
- dbg("Tool error", {
662
- name,
663
- currentToolCallId,
664
- error: error instanceof Error ? error.message : String(error)
665
- });
666
- if (streamingContext.controller && streamingContext.encoder) {
667
- streamingContext.controller.enqueue(
668
- streamingContext.encoder.encode(
669
- `data: ${JSON.stringify({
670
- type: "tool_result",
671
- toolResult: {
672
- id: currentToolCallId,
673
- toolCallId: currentToolCallId,
674
- error: error instanceof Error ? error.message : String(error),
675
- timestamp: /* @__PURE__ */ new Date()
676
- }
677
- })}
3140
+ // routes/mcp/chat.ts
3141
+ var DEBUG_ENABLED = process.env.MCP_DEBUG !== "false";
3142
+ var ELICITATION_TIMEOUT = 3e5;
3143
+ var MAX_AGENT_STEPS = 10;
3144
+ var dbg = (...args) => {
3145
+ if (DEBUG_ENABLED) console.log("[mcp/chat]", ...args);
3146
+ };
3147
+ try {
3148
+ process.setMaxListeners?.(50);
3149
+ } catch {
3150
+ }
3151
+ var chat = new Hono6();
3152
+ var sendSseEvent = (controller, encoder, event) => {
3153
+ const payload = event === "[DONE]" ? "[DONE]" : JSON.stringify(event);
3154
+ controller.enqueue(encoder.encode(`data: ${payload}
678
3155
 
679
- `
680
- )
681
- );
682
- }
683
- throw error;
684
- }
685
- }
686
- };
687
- }
688
- return wrappedTools;
3156
+ `));
689
3157
  };
690
- var handleAgentStepFinish = (streamingContext, text, toolCalls, toolResults) => {
3158
+ var handleAgentStepFinish = (streamingContext, text2, toolCalls, toolResults) => {
691
3159
  try {
692
3160
  if (toolCalls && Array.isArray(toolCalls)) {
693
3161
  for (const call of toolCalls) {
694
3162
  const currentToolCallId = ++streamingContext.toolCallId;
695
3163
  streamingContext.lastEmittedToolCallId = currentToolCallId;
696
3164
  if (streamingContext.controller && streamingContext.encoder) {
697
- streamingContext.controller.enqueue(
698
- streamingContext.encoder.encode(
699
- `data: ${JSON.stringify({
700
- type: "tool_call",
701
- toolCall: {
702
- id: currentToolCallId,
703
- name: call.name || call.toolName,
704
- parameters: call.params || call.args || {},
705
- timestamp: /* @__PURE__ */ new Date(),
706
- status: "executing"
707
- }
708
- })}
709
-
710
- `
711
- )
712
- );
3165
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3166
+ type: "tool_call",
3167
+ toolCall: {
3168
+ id: currentToolCallId,
3169
+ name: call.name || call.toolName,
3170
+ parameters: call.params || call.args || {},
3171
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3172
+ status: "executing"
3173
+ }
3174
+ });
713
3175
  }
714
3176
  }
715
3177
  }
@@ -717,47 +3179,35 @@ var handleAgentStepFinish = (streamingContext, text, toolCalls, toolResults) =>
717
3179
  for (const result of toolResults) {
718
3180
  const currentToolCallId = streamingContext.lastEmittedToolCallId != null ? streamingContext.lastEmittedToolCallId : ++streamingContext.toolCallId;
719
3181
  if (streamingContext.controller && streamingContext.encoder) {
720
- streamingContext.controller.enqueue(
721
- streamingContext.encoder.encode(
722
- `data: ${JSON.stringify({
723
- type: "tool_result",
724
- toolResult: {
725
- id: currentToolCallId,
726
- toolCallId: currentToolCallId,
727
- result: result.result,
728
- error: result.error,
729
- timestamp: /* @__PURE__ */ new Date()
730
- }
731
- })}
732
-
733
- `
734
- )
735
- );
3182
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3183
+ type: "tool_result",
3184
+ toolResult: {
3185
+ id: currentToolCallId,
3186
+ toolCallId: currentToolCallId,
3187
+ result: result.result,
3188
+ error: result.error,
3189
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3190
+ }
3191
+ });
736
3192
  }
737
3193
  }
738
3194
  }
739
3195
  streamingContext.stepIndex = (streamingContext.stepIndex || 0) + 1;
740
3196
  if (streamingContext.controller && streamingContext.encoder) {
741
- streamingContext.controller.enqueue(
742
- streamingContext.encoder.encode(
743
- `data: ${JSON.stringify({
744
- type: "trace_step",
745
- step: streamingContext.stepIndex,
746
- text,
747
- toolCalls: (toolCalls || []).map((c) => ({
748
- name: c.name || c.toolName,
749
- params: c.params || c.args || {}
750
- })),
751
- toolResults: (toolResults || []).map((r) => ({
752
- result: r.result,
753
- error: r.error
754
- })),
755
- timestamp: /* @__PURE__ */ new Date()
756
- })}
757
-
758
- `
759
- )
760
- );
3197
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3198
+ type: "trace_step",
3199
+ step: streamingContext.stepIndex,
3200
+ text: text2,
3201
+ toolCalls: (toolCalls || []).map((c) => ({
3202
+ name: c.name || c.toolName,
3203
+ params: c.params || c.args || {}
3204
+ })),
3205
+ toolResults: (toolResults || []).map((r) => ({
3206
+ result: r.result,
3207
+ error: r.error
3208
+ })),
3209
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3210
+ });
761
3211
  }
762
3212
  } catch (err) {
763
3213
  dbg("onStepFinish error", err);
@@ -766,17 +3216,48 @@ var handleAgentStepFinish = (streamingContext, text, toolCalls, toolResults) =>
766
3216
  var streamAgentResponse = async (streamingContext, stream) => {
767
3217
  let hasContent = false;
768
3218
  let chunkCount = 0;
769
- for await (const chunk of stream.textStream) {
770
- if (chunk && chunk.trim()) {
3219
+ for await (const chunk of stream.fullStream) {
3220
+ chunkCount++;
3221
+ if (chunk.type === "text-delta" && chunk.textDelta) {
771
3222
  hasContent = true;
772
- chunkCount++;
773
- streamingContext.controller.enqueue(
774
- streamingContext.encoder.encode(
775
- `data: ${JSON.stringify({ type: "text", content: chunk })}
776
-
777
- `
778
- )
779
- );
3223
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3224
+ type: "text",
3225
+ content: chunk.textDelta
3226
+ });
3227
+ }
3228
+ if (chunk.type === "tool-call" && chunk.toolName) {
3229
+ const currentToolCallId = ++streamingContext.toolCallId;
3230
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3231
+ type: "tool_call",
3232
+ toolCall: {
3233
+ id: currentToolCallId,
3234
+ name: chunk.toolName,
3235
+ parameters: chunk.args || {},
3236
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3237
+ status: "executing"
3238
+ }
3239
+ });
3240
+ }
3241
+ if (chunk.type === "tool-result" && chunk.result !== void 0) {
3242
+ const currentToolCallId = streamingContext.toolCallId;
3243
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3244
+ type: "tool_result",
3245
+ toolResult: {
3246
+ id: currentToolCallId,
3247
+ toolCallId: currentToolCallId,
3248
+ result: chunk.result,
3249
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3250
+ }
3251
+ });
3252
+ }
3253
+ if (chunk.type === "error" && chunk.error) {
3254
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3255
+ type: "error",
3256
+ error: chunk.error instanceof Error ? chunk.error.message : String(chunk.error)
3257
+ });
3258
+ }
3259
+ if (chunk.type === "finish") {
3260
+ break;
780
3261
  }
781
3262
  }
782
3263
  dbg("Streaming finished", { hasContent, chunkCount });
@@ -787,44 +3268,54 @@ var fallbackToCompletion = async (agent, messages, streamingContext, provider, t
787
3268
  const result = await agent.generate(messages, {
788
3269
  temperature: temperature == null || void 0 ? getDefaultTemperatureByProvider(provider) : temperature
789
3270
  });
3271
+ console.log("result", result);
790
3272
  if (result.text && result.text.trim()) {
791
- streamingContext.controller.enqueue(
792
- streamingContext.encoder.encode(
793
- `data: ${JSON.stringify({
794
- type: "text",
795
- content: result.text
796
- })}
797
-
798
- `
799
- )
800
- );
3273
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3274
+ type: "text",
3275
+ content: result.text
3276
+ });
801
3277
  }
802
3278
  } catch (fallbackErr) {
803
- streamingContext.controller.enqueue(
804
- streamingContext.encoder.encode(
805
- `data: ${JSON.stringify({
806
- type: "text",
807
- content: "Failed to generate response. Please try again. ",
808
- error: fallbackErr instanceof Error ? fallbackErr.message : "Unknown error"
809
- })}
810
-
811
- `
812
- )
813
- );
3279
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3280
+ type: "error",
3281
+ error: fallbackErr instanceof Error ? fallbackErr.message : "Unknown error"
3282
+ });
814
3283
  }
815
3284
  };
816
- var createStreamingResponse = async (agent, messages, toolsets, streamingContext, provider, temperature) => {
817
- const stream = await agent.stream(messages, {
818
- maxSteps: MAX_AGENT_STEPS,
819
- temperature: temperature == null || void 0 ? getDefaultTemperatureByProvider(provider) : temperature,
820
- toolsets,
821
- onStepFinish: ({ text, toolCalls, toolResults }) => {
822
- handleAgentStepFinish(streamingContext, text, toolCalls, toolResults);
3285
+ var fallbackToStreamV1Method = async (agent, messages, streamingContext, provider, temperature) => {
3286
+ try {
3287
+ const stream = await agent.stream(messages, {
3288
+ maxSteps: MAX_AGENT_STEPS,
3289
+ temperature: temperature == null || void 0 ? getDefaultTemperatureByProvider(provider) : temperature,
3290
+ onStepFinish: ({ text: text2, toolCalls, toolResults }) => {
3291
+ handleAgentStepFinish(streamingContext, text2, toolCalls, toolResults);
3292
+ }
3293
+ });
3294
+ let hasContent = false;
3295
+ let chunkCount = 0;
3296
+ for await (const chunk of stream.textStream) {
3297
+ if (chunk && chunk.trim()) {
3298
+ hasContent = true;
3299
+ chunkCount++;
3300
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3301
+ type: "text",
3302
+ content: chunk
3303
+ });
3304
+ }
823
3305
  }
824
- });
825
- const { hasContent } = await streamAgentResponse(streamingContext, stream);
826
- if (!hasContent) {
827
- dbg("No content from textStream; falling back to completion");
3306
+ dbg("Stream method finished", { hasContent, chunkCount });
3307
+ if (!hasContent) {
3308
+ dbg("No content from textStream; falling back to completion");
3309
+ await fallbackToCompletion(
3310
+ agent,
3311
+ messages,
3312
+ streamingContext,
3313
+ provider,
3314
+ temperature
3315
+ );
3316
+ }
3317
+ } catch (streamErr) {
3318
+ dbg("Stream method failed", streamErr);
828
3319
  await fallbackToCompletion(
829
3320
  agent,
830
3321
  messages,
@@ -833,19 +3324,52 @@ var createStreamingResponse = async (agent, messages, toolsets, streamingContext
833
3324
  temperature
834
3325
  );
835
3326
  }
836
- streamingContext.controller.enqueue(
837
- streamingContext.encoder.encode(
838
- `data: ${JSON.stringify({
839
- type: "elicitation_complete"
840
- })}
841
-
842
- `
843
- )
844
- );
845
- streamingContext.controller.enqueue(
846
- streamingContext.encoder.encode(`data: [DONE]
847
-
848
- `)
3327
+ };
3328
+ var createStreamingResponse = async (agent, messages, streamingContext, provider, temperature) => {
3329
+ try {
3330
+ const stream = await agent.streamVNext(messages, {
3331
+ stopWhen: stepCountIs(MAX_AGENT_STEPS),
3332
+ modelSettings: {
3333
+ temperature: temperature == null || void 0 ? getDefaultTemperatureByProvider(provider) : temperature
3334
+ },
3335
+ onStepFinish: ({ text: text2, toolCalls, toolResults }) => {
3336
+ handleAgentStepFinish(streamingContext, text2, toolCalls, toolResults);
3337
+ }
3338
+ });
3339
+ const { hasContent } = await streamAgentResponse(streamingContext, stream);
3340
+ if (!hasContent) {
3341
+ dbg("No content from fullStream; falling back to completion");
3342
+ await fallbackToCompletion(
3343
+ agent,
3344
+ messages,
3345
+ streamingContext,
3346
+ provider,
3347
+ temperature
3348
+ );
3349
+ }
3350
+ } catch (error) {
3351
+ if (error instanceof Error && error.message.includes("V1 models are not supported for streamVNext")) {
3352
+ dbg(
3353
+ "streamVNext not supported for this model, falling back to stream method"
3354
+ );
3355
+ await fallbackToStreamV1Method(
3356
+ agent,
3357
+ messages,
3358
+ streamingContext,
3359
+ provider,
3360
+ temperature
3361
+ );
3362
+ } else {
3363
+ throw error;
3364
+ }
3365
+ }
3366
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3367
+ type: "elicitation_complete"
3368
+ });
3369
+ sendSseEvent(
3370
+ streamingContext.controller,
3371
+ streamingContext.encoder,
3372
+ "[DONE]"
849
3373
  );
850
3374
  };
851
3375
  chat.post("/", async (c) => {
@@ -853,7 +3377,6 @@ chat.post("/", async (c) => {
853
3377
  try {
854
3378
  const requestData = await c.req.json();
855
3379
  const {
856
- serverConfigs,
857
3380
  model,
858
3381
  provider,
859
3382
  apiKey,
@@ -875,8 +3398,11 @@ chat.post("/", async (c) => {
875
3398
  400
876
3399
  );
877
3400
  }
878
- const pending = pendingElicitations2.get(requestId);
879
- if (!pending) {
3401
+ const success = mcpClientManager.respondToElicitation(
3402
+ requestId,
3403
+ response
3404
+ );
3405
+ if (!success) {
880
3406
  return c.json(
881
3407
  {
882
3408
  success: false,
@@ -885,8 +3411,6 @@ chat.post("/", async (c) => {
885
3411
  404
886
3412
  );
887
3413
  }
888
- pending.resolve(response);
889
- pendingElicitations2.delete(requestId);
890
3414
  return c.json({ success: true });
891
3415
  }
892
3416
  if (!model?.id || !apiKey || !messages) {
@@ -898,80 +3422,15 @@ chat.post("/", async (c) => {
898
3422
  400
899
3423
  );
900
3424
  }
901
- if (!serverConfigs || Object.keys(serverConfigs).length === 0) {
902
- return c.json(
903
- {
904
- success: false,
905
- error: "No server configs provided"
906
- },
907
- 400
908
- );
909
- }
910
- const serverErrors = {};
911
- const connectedServers = [];
912
- for (const [serverName, serverConfig] of Object.entries(serverConfigs)) {
913
- try {
914
- await mcpClientManager.connectToServer(serverName, serverConfig);
915
- connectedServers.push(serverName);
916
- dbg("Connected to server", { serverName });
917
- } catch (error) {
918
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
919
- serverErrors[serverName] = errorMessage;
920
- dbg("Failed to connect to server", { serverName, error: errorMessage });
921
- }
922
- }
923
- if (connectedServers.length === 0) {
924
- return c.json(
925
- {
926
- success: false,
927
- error: "Failed to connect to any servers",
928
- details: serverErrors
929
- },
930
- 400
931
- );
932
- }
933
- if (Object.keys(serverErrors).length > 0) {
934
- dbg("Some servers failed to connect", {
935
- connectedServers,
936
- failedServers: Object.keys(serverErrors),
937
- errors: serverErrors
938
- });
939
- }
940
3425
  const llmModel = createLlmModel(model, apiKey, ollamaBaseUrl);
3426
+ const toolsets = await mcpClientManager.getFlattenedToolsetsForEnabledServers();
941
3427
  const agent = new Agent({
942
3428
  name: "MCP Chat Agent",
943
3429
  instructions: systemPrompt || "You are a helpful assistant with access to MCP tools.",
944
3430
  model: llmModel,
945
- tools: void 0
946
- // Start without tools, add them in streaming context
947
- });
948
- const formattedMessages = messages.map((msg) => ({
949
- role: msg.role,
950
- content: msg.content
951
- }));
952
- const allTools = mcpClientManager.getAvailableTools();
953
- const toolsByServer = {};
954
- for (const tool of allTools) {
955
- if (!toolsByServer[tool.serverId]) {
956
- toolsByServer[tool.serverId] = {};
957
- }
958
- toolsByServer[tool.serverId][tool.name] = {
959
- description: tool.description,
960
- inputSchema: tool.inputSchema,
961
- execute: async (params) => {
962
- return await mcpClientManager.executeToolDirect(
963
- `${tool.serverId}:${tool.name}`,
964
- params
965
- );
966
- }
967
- };
968
- }
969
- dbg("Streaming start", {
970
- connectedServers,
971
- toolCount: allTools.length,
972
- messageCount: formattedMessages.length
3431
+ tools: toolsets
973
3432
  });
974
- const encoder = new TextEncoder3();
3433
+ const encoder = new TextEncoder2();
975
3434
  const readableStream = new ReadableStream({
976
3435
  async start(controller) {
977
3436
  const streamingContext = {
@@ -981,70 +3440,53 @@ chat.post("/", async (c) => {
981
3440
  lastEmittedToolCallId: null,
982
3441
  stepIndex: 0
983
3442
  };
984
- const flattenedTools = {};
985
- Object.values(toolsByServer).forEach((serverTools) => {
986
- Object.assign(flattenedTools, serverTools);
987
- });
988
- const streamingWrappedTools = wrapToolsWithStreaming(
989
- flattenedTools,
990
- streamingContext
991
- );
992
- const streamingAgent = new Agent({
993
- name: agent.name,
994
- instructions: agent.instructions,
995
- model: agent.model,
996
- tools: Object.keys(streamingWrappedTools).length > 0 ? streamingWrappedTools : void 0
997
- });
998
3443
  mcpClientManager.setElicitationCallback(async (request) => {
999
3444
  const elicitationRequest = {
1000
3445
  message: request.message,
1001
3446
  requestedSchema: request.schema
1002
3447
  };
1003
3448
  if (streamingContext.controller && streamingContext.encoder) {
1004
- streamingContext.controller.enqueue(
1005
- streamingContext.encoder.encode(
1006
- `data: ${JSON.stringify({
1007
- type: "elicitation_request",
1008
- requestId: request.requestId,
1009
- message: elicitationRequest.message,
1010
- schema: elicitationRequest.requestedSchema,
1011
- timestamp: /* @__PURE__ */ new Date()
1012
- })}
1013
-
1014
- `
1015
- )
3449
+ sendSseEvent(
3450
+ streamingContext.controller,
3451
+ streamingContext.encoder,
3452
+ {
3453
+ type: "elicitation_request",
3454
+ requestId: request.requestId,
3455
+ message: elicitationRequest.message,
3456
+ schema: elicitationRequest.requestedSchema,
3457
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3458
+ }
1016
3459
  );
1017
3460
  }
1018
3461
  return new Promise((resolve, reject) => {
1019
- pendingElicitations2.set(request.requestId, { resolve, reject });
1020
- setTimeout(() => {
1021
- if (pendingElicitations2.has(request.requestId)) {
1022
- pendingElicitations2.delete(request.requestId);
1023
- reject(new Error("Elicitation timeout"));
1024
- }
3462
+ const timeout = setTimeout(() => {
3463
+ reject(new Error("Elicitation timeout"));
1025
3464
  }, ELICITATION_TIMEOUT);
3465
+ mcpClientManager.getPendingElicitations().set(request.requestId, {
3466
+ resolve: (response2) => {
3467
+ clearTimeout(timeout);
3468
+ resolve(response2);
3469
+ },
3470
+ reject: (error) => {
3471
+ clearTimeout(timeout);
3472
+ reject(error);
3473
+ }
3474
+ });
1026
3475
  });
1027
3476
  });
1028
3477
  try {
1029
3478
  await createStreamingResponse(
1030
- streamingAgent,
1031
- formattedMessages,
1032
- toolsByServer,
3479
+ agent,
3480
+ messages,
1033
3481
  streamingContext,
1034
3482
  provider,
1035
3483
  temperature
1036
3484
  );
1037
3485
  } catch (error) {
1038
- controller.enqueue(
1039
- encoder.encode(
1040
- `data: ${JSON.stringify({
1041
- type: "error",
1042
- error: error instanceof Error ? error.message : "Unknown error"
1043
- })}
1044
-
1045
- `
1046
- )
1047
- );
3486
+ sendSseEvent(controller, encoder, {
3487
+ type: "error",
3488
+ error: error instanceof Error ? error.message : "Unknown error"
3489
+ });
1048
3490
  } finally {
1049
3491
  mcpClientManager.clearElicitationCallback();
1050
3492
  controller.close();
@@ -1327,12 +3769,12 @@ tests.post("/run-all", async (c) => {
1327
3769
  try {
1328
3770
  let serverConfigs = {};
1329
3771
  if (test.selectedServers && test.selectedServers.length > 0) {
1330
- for (const name of test.selectedServers) {
1331
- if (allServers[name]) serverConfigs[name] = allServers[name];
3772
+ for (const name17 of test.selectedServers) {
3773
+ if (allServers[name17]) serverConfigs[name17] = allServers[name17];
1332
3774
  }
1333
3775
  } else {
1334
- for (const [name, cfg] of Object.entries(allServers)) {
1335
- serverConfigs[name] = cfg;
3776
+ for (const [name17, cfg] of Object.entries(allServers)) {
3777
+ serverConfigs[name17] = cfg;
1336
3778
  }
1337
3779
  }
1338
3780
  const validation = validateMultipleServerConfigs(serverConfigs);
@@ -1352,37 +3794,37 @@ tests.post("/run-all", async (c) => {
1352
3794
  model
1353
3795
  });
1354
3796
  const toolsets = await client.getToolsets();
1355
- const stream = await agent.stream(
3797
+ const stream = await agent.streamVNext(
1356
3798
  [{ role: "user", content: test.prompt || "" }],
1357
3799
  {
1358
3800
  maxSteps: 10,
1359
- toolsets,
1360
- onStepFinish: ({ text, toolCalls, toolResults }) => {
1361
- step += 1;
1362
- (toolCalls || []).forEach((c2) => {
1363
- const toolName = c2?.name || c2?.toolName;
1364
- if (toolName) {
1365
- calledTools.add(toolName);
1366
- }
1367
- });
1368
- controller.enqueue(
1369
- encoder.encode(
1370
- `data: ${JSON.stringify({
1371
- type: "trace_step",
1372
- testId: test.id,
1373
- step,
1374
- text,
1375
- toolCalls,
1376
- toolResults
1377
- })}
3801
+ toolsets
3802
+ }
3803
+ );
3804
+ for await (const chunk of stream.fullStream) {
3805
+ if (chunk.type === "tool-call" && chunk.payload) {
3806
+ const toolName = chunk.payload.toolName;
3807
+ if (toolName) {
3808
+ calledTools.add(toolName);
3809
+ }
3810
+ }
3811
+ if (chunk.type === "finish") {
3812
+ step += 1;
3813
+ controller.enqueue(
3814
+ encoder.encode(
3815
+ `data: ${JSON.stringify({
3816
+ type: "trace_step",
3817
+ testId: test.id,
3818
+ step,
3819
+ text: "Test completed",
3820
+ toolCalls: Array.from(calledTools),
3821
+ toolResults: []
3822
+ })}
1378
3823
 
1379
3824
  `
1380
- )
1381
- );
1382
- }
3825
+ )
3826
+ );
1383
3827
  }
1384
- );
1385
- for await (const _ of stream.textStream) {
1386
3828
  }
1387
3829
  const called = Array.from(calledTools);
1388
3830
  const missing = Array.from(expectedSet).filter(
@@ -1484,8 +3926,63 @@ oauth.get("/metadata", async (c) => {
1484
3926
  });
1485
3927
  var oauth_default = oauth;
1486
3928
 
3929
+ // routes/mcp/export.ts
3930
+ import { Hono as Hono9 } from "hono";
3931
+ import { zodToJsonSchema as zodToJsonSchema3 } from "zod-to-json-schema";
3932
+ var exporter = new Hono9();
3933
+ exporter.post("/server", async (c) => {
3934
+ try {
3935
+ const { serverId } = await c.req.json();
3936
+ if (!serverId) {
3937
+ return c.json({ error: "serverId is required" }, 400);
3938
+ }
3939
+ const mcp2 = c.mcpJamClientManager;
3940
+ const status = mcp2.getConnectionStatus(serverId);
3941
+ if (status !== "connected") {
3942
+ return c.json({ error: `Server '${serverId}' is not connected` }, 400);
3943
+ }
3944
+ const flattenedTools = await mcp2.getToolsetsForServer(serverId);
3945
+ const tools2 = [];
3946
+ for (const [name17, tool] of Object.entries(flattenedTools)) {
3947
+ let inputSchema = tool.inputSchema;
3948
+ try {
3949
+ inputSchema = zodToJsonSchema3(inputSchema);
3950
+ } catch {
3951
+ }
3952
+ tools2.push({
3953
+ name: name17,
3954
+ description: tool.description,
3955
+ inputSchema,
3956
+ outputSchema: tool.outputSchema
3957
+ });
3958
+ }
3959
+ const resources2 = mcp2.getResourcesForServer(serverId).map((r) => ({
3960
+ uri: r.uri,
3961
+ name: r.name,
3962
+ description: r.description,
3963
+ mimeType: r.mimeType
3964
+ }));
3965
+ const prompts2 = mcp2.getPromptsForServer(serverId).map((p) => ({
3966
+ name: p.name,
3967
+ description: p.description,
3968
+ arguments: p.arguments
3969
+ }));
3970
+ return c.json({
3971
+ serverId,
3972
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
3973
+ tools: tools2,
3974
+ resources: resources2,
3975
+ prompts: prompts2
3976
+ });
3977
+ } catch (err) {
3978
+ const msg = err instanceof Error ? err.message : String(err);
3979
+ return c.json({ error: msg }, 500);
3980
+ }
3981
+ });
3982
+ var export_default = exporter;
3983
+
1487
3984
  // routes/mcp/index.ts
1488
- var mcp = new Hono9();
3985
+ var mcp = new Hono10();
1489
3986
  mcp.get("/health", (c) => {
1490
3987
  return c.json({
1491
3988
  service: "MCP API",
@@ -1501,6 +3998,7 @@ mcp.route("/tests", tests_default);
1501
3998
  mcp.route("/resources", resources_default);
1502
3999
  mcp.route("/prompts", prompts_default);
1503
4000
  mcp.route("/oauth", oauth_default);
4001
+ mcp.route("/export", export_default);
1504
4002
  var mcp_default = mcp;
1505
4003
 
1506
4004
  // services/mcpjam-client-manager.ts
@@ -1526,24 +4024,49 @@ var MCPJamClientManager = class {
1526
4024
  pendingElicitations = /* @__PURE__ */ new Map();
1527
4025
  // Optional callback for handling elicitation requests
1528
4026
  elicitationCallback;
1529
- // Helper method to get unique ID for a server name
1530
- getServerUniqueId(serverName) {
1531
- return this.serverIdMapping.get(serverName);
4027
+ // Centralized server ID resolution - handles both original names and unique IDs
4028
+ resolveServerId(serverIdentifier) {
4029
+ if (this.mcpClients.has(serverIdentifier)) {
4030
+ return serverIdentifier;
4031
+ }
4032
+ return this.serverIdMapping.get(serverIdentifier);
1532
4033
  }
1533
4034
  // Public method to get server ID for external use (like frontend)
1534
4035
  getServerIdForName(serverName) {
1535
4036
  return this.serverIdMapping.get(serverName);
1536
4037
  }
1537
- // Public method to get original server name from a unique server ID
1538
- getOriginalNameForId(uniqueServerId) {
1539
- for (const [originalName, uid] of this.serverIdMapping.entries()) {
1540
- if (uid === uniqueServerId) return originalName;
4038
+ flattenToolsets(toolsets) {
4039
+ const flattenedTools = {};
4040
+ Object.values(toolsets).forEach((serverTools) => {
4041
+ Object.assign(flattenedTools, serverTools);
4042
+ });
4043
+ return flattenedTools;
4044
+ }
4045
+ async getFlattenedToolsetsForEnabledServers() {
4046
+ const allFlattenedTools = {};
4047
+ for (const [serverId, client] of this.mcpClients.entries()) {
4048
+ if (this.getConnectionStatus(serverId) !== "connected") continue;
4049
+ try {
4050
+ const toolsets = await client.getToolsets();
4051
+ const flattenedTools = this.flattenToolsets(toolsets);
4052
+ Object.assign(allFlattenedTools, flattenedTools);
4053
+ } catch (error) {
4054
+ console.warn(`Failed to get tools from server ${serverId}:`, error);
4055
+ }
1541
4056
  }
1542
- return void 0;
4057
+ return allFlattenedTools;
1543
4058
  }
1544
- // Convenience: map an array of unique IDs to their original names (fallback to ID if not found)
1545
- mapIdsToOriginalNames(uniqueIds) {
1546
- return uniqueIds.map((id) => this.getOriginalNameForId(id) || id);
4059
+ async getToolsetsForServer(serverId) {
4060
+ const id = this.resolveServerId(serverId);
4061
+ if (!id) {
4062
+ throw new Error(`No MCP client available for server: ${serverId}`);
4063
+ }
4064
+ const client = this.mcpClients.get(id);
4065
+ if (!client) {
4066
+ throw new Error(`No MCP client available for server: ${serverId}`);
4067
+ }
4068
+ const toolsets = await client.getToolsets();
4069
+ return this.flattenToolsets(toolsets);
1547
4070
  }
1548
4071
  async connectToServer(serverId, serverConfig) {
1549
4072
  const pending = this.pendingConnections.get(serverId);
@@ -1598,7 +4121,7 @@ var MCPJamClientManager = class {
1598
4121
  await connectPromise;
1599
4122
  }
1600
4123
  async disconnectFromServer(serverId) {
1601
- const id = this.getServerUniqueId(serverId);
4124
+ const id = this.resolveServerId(serverId);
1602
4125
  if (!id) return;
1603
4126
  const client = this.mcpClients.get(id);
1604
4127
  if (client) {
@@ -1624,7 +4147,7 @@ var MCPJamClientManager = class {
1624
4147
  }
1625
4148
  }
1626
4149
  getConnectionStatus(serverId) {
1627
- const id = this.getServerUniqueId(serverId);
4150
+ const id = this.resolveServerId(serverId);
1628
4151
  return id ? this.statuses.get(id) || "disconnected" : "disconnected";
1629
4152
  }
1630
4153
  getConnectedServers() {
@@ -1645,13 +4168,10 @@ var MCPJamClientManager = class {
1645
4168
  const client = this.mcpClients.get(serverId);
1646
4169
  if (!client) return;
1647
4170
  const toolsets = await client.getToolsets();
1648
- const flattenedTools = {};
1649
- Object.values(toolsets).forEach((serverTools) => {
1650
- Object.assign(flattenedTools, serverTools);
1651
- });
1652
- for (const [name, tool] of Object.entries(flattenedTools)) {
1653
- this.toolRegistry.set(`${serverId}:${name}`, {
1654
- name,
4171
+ const flattenedTools = this.flattenToolsets(toolsets);
4172
+ for (const [name17, tool] of Object.entries(flattenedTools)) {
4173
+ this.toolRegistry.set(`${serverId}:${name17}`, {
4174
+ name: name17,
1655
4175
  description: tool.description,
1656
4176
  inputSchema: tool.inputSchema,
1657
4177
  outputSchema: tool.outputSchema,
@@ -1691,27 +4211,11 @@ var MCPJamClientManager = class {
1691
4211
  getAvailableTools() {
1692
4212
  return Array.from(this.toolRegistry.values());
1693
4213
  }
1694
- async getToolsetsForServer(serverId) {
1695
- const id = this.getServerUniqueId(serverId);
1696
- if (!id) {
1697
- throw new Error(`No MCP client available for server: ${serverId}`);
1698
- }
1699
- const client = this.mcpClients.get(id);
1700
- if (!client) {
1701
- throw new Error(`No MCP client available for server: ${serverId}`);
1702
- }
1703
- const toolsets = await client.getToolsets();
1704
- const flattenedTools = {};
1705
- Object.values(toolsets).forEach((serverTools) => {
1706
- Object.assign(flattenedTools, serverTools);
1707
- });
1708
- return flattenedTools;
1709
- }
1710
4214
  getAvailableResources() {
1711
4215
  return Array.from(this.resourceRegistry.values());
1712
4216
  }
1713
4217
  getResourcesForServer(serverId) {
1714
- const id = this.getServerUniqueId(serverId);
4218
+ const id = this.resolveServerId(serverId);
1715
4219
  if (!id) return [];
1716
4220
  return Array.from(this.resourceRegistry.values()).filter(
1717
4221
  (r) => r.serverId === id
@@ -1721,7 +4225,7 @@ var MCPJamClientManager = class {
1721
4225
  return Array.from(this.promptRegistry.values());
1722
4226
  }
1723
4227
  getPromptsForServer(serverId) {
1724
- const id = this.getServerUniqueId(serverId);
4228
+ const id = this.resolveServerId(serverId);
1725
4229
  if (!id) return [];
1726
4230
  return Array.from(this.promptRegistry.values()).filter(
1727
4231
  (p) => p.serverId === id
@@ -1729,17 +4233,16 @@ var MCPJamClientManager = class {
1729
4233
  }
1730
4234
  async executeToolDirect(toolName, parameters = {}) {
1731
4235
  let serverId = "";
1732
- let name = toolName;
4236
+ let name17 = toolName;
1733
4237
  if (toolName.includes(":")) {
1734
4238
  const [sid, n] = toolName.split(":", 2);
1735
- const mappedId = this.getServerUniqueId(sid);
1736
- serverId = mappedId || (this.mcpClients.has(sid) ? sid : "");
1737
- name = n;
4239
+ serverId = this.resolveServerId(sid) || "";
4240
+ name17 = n;
1738
4241
  } else {
1739
4242
  for (const tool2 of this.toolRegistry.values()) {
1740
4243
  if (tool2.name === toolName) {
1741
4244
  serverId = tool2.serverId;
1742
- name = toolName;
4245
+ name17 = toolName;
1743
4246
  break;
1744
4247
  }
1745
4248
  }
@@ -1748,13 +4251,10 @@ var MCPJamClientManager = class {
1748
4251
  for (const [clientServerId, client2] of this.mcpClients.entries()) {
1749
4252
  try {
1750
4253
  const toolsets2 = await client2.getToolsets();
1751
- const flattenedTools2 = {};
1752
- Object.values(toolsets2).forEach((serverTools) => {
1753
- Object.assign(flattenedTools2, serverTools);
1754
- });
4254
+ const flattenedTools2 = this.flattenToolsets(toolsets2);
1755
4255
  if (flattenedTools2[toolName]) {
1756
4256
  serverId = clientServerId;
1757
- name = toolName;
4257
+ name17 = toolName;
1758
4258
  break;
1759
4259
  }
1760
4260
  } catch {
@@ -1768,13 +4268,10 @@ var MCPJamClientManager = class {
1768
4268
  if (!client)
1769
4269
  throw new Error(`No MCP client available for server: ${serverId}`);
1770
4270
  const toolsets = await client.getToolsets();
1771
- const flattenedTools = {};
1772
- Object.values(toolsets).forEach((serverTools) => {
1773
- Object.assign(flattenedTools, serverTools);
1774
- });
1775
- const tool = flattenedTools[name];
4271
+ const flattenedTools = this.flattenToolsets(toolsets);
4272
+ const tool = flattenedTools[name17];
1776
4273
  if (!tool)
1777
- throw new Error(`Tool '${name}' not found in server '${serverId}'`);
4274
+ throw new Error(`Tool '${name17}' not found in server '${serverId}'`);
1778
4275
  const schema = tool.inputSchema;
1779
4276
  const hasContextProperty = schema && typeof schema === "object" && schema.properties && Object.prototype.hasOwnProperty.call(
1780
4277
  schema.properties,
@@ -1801,8 +4298,7 @@ var MCPJamClientManager = class {
1801
4298
  }
1802
4299
  async getResource(resourceUri, serverId) {
1803
4300
  let uri = resourceUri;
1804
- const mappedId = this.getServerUniqueId(serverId);
1805
- const resolvedServerId = mappedId || (this.mcpClients.has(serverId) ? serverId : void 0);
4301
+ const resolvedServerId = this.resolveServerId(serverId);
1806
4302
  if (!resolvedServerId) {
1807
4303
  throw new Error(`No MCP client available for server: ${serverId}`);
1808
4304
  }
@@ -1812,8 +4308,7 @@ var MCPJamClientManager = class {
1812
4308
  return { contents: content?.contents || [] };
1813
4309
  }
1814
4310
  async getPrompt(promptName, serverId, args) {
1815
- const mappedId = this.getServerUniqueId(serverId);
1816
- const resolvedServerId = mappedId || (this.mcpClients.has(serverId) ? serverId : void 0);
4311
+ const resolvedServerId = this.resolveServerId(serverId);
1817
4312
  if (!resolvedServerId) {
1818
4313
  throw new Error(`No MCP client available for server: ${serverId}`);
1819
4314
  }
@@ -1902,6 +4397,39 @@ function logBox(content, title) {
1902
4397
  console.log("\u2514" + "\u2500".repeat(width) + "\u2518");
1903
4398
  }
1904
4399
  function getMCPConfigFromEnv() {
4400
+ const configData = process.env.MCP_CONFIG_DATA;
4401
+ if (configData) {
4402
+ try {
4403
+ const config = JSON.parse(configData);
4404
+ console.log("Parsed config data:", config);
4405
+ if (config.mcpServers && Object.keys(config.mcpServers).length > 0) {
4406
+ const servers2 = Object.entries(config.mcpServers).map(
4407
+ ([name17, serverConfig]) => ({
4408
+ name: name17,
4409
+ type: serverConfig.type || "stdio",
4410
+ // Default to stdio if not specified
4411
+ command: serverConfig.command,
4412
+ args: serverConfig.args || [],
4413
+ env: serverConfig.env || {},
4414
+ url: serverConfig.url
4415
+ // For SSE/HTTP connections
4416
+ })
4417
+ );
4418
+ console.log("Transformed servers:", servers2);
4419
+ const autoConnectServer = process.env.MCP_AUTO_CONNECT_SERVER;
4420
+ console.log(
4421
+ "Auto-connect server filter:",
4422
+ autoConnectServer || "none (connect to all)"
4423
+ );
4424
+ return {
4425
+ servers: servers2,
4426
+ autoConnectServer: autoConnectServer || null
4427
+ };
4428
+ }
4429
+ } catch (error) {
4430
+ console.error("Failed to parse MCP_CONFIG_DATA:", error);
4431
+ }
4432
+ }
1905
4433
  const command = process.env.MCP_SERVER_COMMAND;
1906
4434
  if (!command) {
1907
4435
  return null;
@@ -1909,17 +4437,22 @@ function getMCPConfigFromEnv() {
1909
4437
  const argsString = process.env.MCP_SERVER_ARGS;
1910
4438
  const args = argsString ? JSON.parse(argsString) : [];
1911
4439
  return {
1912
- command,
1913
- args,
1914
- name: "CLI Server"
1915
- // Default name for CLI-provided servers
4440
+ servers: [
4441
+ {
4442
+ command,
4443
+ args,
4444
+ name: "CLI Server",
4445
+ // Default name for CLI-provided servers
4446
+ env: {}
4447
+ }
4448
+ ]
1916
4449
  };
1917
4450
  }
1918
4451
  try {
1919
4452
  fixPath();
1920
4453
  } catch {
1921
4454
  }
1922
- var app = new Hono10();
4455
+ var app = new Hono11();
1923
4456
  var mcpJamClientManager = new MCPJamClientManager();
1924
4457
  app.use("*", async (c, next) => {
1925
4458
  c.mcpJamClientManager = mcpJamClientManager;
@@ -1973,7 +4506,8 @@ if (process.env.NODE_ENV === "production") {
1973
4506
  });
1974
4507
  }
1975
4508
  var port = parseInt(process.env.PORT || "3000");
1976
- logBox(`http://localhost:${port}`, "\u{1F680} Inspector Launched");
4509
+ var hostname = process.env.NODE_ENV === "production" ? "127.0.0.1" : "localhost";
4510
+ logBox(`http://${hostname}:${port}`, "\u{1F680} Inspector Launched");
1977
4511
  var server = serve({
1978
4512
  fetch: app.fetch,
1979
4513
  port,