@opentiny/next-sdk 0.2.9 → 0.3.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4068 @@
1
+ import { MessageChannelServerTransport as ge, createTransportPair as ut, MessageChannelClientTransport as ye, sseOptions as dt, streamOptions as pt, createSseProxy as ht, createSocketProxy as mt, createStreamProxy as ft, MessageChannelTransport as gt } from "@opentiny/next";
2
+ import { McpServer as qe } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { SetLevelRequestSchema as Te, SubscribeRequestSchema as yt, UnsubscribeRequestSchema as vt, ListResourcesRequestSchema as wt, RootsListChangedNotificationSchema as _t, CallToolResultSchema as bt, ElicitRequestSchema as St, CreateMessageRequestSchema as Tt, ListRootsRequestSchema as Pt, ToolListChangedNotificationSchema as Ct, PromptListChangedNotificationSchema as Rt, ResourceListChangedNotificationSchema as Mt, ResourceUpdatedNotificationSchema as Et, LoggingMessageNotificationSchema as At, JSONRPCMessageSchema as kt } from "@modelcontextprotocol/sdk/types.js";
4
+ import { dynamicTool as Ot, jsonSchema as It, generateText as Pe, streamText as ie, stepCountIs as xt } from "ai";
5
+ import { TypeValidationError as pe, JSONParseError as Ce, InvalidArgumentError as Lt, AISDKError as K } from "@ai-sdk/provider";
6
+ import * as Re from "zod/v4";
7
+ import { z as o } from "zod/v4";
8
+ import { ZodFirstPartyTypeKind as w } from "zod/v3";
9
+ import { StreamableHTTPClientTransport as se } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
10
+ import { SSEClientTransport as ne } from "@modelcontextprotocol/sdk/client/sse.js";
11
+ import { InMemoryTransport as Ut } from "@modelcontextprotocol/sdk/inMemory.js";
12
+ import { createOpenAI as $t } from "@ai-sdk/openai";
13
+ import { createDeepSeek as jt } from "@ai-sdk/deepseek";
14
+ import { Client as He } from "@modelcontextprotocol/sdk/client/index.js";
15
+ import { WebSocketClientTransport as Nt } from "@modelcontextprotocol/sdk/client/websocket.js";
16
+ class _n {
17
+ constructor(e, r) {
18
+ const s = {
19
+ name: "web-mcp-server",
20
+ version: "1.0.0"
21
+ }, n = {
22
+ prompts: { listChanged: !0 },
23
+ resources: { subscribe: !0, listChanged: !0 },
24
+ tools: { listChanged: !0 },
25
+ completions: {},
26
+ logging: {}
27
+ };
28
+ this.server = new qe(e || s, r || { capabilities: n }), this.server.server.oninitialized = () => {
29
+ this.oninitialized?.();
30
+ }, this.server.server.onclose = () => {
31
+ this.onclose?.();
32
+ }, this.server.server.onerror = (a) => {
33
+ this.onerror?.(a);
34
+ }, this.server.server.setRequestHandler(Te, async () => ({}));
35
+ }
36
+ /**
37
+ * Connects the server to a transport via the specified option.
38
+ */
39
+ async connect(e) {
40
+ return typeof e.start == "function" ? (this.transport = e, this.transport.onclose = void 0, this.transport.onerror = void 0, this.transport.onmessage = void 0) : (this.transport = new ge(e), await this.transport.listen()), await this.server.connect(this.transport), this.transport;
41
+ }
42
+ /**
43
+ * Closes the connection.
44
+ */
45
+ async close() {
46
+ await this.server.close();
47
+ }
48
+ /**
49
+ * Registers a tool with a config object and callback.
50
+ */
51
+ registerTool(e, r, s) {
52
+ return this.server.registerTool(e, r, s);
53
+ }
54
+ /**
55
+ * Registers a prompt with a config object and callback.
56
+ */
57
+ registerPrompt(e, r, s) {
58
+ return this.server.registerPrompt(e, r, s);
59
+ }
60
+ registerResource(e, r, s, n) {
61
+ return typeof r == "string" ? this.server.registerResource(e, r, s, n) : this.server.registerResource(e, r, s, n);
62
+ }
63
+ /**
64
+ * Checks if the server is connected to a transport.
65
+ * @returns True if the server is connected
66
+ */
67
+ isConnected() {
68
+ return this.server.isConnected();
69
+ }
70
+ /**
71
+ * Sends a resource list changed event to the client, if connected.
72
+ */
73
+ sendResourceListChanged() {
74
+ this.server.sendResourceListChanged();
75
+ }
76
+ /**
77
+ * Sends a tool list changed event to the client, if connected.
78
+ */
79
+ sendToolListChanged() {
80
+ this.server.sendToolListChanged();
81
+ }
82
+ /**
83
+ * Sends a prompt list changed event to the client, if connected.
84
+ */
85
+ sendPromptListChanged() {
86
+ this.server.sendPromptListChanged();
87
+ }
88
+ /**
89
+ * After initialization has completed, this will be populated with the client's reported capabilities.
90
+ */
91
+ getClientCapabilities() {
92
+ return this.server.server.getClientCapabilities();
93
+ }
94
+ /**
95
+ * After initialization has completed, this will be populated with information about the client's name and version.
96
+ */
97
+ getClientVersion() {
98
+ return this.server.server.getClientVersion();
99
+ }
100
+ /**
101
+ * Sends a ping to the client to check if it is still connected.
102
+ */
103
+ async ping() {
104
+ return await this.server.server.ping();
105
+ }
106
+ /**
107
+ * Creates a LLM message to be sent to the client.
108
+ */
109
+ async createMessage(e, r) {
110
+ return await this.server.server.createMessage(e, r);
111
+ }
112
+ /**
113
+ * Elicits input from the client, such as a prompt or resource.
114
+ */
115
+ async elicitInput(e, r) {
116
+ return await this.server.server.elicitInput(e, r);
117
+ }
118
+ /**
119
+ * Lists the root resources available to the client.
120
+ */
121
+ async listRoots(e, r) {
122
+ return await this.server.server.listRoots(e, r);
123
+ }
124
+ /**
125
+ * Sends a logging message to the client.
126
+ */
127
+ async sendLoggingMessage(e) {
128
+ return await this.server.server.sendLoggingMessage(e);
129
+ }
130
+ /**
131
+ * Sends a resource updated notification to the client.
132
+ */
133
+ async sendResourceUpdated(e) {
134
+ return await this.server.server.sendResourceUpdated(e);
135
+ }
136
+ /**
137
+ * Sends a request and wait for a response.
138
+ *
139
+ * Do not use this method to emit notifications! Use notification() instead.
140
+ */
141
+ request(e, r, s) {
142
+ return this.server.server.request(e, r, s);
143
+ }
144
+ /**
145
+ * Emits a notification, which is a one-way message that does not expect a response.
146
+ */
147
+ async notification(e, r) {
148
+ return await this.server.server.notification(e, r);
149
+ }
150
+ /**
151
+ * Registers a handler to invoke when this protocol object receives a request with the given method.
152
+ *
153
+ * Note that this will replace any previous request handler for the same method.
154
+ */
155
+ setRequestHandler(e, r) {
156
+ this.server.server.setRequestHandler(e, r);
157
+ }
158
+ /**
159
+ * Removes the request handler for the given method.
160
+ */
161
+ removeRequestHandler(e) {
162
+ this.server.server.removeRequestHandler(e);
163
+ }
164
+ /**
165
+ * Registers a handler to invoke when this protocol object receives a notification with the given method.
166
+ *
167
+ * Note that this will replace any previous notification handler for the same method.
168
+ */
169
+ setNotificationHandler(e, r) {
170
+ this.server.server.setNotificationHandler(e, r);
171
+ }
172
+ /**
173
+ * Removes the notification handler for the given method.
174
+ */
175
+ removeNotificationHandler(e) {
176
+ this.server.server.removeNotificationHandler(e);
177
+ }
178
+ /**
179
+ * Registers a handler for the subscribe request.
180
+ */
181
+ onSubscribe(e) {
182
+ this.server.server.setRequestHandler(yt, e);
183
+ }
184
+ /**
185
+ * Registers a handler for the unsubscribe request.
186
+ */
187
+ onUnsubscribe(e) {
188
+ this.server.server.setRequestHandler(vt, e);
189
+ }
190
+ /**
191
+ * Registers a handler for the set log level request.
192
+ */
193
+ onSetLogLevel(e) {
194
+ this.server.server.setRequestHandler(Te, e);
195
+ }
196
+ /**
197
+ * Registers a handler for the list tools request.
198
+ */
199
+ onListResources(e) {
200
+ this.server.server.setRequestHandler(wt, e);
201
+ }
202
+ /**
203
+ * Registers a handler for the roots list changed notification.
204
+ */
205
+ onRootsListChanged(e) {
206
+ this.server.server.setNotificationHandler(_t, e);
207
+ }
208
+ /**
209
+ * Close the transport for window.addEventListener('pagehide')
210
+ */
211
+ async onPagehide(e) {
212
+ e.persisted || this.transport && typeof this.transport.close == "function" && await this.transport.close();
213
+ }
214
+ }
215
+ const bn = (t, e) => new ge(t, e), Sn = () => ut(), Tn = (t) => t instanceof ge, Pn = (t) => t instanceof qe;
216
+ class qt {
217
+ constructor(e, r) {
218
+ const s = {
219
+ name: "web-mcp-client",
220
+ version: "1.0.0"
221
+ }, n = {
222
+ roots: { listChanged: !0 },
223
+ sampling: {},
224
+ elicitation: {}
225
+ };
226
+ this.client = new He(e || s, r || { capabilities: n }), this.client.onclose = () => {
227
+ this.onclose?.();
228
+ }, this.client.onerror = (a) => {
229
+ this.onerror?.(a);
230
+ };
231
+ }
232
+ /**
233
+ * Connects the client to a transport via the specified option.
234
+ */
235
+ async connect(e) {
236
+ if (typeof e.start == "function")
237
+ return this.transport = e, this.transport.onclose = void 0, this.transport.onerror = void 0, this.transport.onmessage = void 0, await this.client.connect(this.transport), { transport: this.transport, sessionId: this.transport.sessionId };
238
+ const { url: r, token: s, sessionId: n, type: a, agent: i, onError: u } = e;
239
+ if (i === !0) {
240
+ const p = { client: this.client, url: r, token: s, sessionId: n };
241
+ let g;
242
+ return await (async () => {
243
+ const { transport: m, sessionId: y } = a === "sse" ? await ht(p) : a === "socket" ? await mt(p) : await ft(p);
244
+ m.onerror = async (h) => {
245
+ u?.(h);
246
+ }, g = { transport: m, sessionId: y };
247
+ })(), g;
248
+ }
249
+ const l = new URL(r);
250
+ let c;
251
+ if (a === "channel" && (c = new ye(r), await this.client.connect(c)), a === "sse") {
252
+ const p = dt(s, n);
253
+ c = new ne(l, p), await this.client.connect(c);
254
+ }
255
+ if (a === "socket" && (c = new Nt(new URL(`${r}?sessionId=${n}&token=${s}`)), c.sessionId = n, await this.client.connect(c)), typeof c > "u") {
256
+ const p = pt(s, n);
257
+ c = new se(l, p), await this.client.connect(c);
258
+ }
259
+ return this.transport = c, { transport: this.transport, sessionId: this.transport.sessionId };
260
+ }
261
+ /**
262
+ * Closes the connection.
263
+ */
264
+ async close() {
265
+ await this.client.close();
266
+ }
267
+ /**
268
+ * After initialization has completed, this will be populated with the server's reported capabilities.
269
+ */
270
+ getServerCapabilities() {
271
+ return this.client.getServerCapabilities();
272
+ }
273
+ /**
274
+ * After initialization has completed, this will be populated with information about the server's name and version.
275
+ */
276
+ getServerVersion() {
277
+ return this.client.getServerVersion();
278
+ }
279
+ /**
280
+ * After initialization has completed, this may be populated with information about the server's instructions.
281
+ */
282
+ getInstructions() {
283
+ return this.client.getInstructions();
284
+ }
285
+ /**
286
+ * Sends a ping to the server to check if it is still connected.
287
+ */
288
+ async ping(e) {
289
+ return await this.client.ping(e);
290
+ }
291
+ /**
292
+ * Sends a completion request to the server.
293
+ */
294
+ async complete(e, r) {
295
+ return await this.client.complete(e, r);
296
+ }
297
+ /**
298
+ * Sends a request for setting the logging level to the server.
299
+ */
300
+ async setLoggingLevel(e, r) {
301
+ return await this.client.setLoggingLevel(e, r);
302
+ }
303
+ /**
304
+ * Gets the prompt with the given params from the server.
305
+ */
306
+ async getPrompt(e, r) {
307
+ return await this.client.getPrompt(e, r);
308
+ }
309
+ /**
310
+ * Lists all prompts available on the server.
311
+ */
312
+ async listPrompts(e, r) {
313
+ return await this.client.listPrompts(e, r);
314
+ }
315
+ /**
316
+ * Lists all resources available on the server.
317
+ */
318
+ async listResources(e, r) {
319
+ return await this.client.listResources(e, r);
320
+ }
321
+ /**
322
+ * Lists all resource templates available on the server.
323
+ */
324
+ async listResourceTemplates(e, r) {
325
+ return await this.client.listResourceTemplates(e, r);
326
+ }
327
+ /**
328
+ * Reads the resource with the given params from the server.
329
+ */
330
+ async readResource(e, r) {
331
+ return await this.client.readResource(e, r);
332
+ }
333
+ /**
334
+ * Subscribes to a resource on the server.
335
+ */
336
+ async subscribeResource(e, r) {
337
+ return await this.client.subscribeResource(e, r);
338
+ }
339
+ /**
340
+ * Unsubscribes from a resource on the server.
341
+ */
342
+ async unsubscribeResource(e, r) {
343
+ return await this.client.unsubscribeResource(e, r);
344
+ }
345
+ /**
346
+ * Calls a tool on the server with the given parameters.
347
+ */
348
+ async callTool(e, r) {
349
+ return await this.client.callTool(e, bt, r);
350
+ }
351
+ /**
352
+ * Lists all tools available on the server.
353
+ */
354
+ async listTools(e, r) {
355
+ return await this.client.listTools(e, r);
356
+ }
357
+ /**
358
+ * Sends a notification for the roots list changed event to the server.
359
+ */
360
+ async sendRootsListChanged() {
361
+ return await this.client.sendRootsListChanged();
362
+ }
363
+ /**
364
+ * Sends a request and wait for a response.
365
+ *
366
+ * Do not use this method to emit notifications! Use notification() instead.
367
+ */
368
+ request(e, r, s) {
369
+ return this.client.request(e, r, s);
370
+ }
371
+ /**
372
+ * Emits a notification, which is a one-way message that does not expect a response.
373
+ */
374
+ async notification(e, r) {
375
+ return await this.client.notification(e, r);
376
+ }
377
+ /**
378
+ * Registers a handler to invoke when this protocol object receives a request with the given method.
379
+ *
380
+ * Note that this will replace any previous request handler for the same method.
381
+ */
382
+ setRequestHandler(e, r) {
383
+ this.client.setRequestHandler(e, r);
384
+ }
385
+ /**
386
+ * Removes the request handler for the given method.
387
+ */
388
+ removeRequestHandler(e) {
389
+ this.client.removeRequestHandler(e);
390
+ }
391
+ /**
392
+ * Registers a handler to invoke when this protocol object receives a notification with the given method.
393
+ *
394
+ * Note that this will replace any previous notification handler for the same method.
395
+ */
396
+ setNotificationHandler(e, r) {
397
+ this.client.setNotificationHandler(e, r);
398
+ }
399
+ /**
400
+ * Removes the notification handler for the given method.
401
+ */
402
+ removeNotificationHandler(e) {
403
+ this.client.removeNotificationHandler(e);
404
+ }
405
+ /**
406
+ * Registers a handler for the elicitation request.
407
+ */
408
+ onElicit(e) {
409
+ this.client.setRequestHandler(St, e);
410
+ }
411
+ /**
412
+ * Registers a handler for the create LLM message request.
413
+ */
414
+ onCreateMessage(e) {
415
+ this.client.setRequestHandler(Tt, e);
416
+ }
417
+ /**
418
+ * Registers a handler for the list roots request.
419
+ */
420
+ onListRoots(e) {
421
+ this.client.setRequestHandler(Pt, e);
422
+ }
423
+ /**
424
+ * Registers a handler for the tool list changed notification.
425
+ */
426
+ onToolListChanged(e) {
427
+ this.client.setNotificationHandler(Ct, e);
428
+ }
429
+ /**
430
+ * Registers a handler for the prompt list changed notification.
431
+ */
432
+ onPromptListChanged(e) {
433
+ this.client.setNotificationHandler(Rt, e);
434
+ }
435
+ /**
436
+ * Registers a handler for the resource list changed notification.
437
+ */
438
+ onResourceListChanged(e) {
439
+ this.client.setNotificationHandler(Mt, e);
440
+ }
441
+ /**
442
+ * Registers a handler for the resource updated notification.
443
+ */
444
+ onResourceUpdated(e) {
445
+ this.client.setNotificationHandler(Et, e);
446
+ }
447
+ /**
448
+ * Registers a handler for the logging message notification.
449
+ */
450
+ onLoggingMessage(e) {
451
+ this.client.setNotificationHandler(At, e);
452
+ }
453
+ /**
454
+ * Close the transport for window.addEventListener('pagehide')
455
+ */
456
+ async onPagehide(e) {
457
+ e.persisted || (Ht(this.transport) ? await this.transport.terminateSession() : this.transport && typeof this.transport.close == "function" && await this.transport.close());
458
+ }
459
+ }
460
+ const Cn = (t, e) => new ne(t, e), Rn = (t, e) => new se(t, e), Mn = (t, e) => new ye(t, e), En = (t) => t instanceof ne, Ht = (t) => t instanceof se, An = (t) => t instanceof ye, kn = (t) => t instanceof He, On = (t, e, r) => {
461
+ window.postMessage({ type: t, direction: r, data: e }, "*");
462
+ }, In = (t, e, r) => {
463
+ const s = async function(n) {
464
+ n.source === window && n.data.type === t && n.data.direction === r && await e(n.data.data);
465
+ };
466
+ return window.addEventListener("message", s), () => window.removeEventListener("message", s);
467
+ }, Zt = (t, e, r) => {
468
+ if (r.endsWith("content"))
469
+ chrome.tabs.query({}, (s) => {
470
+ s.forEach((n) => {
471
+ chrome.tabs.sendMessage(n.id, { type: t, data: e, direction: r, tabId: n.id });
472
+ });
473
+ });
474
+ else
475
+ return chrome.runtime.sendMessage({ direction: r, type: t, data: e });
476
+ }, Dt = (t, e, r, s) => {
477
+ const n = (a, i, u) => {
478
+ if (a.type === t && a.direction === r && (!s || s && a.tabId === s)) {
479
+ const { data: l } = a;
480
+ e(l, i, u), u(i);
481
+ }
482
+ };
483
+ return chrome.runtime.onMessage.addListener(n), () => chrome.runtime.onMessage.removeListener(n);
484
+ };
485
+ class zt {
486
+ constructor(e) {
487
+ this._isStarted = !1, this._isClosed = !1, this.targetSessionId = e, this._messageListener = Dt(
488
+ "mcp-server-to-client",
489
+ (r) => {
490
+ try {
491
+ if (r.sessionId !== this.targetSessionId) return;
492
+ const s = kt.parse(r.mcpMessage);
493
+ this.onmessage?.(s);
494
+ } catch (s) {
495
+ console.log("【Client Transport】处理server消息错误:", s);
496
+ }
497
+ },
498
+ "content->bg"
499
+ );
500
+ }
501
+ // 是否已关闭
502
+ _throwError(e, r) {
503
+ if (e()) {
504
+ const s = new Error(r);
505
+ throw console.log(r, s), this.onerror && this.onerror(s), s;
506
+ }
507
+ }
508
+ /** 启动 transport,开始监听消息 */
509
+ async start() {
510
+ this._throwError(() => this._isClosed, "【Client Transport】 未启动,无法重新启动"), this._isStarted = !0;
511
+ }
512
+ /** 发送消息到 MCP Server */
513
+ async send(e, r) {
514
+ this._throwError(() => !this._isStarted, "【Client Transport】 未启动,无法发送消息"), this._throwError(() => this._isClosed, "【Client Transport】 已关闭,无法发送消息");
515
+ let s;
516
+ if (chrome.sessionRegistry) {
517
+ const n = chrome.sessionRegistry.get(this.targetSessionId);
518
+ n && n.tabIds.length > 0 && (s = n.tabIds[n.tabIds.length - 1]);
519
+ }
520
+ s == null && (s = await chrome.runtime.sendMessage({ type: "get-session-tab-id", sessionId: this.targetSessionId })), this._throwError(() => s == null, `【Client Transport】后台未找到活动的tabId用于${this.targetSessionId}`), Zt(
521
+ "mcp-client-to-server",
522
+ { sessionId: this.targetSessionId, tabId: s, mcpMessage: e },
523
+ "bg->content"
524
+ );
525
+ }
526
+ /** 关闭 transport */
527
+ async close() {
528
+ if (!this._isClosed)
529
+ try {
530
+ this._isClosed = !0, this._isStarted = !1, this._messageListener && this._messageListener(), this.onclose && this.onclose();
531
+ } catch {
532
+ this._throwError(() => !0, "【Client Transport】 关闭时发生错误");
533
+ }
534
+ }
535
+ }
536
+ class Me extends Error {
537
+ constructor(e, r) {
538
+ super(e), this.name = "ParseError", this.type = r.type, this.field = r.field, this.value = r.value, this.line = r.line;
539
+ }
540
+ }
541
+ function ce(t) {
542
+ }
543
+ function Ft(t) {
544
+ if (typeof t == "function")
545
+ throw new TypeError(
546
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
547
+ );
548
+ const { onEvent: e = ce, onError: r = ce, onRetry: s = ce, onComment: n } = t;
549
+ let a = "", i = !0, u, l = "", c = "";
550
+ function p(h) {
551
+ const f = i ? h.replace(/^\xEF\xBB\xBF/, "") : h, [v, b] = Vt(`${a}${f}`);
552
+ for (const T of v)
553
+ g(T);
554
+ a = b, i = !1;
555
+ }
556
+ function g(h) {
557
+ if (h === "") {
558
+ m();
559
+ return;
560
+ }
561
+ if (h.startsWith(":")) {
562
+ n && n(h.slice(h.startsWith(": ") ? 2 : 1));
563
+ return;
564
+ }
565
+ const f = h.indexOf(":");
566
+ if (f !== -1) {
567
+ const v = h.slice(0, f), b = h[f + 1] === " " ? 2 : 1, T = h.slice(f + b);
568
+ d(v, T, h);
569
+ return;
570
+ }
571
+ d(h, "", h);
572
+ }
573
+ function d(h, f, v) {
574
+ switch (h) {
575
+ case "event":
576
+ c = f;
577
+ break;
578
+ case "data":
579
+ l = `${l}${f}
580
+ `;
581
+ break;
582
+ case "id":
583
+ u = f.includes("\0") ? void 0 : f;
584
+ break;
585
+ case "retry":
586
+ /^\d+$/.test(f) ? s(parseInt(f, 10)) : r(
587
+ new Me(`Invalid \`retry\` value: "${f}"`, {
588
+ type: "invalid-retry",
589
+ value: f,
590
+ line: v
591
+ })
592
+ );
593
+ break;
594
+ default:
595
+ r(
596
+ new Me(
597
+ `Unknown field "${h.length > 20 ? `${h.slice(0, 20)}…` : h}"`,
598
+ { type: "unknown-field", field: h, value: f, line: v }
599
+ )
600
+ );
601
+ break;
602
+ }
603
+ }
604
+ function m() {
605
+ l.length > 0 && e({
606
+ id: u,
607
+ event: c || void 0,
608
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
609
+ // then remove the last character from the data buffer.
610
+ data: l.endsWith(`
611
+ `) ? l.slice(0, -1) : l
612
+ }), u = void 0, l = "", c = "";
613
+ }
614
+ function y(h = {}) {
615
+ a && h.consume && g(a), i = !0, u = void 0, l = "", c = "", a = "";
616
+ }
617
+ return { feed: p, reset: y };
618
+ }
619
+ function Vt(t) {
620
+ const e = [];
621
+ let r = "", s = 0;
622
+ for (; s < t.length; ) {
623
+ const n = t.indexOf("\r", s), a = t.indexOf(`
624
+ `, s);
625
+ let i = -1;
626
+ if (n !== -1 && a !== -1 ? i = Math.min(n, a) : n !== -1 ? n === t.length - 1 ? i = -1 : i = n : a !== -1 && (i = a), i === -1) {
627
+ r = t.slice(s);
628
+ break;
629
+ } else {
630
+ const u = t.slice(s, i);
631
+ e.push(u), s = i + 1, t[s - 1] === "\r" && t[s] === `
632
+ ` && s++;
633
+ }
634
+ }
635
+ return [e, r];
636
+ }
637
+ class he extends TransformStream {
638
+ constructor({ onError: e, onRetry: r, onComment: s } = {}) {
639
+ let n;
640
+ super({
641
+ start(a) {
642
+ n = Ft({
643
+ onEvent: (i) => {
644
+ a.enqueue(i);
645
+ },
646
+ onError(i) {
647
+ e === "terminate" ? a.error(i) : typeof e == "function" && e(i);
648
+ },
649
+ onRetry: r,
650
+ onComment: s
651
+ });
652
+ },
653
+ transform(a) {
654
+ n.feed(a);
655
+ }
656
+ });
657
+ }
658
+ }
659
+ var Jt = ({
660
+ prefix: t,
661
+ size: e = 16,
662
+ alphabet: r = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
663
+ separator: s = "-"
664
+ } = {}) => {
665
+ const n = () => {
666
+ const a = r.length, i = new Array(e);
667
+ for (let u = 0; u < e; u++)
668
+ i[u] = r[Math.random() * a | 0];
669
+ return i.join("");
670
+ };
671
+ if (t == null)
672
+ return n;
673
+ if (r.includes(s))
674
+ throw new Lt({
675
+ argument: "separator",
676
+ message: `The separator "${s}" must not be part of the alphabet "${r}".`
677
+ });
678
+ return () => `${t}${s}${n()}`;
679
+ };
680
+ Jt();
681
+ function Ze(t = globalThis) {
682
+ var e, r, s;
683
+ return t.window ? "runtime/browser" : (e = t.navigator) != null && e.userAgent ? `runtime/${t.navigator.userAgent.toLowerCase()}` : (s = (r = t.process) == null ? void 0 : r.versions) != null && s.node ? `runtime/node.js/${t.process.version.substring(0)}` : t.EdgeRuntime ? "runtime/vercel-edge" : "runtime/unknown";
684
+ }
685
+ function Wt(t) {
686
+ if (t == null)
687
+ return {};
688
+ const e = {};
689
+ if (t instanceof Headers)
690
+ t.forEach((r, s) => {
691
+ e[s.toLowerCase()] = r;
692
+ });
693
+ else {
694
+ Array.isArray(t) || (t = Object.entries(t));
695
+ for (const [r, s] of t)
696
+ s != null && (e[r.toLowerCase()] = s);
697
+ }
698
+ return e;
699
+ }
700
+ function De(t, ...e) {
701
+ const r = new Headers(Wt(t)), s = r.get("user-agent") || "";
702
+ return r.set(
703
+ "user-agent",
704
+ [s, ...e].filter(Boolean).join(" ")
705
+ ), Object.fromEntries(r.entries());
706
+ }
707
+ var Bt = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/, Gt = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
708
+ function Ee(t) {
709
+ const e = JSON.parse(t);
710
+ return e === null || typeof e != "object" || Bt.test(t) === !1 && Gt.test(t) === !1 ? e : Kt(e);
711
+ }
712
+ function Kt(t) {
713
+ let e = [t];
714
+ for (; e.length; ) {
715
+ const r = e;
716
+ e = [];
717
+ for (const s of r) {
718
+ if (Object.prototype.hasOwnProperty.call(s, "__proto__"))
719
+ throw new SyntaxError("Object contains forbidden prototype property");
720
+ if (Object.prototype.hasOwnProperty.call(s, "constructor") && s.constructor !== null && typeof s.constructor == "object" && Object.prototype.hasOwnProperty.call(s.constructor, "prototype"))
721
+ throw new SyntaxError("Object contains forbidden prototype property");
722
+ for (const n in s) {
723
+ const a = s[n];
724
+ a && typeof a == "object" && e.push(a);
725
+ }
726
+ }
727
+ }
728
+ return t;
729
+ }
730
+ function Xt(t) {
731
+ const { stackTraceLimit: e } = Error;
732
+ try {
733
+ Error.stackTraceLimit = 0;
734
+ } catch {
735
+ return Ee(t);
736
+ }
737
+ try {
738
+ return Ee(t);
739
+ } finally {
740
+ Error.stackTraceLimit = e;
741
+ }
742
+ }
743
+ function ve(t) {
744
+ if (t.type === "object" || Array.isArray(t.type) && t.type.includes("object")) {
745
+ t.additionalProperties = !1;
746
+ const { properties: r } = t;
747
+ if (r != null)
748
+ for (const s of Object.keys(r))
749
+ r[s] = q(r[s]);
750
+ }
751
+ t.items != null && (t.items = Array.isArray(t.items) ? t.items.map(q) : q(t.items)), t.anyOf != null && (t.anyOf = t.anyOf.map(q)), t.allOf != null && (t.allOf = t.allOf.map(q)), t.oneOf != null && (t.oneOf = t.oneOf.map(q));
752
+ const { definitions: e } = t;
753
+ if (e != null)
754
+ for (const r of Object.keys(e))
755
+ e[r] = q(e[r]);
756
+ return t;
757
+ }
758
+ function q(t) {
759
+ return typeof t == "boolean" ? t : ve(t);
760
+ }
761
+ var Qt = /* @__PURE__ */ Symbol(
762
+ "Let zodToJsonSchema decide on which parser to use"
763
+ ), Ae = {
764
+ name: void 0,
765
+ $refStrategy: "root",
766
+ basePath: ["#"],
767
+ effectStrategy: "input",
768
+ pipeStrategy: "all",
769
+ dateStrategy: "format:date-time",
770
+ mapStrategy: "entries",
771
+ removeAdditionalStrategy: "passthrough",
772
+ allowedAdditionalProperties: !0,
773
+ rejectedAdditionalProperties: !1,
774
+ definitionPath: "definitions",
775
+ strictUnions: !1,
776
+ definitions: {},
777
+ errorMessages: !1,
778
+ patternStrategy: "escape",
779
+ applyRegexFlags: !1,
780
+ emailStrategy: "format:email",
781
+ base64Strategy: "contentEncoding:base64",
782
+ nameStrategy: "ref"
783
+ }, Yt = (t) => typeof t == "string" ? {
784
+ ...Ae,
785
+ name: t
786
+ } : {
787
+ ...Ae,
788
+ ...t
789
+ };
790
+ function E() {
791
+ return {};
792
+ }
793
+ function er(t, e) {
794
+ var r, s, n;
795
+ const a = {
796
+ type: "array"
797
+ };
798
+ return (r = t.type) != null && r._def && ((n = (s = t.type) == null ? void 0 : s._def) == null ? void 0 : n.typeName) !== w.ZodAny && (a.items = S(t.type._def, {
799
+ ...e,
800
+ currentPath: [...e.currentPath, "items"]
801
+ })), t.minLength && (a.minItems = t.minLength.value), t.maxLength && (a.maxItems = t.maxLength.value), t.exactLength && (a.minItems = t.exactLength.value, a.maxItems = t.exactLength.value), a;
802
+ }
803
+ function tr(t) {
804
+ const e = {
805
+ type: "integer",
806
+ format: "int64"
807
+ };
808
+ if (!t.checks) return e;
809
+ for (const r of t.checks)
810
+ switch (r.kind) {
811
+ case "min":
812
+ r.inclusive ? e.minimum = r.value : e.exclusiveMinimum = r.value;
813
+ break;
814
+ case "max":
815
+ r.inclusive ? e.maximum = r.value : e.exclusiveMaximum = r.value;
816
+ break;
817
+ case "multipleOf":
818
+ e.multipleOf = r.value;
819
+ break;
820
+ }
821
+ return e;
822
+ }
823
+ function rr() {
824
+ return { type: "boolean" };
825
+ }
826
+ function ze(t, e) {
827
+ return S(t.type._def, e);
828
+ }
829
+ var sr = (t, e) => S(t.innerType._def, e);
830
+ function Fe(t, e, r) {
831
+ const s = r ?? e.dateStrategy;
832
+ if (Array.isArray(s))
833
+ return {
834
+ anyOf: s.map((n, a) => Fe(t, e, n))
835
+ };
836
+ switch (s) {
837
+ case "string":
838
+ case "format:date-time":
839
+ return {
840
+ type: "string",
841
+ format: "date-time"
842
+ };
843
+ case "format:date":
844
+ return {
845
+ type: "string",
846
+ format: "date"
847
+ };
848
+ case "integer":
849
+ return nr(t);
850
+ }
851
+ }
852
+ var nr = (t) => {
853
+ const e = {
854
+ type: "integer",
855
+ format: "unix-time"
856
+ };
857
+ for (const r of t.checks)
858
+ switch (r.kind) {
859
+ case "min":
860
+ e.minimum = r.value;
861
+ break;
862
+ case "max":
863
+ e.maximum = r.value;
864
+ break;
865
+ }
866
+ return e;
867
+ };
868
+ function or(t, e) {
869
+ return {
870
+ ...S(t.innerType._def, e),
871
+ default: t.defaultValue()
872
+ };
873
+ }
874
+ function ar(t, e) {
875
+ return e.effectStrategy === "input" ? S(t.schema._def, e) : E();
876
+ }
877
+ function ir(t) {
878
+ return {
879
+ type: "string",
880
+ enum: Array.from(t.values)
881
+ };
882
+ }
883
+ var cr = (t) => "type" in t && t.type === "string" ? !1 : "allOf" in t;
884
+ function lr(t, e) {
885
+ const r = [
886
+ S(t.left._def, {
887
+ ...e,
888
+ currentPath: [...e.currentPath, "allOf", "0"]
889
+ }),
890
+ S(t.right._def, {
891
+ ...e,
892
+ currentPath: [...e.currentPath, "allOf", "1"]
893
+ })
894
+ ].filter((n) => !!n), s = [];
895
+ return r.forEach((n) => {
896
+ if (cr(n))
897
+ s.push(...n.allOf);
898
+ else {
899
+ let a = n;
900
+ if ("additionalProperties" in n && n.additionalProperties === !1) {
901
+ const { additionalProperties: i, ...u } = n;
902
+ a = u;
903
+ }
904
+ s.push(a);
905
+ }
906
+ }), s.length ? { allOf: s } : void 0;
907
+ }
908
+ function ur(t) {
909
+ const e = typeof t.value;
910
+ return e !== "bigint" && e !== "number" && e !== "boolean" && e !== "string" ? {
911
+ type: Array.isArray(t.value) ? "array" : "object"
912
+ } : {
913
+ type: e === "bigint" ? "integer" : e,
914
+ const: t.value
915
+ };
916
+ }
917
+ var le = void 0, L = {
918
+ /**
919
+ * `c` was changed to `[cC]` to replicate /i flag
920
+ */
921
+ cuid: /^[cC][^\s-]{8,}$/,
922
+ cuid2: /^[0-9a-z]+$/,
923
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
924
+ /**
925
+ * `a-z` was added to replicate /i flag
926
+ */
927
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
928
+ /**
929
+ * Constructed a valid Unicode RegExp
930
+ *
931
+ * Lazily instantiate since this type of regex isn't supported
932
+ * in all envs (e.g. React Native).
933
+ *
934
+ * See:
935
+ * https://github.com/colinhacks/zod/issues/2433
936
+ * Fix in Zod:
937
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
938
+ */
939
+ emoji: () => (le === void 0 && (le = RegExp(
940
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
941
+ "u"
942
+ )), le),
943
+ /**
944
+ * Unused
945
+ */
946
+ 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}$/,
947
+ /**
948
+ * Unused
949
+ */
950
+ 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])$/,
951
+ 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])$/,
952
+ /**
953
+ * Unused
954
+ */
955
+ 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})))$/,
956
+ 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])$/,
957
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
958
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
959
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
960
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
961
+ };
962
+ function Ve(t, e) {
963
+ const r = {
964
+ type: "string"
965
+ };
966
+ if (t.checks)
967
+ for (const s of t.checks)
968
+ switch (s.kind) {
969
+ case "min":
970
+ r.minLength = typeof r.minLength == "number" ? Math.max(r.minLength, s.value) : s.value;
971
+ break;
972
+ case "max":
973
+ r.maxLength = typeof r.maxLength == "number" ? Math.min(r.maxLength, s.value) : s.value;
974
+ break;
975
+ case "email":
976
+ switch (e.emailStrategy) {
977
+ case "format:email":
978
+ U(r, "email", s.message, e);
979
+ break;
980
+ case "format:idn-email":
981
+ U(r, "idn-email", s.message, e);
982
+ break;
983
+ case "pattern:zod":
984
+ C(r, L.email, s.message, e);
985
+ break;
986
+ }
987
+ break;
988
+ case "url":
989
+ U(r, "uri", s.message, e);
990
+ break;
991
+ case "uuid":
992
+ U(r, "uuid", s.message, e);
993
+ break;
994
+ case "regex":
995
+ C(r, s.regex, s.message, e);
996
+ break;
997
+ case "cuid":
998
+ C(r, L.cuid, s.message, e);
999
+ break;
1000
+ case "cuid2":
1001
+ C(r, L.cuid2, s.message, e);
1002
+ break;
1003
+ case "startsWith":
1004
+ C(
1005
+ r,
1006
+ RegExp(`^${ue(s.value, e)}`),
1007
+ s.message,
1008
+ e
1009
+ );
1010
+ break;
1011
+ case "endsWith":
1012
+ C(
1013
+ r,
1014
+ RegExp(`${ue(s.value, e)}$`),
1015
+ s.message,
1016
+ e
1017
+ );
1018
+ break;
1019
+ case "datetime":
1020
+ U(r, "date-time", s.message, e);
1021
+ break;
1022
+ case "date":
1023
+ U(r, "date", s.message, e);
1024
+ break;
1025
+ case "time":
1026
+ U(r, "time", s.message, e);
1027
+ break;
1028
+ case "duration":
1029
+ U(r, "duration", s.message, e);
1030
+ break;
1031
+ case "length":
1032
+ r.minLength = typeof r.minLength == "number" ? Math.max(r.minLength, s.value) : s.value, r.maxLength = typeof r.maxLength == "number" ? Math.min(r.maxLength, s.value) : s.value;
1033
+ break;
1034
+ case "includes": {
1035
+ C(
1036
+ r,
1037
+ RegExp(ue(s.value, e)),
1038
+ s.message,
1039
+ e
1040
+ );
1041
+ break;
1042
+ }
1043
+ case "ip": {
1044
+ s.version !== "v6" && U(r, "ipv4", s.message, e), s.version !== "v4" && U(r, "ipv6", s.message, e);
1045
+ break;
1046
+ }
1047
+ case "base64url":
1048
+ C(r, L.base64url, s.message, e);
1049
+ break;
1050
+ case "jwt":
1051
+ C(r, L.jwt, s.message, e);
1052
+ break;
1053
+ case "cidr": {
1054
+ s.version !== "v6" && C(r, L.ipv4Cidr, s.message, e), s.version !== "v4" && C(r, L.ipv6Cidr, s.message, e);
1055
+ break;
1056
+ }
1057
+ case "emoji":
1058
+ C(r, L.emoji(), s.message, e);
1059
+ break;
1060
+ case "ulid": {
1061
+ C(r, L.ulid, s.message, e);
1062
+ break;
1063
+ }
1064
+ case "base64": {
1065
+ switch (e.base64Strategy) {
1066
+ case "format:binary": {
1067
+ U(r, "binary", s.message, e);
1068
+ break;
1069
+ }
1070
+ case "contentEncoding:base64": {
1071
+ r.contentEncoding = "base64";
1072
+ break;
1073
+ }
1074
+ case "pattern:zod": {
1075
+ C(r, L.base64, s.message, e);
1076
+ break;
1077
+ }
1078
+ }
1079
+ break;
1080
+ }
1081
+ case "nanoid":
1082
+ C(r, L.nanoid, s.message, e);
1083
+ }
1084
+ return r;
1085
+ }
1086
+ function ue(t, e) {
1087
+ return e.patternStrategy === "escape" ? pr(t) : t;
1088
+ }
1089
+ var dr = new Set(
1090
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1091
+ );
1092
+ function pr(t) {
1093
+ let e = "";
1094
+ for (let r = 0; r < t.length; r++)
1095
+ dr.has(t[r]) || (e += "\\"), e += t[r];
1096
+ return e;
1097
+ }
1098
+ function U(t, e, r, s) {
1099
+ var n;
1100
+ t.format || (n = t.anyOf) != null && n.some((a) => a.format) ? (t.anyOf || (t.anyOf = []), t.format && (t.anyOf.push({
1101
+ format: t.format
1102
+ }), delete t.format), t.anyOf.push({
1103
+ format: e,
1104
+ ...r && s.errorMessages && { errorMessage: { format: r } }
1105
+ })) : t.format = e;
1106
+ }
1107
+ function C(t, e, r, s) {
1108
+ var n;
1109
+ t.pattern || (n = t.allOf) != null && n.some((a) => a.pattern) ? (t.allOf || (t.allOf = []), t.pattern && (t.allOf.push({
1110
+ pattern: t.pattern
1111
+ }), delete t.pattern), t.allOf.push({
1112
+ pattern: ke(e, s),
1113
+ ...r && s.errorMessages && { errorMessage: { pattern: r } }
1114
+ })) : t.pattern = ke(e, s);
1115
+ }
1116
+ function ke(t, e) {
1117
+ var r;
1118
+ if (!e.applyRegexFlags || !t.flags)
1119
+ return t.source;
1120
+ const s = {
1121
+ i: t.flags.includes("i"),
1122
+ // Case-insensitive
1123
+ m: t.flags.includes("m"),
1124
+ // `^` and `$` matches adjacent to newline characters
1125
+ s: t.flags.includes("s")
1126
+ // `.` matches newlines
1127
+ }, n = s.i ? t.source.toLowerCase() : t.source;
1128
+ let a = "", i = !1, u = !1, l = !1;
1129
+ for (let c = 0; c < n.length; c++) {
1130
+ if (i) {
1131
+ a += n[c], i = !1;
1132
+ continue;
1133
+ }
1134
+ if (s.i) {
1135
+ if (u) {
1136
+ if (n[c].match(/[a-z]/)) {
1137
+ l ? (a += n[c], a += `${n[c - 2]}-${n[c]}`.toUpperCase(), l = !1) : n[c + 1] === "-" && ((r = n[c + 2]) != null && r.match(/[a-z]/)) ? (a += n[c], l = !0) : a += `${n[c]}${n[c].toUpperCase()}`;
1138
+ continue;
1139
+ }
1140
+ } else if (n[c].match(/[a-z]/)) {
1141
+ a += `[${n[c]}${n[c].toUpperCase()}]`;
1142
+ continue;
1143
+ }
1144
+ }
1145
+ if (s.m) {
1146
+ if (n[c] === "^") {
1147
+ a += `(^|(?<=[\r
1148
+ ]))`;
1149
+ continue;
1150
+ } else if (n[c] === "$") {
1151
+ a += `($|(?=[\r
1152
+ ]))`;
1153
+ continue;
1154
+ }
1155
+ }
1156
+ if (s.s && n[c] === ".") {
1157
+ a += u ? `${n[c]}\r
1158
+ ` : `[${n[c]}\r
1159
+ ]`;
1160
+ continue;
1161
+ }
1162
+ a += n[c], n[c] === "\\" ? i = !0 : u && n[c] === "]" ? u = !1 : !u && n[c] === "[" && (u = !0);
1163
+ }
1164
+ try {
1165
+ new RegExp(a);
1166
+ } catch {
1167
+ return console.warn(
1168
+ `Could not convert regex pattern at ${e.currentPath.join(
1169
+ "/"
1170
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
1171
+ ), t.source;
1172
+ }
1173
+ return a;
1174
+ }
1175
+ function Je(t, e) {
1176
+ var r, s, n, a, i, u;
1177
+ const l = {
1178
+ type: "object",
1179
+ additionalProperties: (r = S(t.valueType._def, {
1180
+ ...e,
1181
+ currentPath: [...e.currentPath, "additionalProperties"]
1182
+ })) != null ? r : e.allowedAdditionalProperties
1183
+ };
1184
+ if (((s = t.keyType) == null ? void 0 : s._def.typeName) === w.ZodString && ((n = t.keyType._def.checks) != null && n.length)) {
1185
+ const { type: c, ...p } = Ve(t.keyType._def, e);
1186
+ return {
1187
+ ...l,
1188
+ propertyNames: p
1189
+ };
1190
+ } else {
1191
+ if (((a = t.keyType) == null ? void 0 : a._def.typeName) === w.ZodEnum)
1192
+ return {
1193
+ ...l,
1194
+ propertyNames: {
1195
+ enum: t.keyType._def.values
1196
+ }
1197
+ };
1198
+ if (((i = t.keyType) == null ? void 0 : i._def.typeName) === w.ZodBranded && t.keyType._def.type._def.typeName === w.ZodString && ((u = t.keyType._def.type._def.checks) != null && u.length)) {
1199
+ const { type: c, ...p } = ze(
1200
+ t.keyType._def,
1201
+ e
1202
+ );
1203
+ return {
1204
+ ...l,
1205
+ propertyNames: p
1206
+ };
1207
+ }
1208
+ }
1209
+ return l;
1210
+ }
1211
+ function hr(t, e) {
1212
+ if (e.mapStrategy === "record")
1213
+ return Je(t, e);
1214
+ const r = S(t.keyType._def, {
1215
+ ...e,
1216
+ currentPath: [...e.currentPath, "items", "items", "0"]
1217
+ }) || E(), s = S(t.valueType._def, {
1218
+ ...e,
1219
+ currentPath: [...e.currentPath, "items", "items", "1"]
1220
+ }) || E();
1221
+ return {
1222
+ type: "array",
1223
+ maxItems: 125,
1224
+ items: {
1225
+ type: "array",
1226
+ items: [r, s],
1227
+ minItems: 2,
1228
+ maxItems: 2
1229
+ }
1230
+ };
1231
+ }
1232
+ function mr(t) {
1233
+ const e = t.values, s = Object.keys(t.values).filter((a) => typeof e[e[a]] != "number").map((a) => e[a]), n = Array.from(
1234
+ new Set(s.map((a) => typeof a))
1235
+ );
1236
+ return {
1237
+ type: n.length === 1 ? n[0] === "string" ? "string" : "number" : ["string", "number"],
1238
+ enum: s
1239
+ };
1240
+ }
1241
+ function fr() {
1242
+ return { not: E() };
1243
+ }
1244
+ function gr() {
1245
+ return {
1246
+ type: "null"
1247
+ };
1248
+ }
1249
+ var me = {
1250
+ ZodString: "string",
1251
+ ZodNumber: "number",
1252
+ ZodBigInt: "integer",
1253
+ ZodBoolean: "boolean",
1254
+ ZodNull: "null"
1255
+ };
1256
+ function yr(t, e) {
1257
+ const r = t.options instanceof Map ? Array.from(t.options.values()) : t.options;
1258
+ if (r.every(
1259
+ (s) => s._def.typeName in me && (!s._def.checks || !s._def.checks.length)
1260
+ )) {
1261
+ const s = r.reduce((n, a) => {
1262
+ const i = me[a._def.typeName];
1263
+ return i && !n.includes(i) ? [...n, i] : n;
1264
+ }, []);
1265
+ return {
1266
+ type: s.length > 1 ? s : s[0]
1267
+ };
1268
+ } else if (r.every((s) => s._def.typeName === "ZodLiteral" && !s.description)) {
1269
+ const s = r.reduce(
1270
+ (n, a) => {
1271
+ const i = typeof a._def.value;
1272
+ switch (i) {
1273
+ case "string":
1274
+ case "number":
1275
+ case "boolean":
1276
+ return [...n, i];
1277
+ case "bigint":
1278
+ return [...n, "integer"];
1279
+ case "object":
1280
+ if (a._def.value === null) return [...n, "null"];
1281
+ case "symbol":
1282
+ case "undefined":
1283
+ case "function":
1284
+ default:
1285
+ return n;
1286
+ }
1287
+ },
1288
+ []
1289
+ );
1290
+ if (s.length === r.length) {
1291
+ const n = s.filter((a, i, u) => u.indexOf(a) === i);
1292
+ return {
1293
+ type: n.length > 1 ? n : n[0],
1294
+ enum: r.reduce(
1295
+ (a, i) => a.includes(i._def.value) ? a : [...a, i._def.value],
1296
+ []
1297
+ )
1298
+ };
1299
+ }
1300
+ } else if (r.every((s) => s._def.typeName === "ZodEnum"))
1301
+ return {
1302
+ type: "string",
1303
+ enum: r.reduce(
1304
+ (s, n) => [
1305
+ ...s,
1306
+ ...n._def.values.filter((a) => !s.includes(a))
1307
+ ],
1308
+ []
1309
+ )
1310
+ };
1311
+ return vr(t, e);
1312
+ }
1313
+ var vr = (t, e) => {
1314
+ const r = (t.options instanceof Map ? Array.from(t.options.values()) : t.options).map(
1315
+ (s, n) => S(s._def, {
1316
+ ...e,
1317
+ currentPath: [...e.currentPath, "anyOf", `${n}`]
1318
+ })
1319
+ ).filter(
1320
+ (s) => !!s && (!e.strictUnions || typeof s == "object" && Object.keys(s).length > 0)
1321
+ );
1322
+ return r.length ? { anyOf: r } : void 0;
1323
+ };
1324
+ function wr(t, e) {
1325
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1326
+ t.innerType._def.typeName
1327
+ ) && (!t.innerType._def.checks || !t.innerType._def.checks.length))
1328
+ return {
1329
+ type: [
1330
+ me[t.innerType._def.typeName],
1331
+ "null"
1332
+ ]
1333
+ };
1334
+ const r = S(t.innerType._def, {
1335
+ ...e,
1336
+ currentPath: [...e.currentPath, "anyOf", "0"]
1337
+ });
1338
+ return r && { anyOf: [r, { type: "null" }] };
1339
+ }
1340
+ function _r(t) {
1341
+ const e = {
1342
+ type: "number"
1343
+ };
1344
+ if (!t.checks) return e;
1345
+ for (const r of t.checks)
1346
+ switch (r.kind) {
1347
+ case "int":
1348
+ e.type = "integer";
1349
+ break;
1350
+ case "min":
1351
+ r.inclusive ? e.minimum = r.value : e.exclusiveMinimum = r.value;
1352
+ break;
1353
+ case "max":
1354
+ r.inclusive ? e.maximum = r.value : e.exclusiveMaximum = r.value;
1355
+ break;
1356
+ case "multipleOf":
1357
+ e.multipleOf = r.value;
1358
+ break;
1359
+ }
1360
+ return e;
1361
+ }
1362
+ function br(t, e) {
1363
+ const r = {
1364
+ type: "object",
1365
+ properties: {}
1366
+ }, s = [], n = t.shape();
1367
+ for (const i in n) {
1368
+ let u = n[i];
1369
+ if (u === void 0 || u._def === void 0)
1370
+ continue;
1371
+ const l = Tr(u), c = S(u._def, {
1372
+ ...e,
1373
+ currentPath: [...e.currentPath, "properties", i],
1374
+ propertyPath: [...e.currentPath, "properties", i]
1375
+ });
1376
+ c !== void 0 && (r.properties[i] = c, l || s.push(i));
1377
+ }
1378
+ s.length && (r.required = s);
1379
+ const a = Sr(t, e);
1380
+ return a !== void 0 && (r.additionalProperties = a), r;
1381
+ }
1382
+ function Sr(t, e) {
1383
+ if (t.catchall._def.typeName !== "ZodNever")
1384
+ return S(t.catchall._def, {
1385
+ ...e,
1386
+ currentPath: [...e.currentPath, "additionalProperties"]
1387
+ });
1388
+ switch (t.unknownKeys) {
1389
+ case "passthrough":
1390
+ return e.allowedAdditionalProperties;
1391
+ case "strict":
1392
+ return e.rejectedAdditionalProperties;
1393
+ case "strip":
1394
+ return e.removeAdditionalStrategy === "strict" ? e.allowedAdditionalProperties : e.rejectedAdditionalProperties;
1395
+ }
1396
+ }
1397
+ function Tr(t) {
1398
+ try {
1399
+ return t.isOptional();
1400
+ } catch {
1401
+ return !0;
1402
+ }
1403
+ }
1404
+ var Pr = (t, e) => {
1405
+ var r;
1406
+ if (e.currentPath.toString() === ((r = e.propertyPath) == null ? void 0 : r.toString()))
1407
+ return S(t.innerType._def, e);
1408
+ const s = S(t.innerType._def, {
1409
+ ...e,
1410
+ currentPath: [...e.currentPath, "anyOf", "1"]
1411
+ });
1412
+ return s ? { anyOf: [{ not: E() }, s] } : E();
1413
+ }, Cr = (t, e) => {
1414
+ if (e.pipeStrategy === "input")
1415
+ return S(t.in._def, e);
1416
+ if (e.pipeStrategy === "output")
1417
+ return S(t.out._def, e);
1418
+ const r = S(t.in._def, {
1419
+ ...e,
1420
+ currentPath: [...e.currentPath, "allOf", "0"]
1421
+ }), s = S(t.out._def, {
1422
+ ...e,
1423
+ currentPath: [...e.currentPath, "allOf", r ? "1" : "0"]
1424
+ });
1425
+ return {
1426
+ allOf: [r, s].filter((n) => n !== void 0)
1427
+ };
1428
+ };
1429
+ function Rr(t, e) {
1430
+ return S(t.type._def, e);
1431
+ }
1432
+ function Mr(t, e) {
1433
+ const s = {
1434
+ type: "array",
1435
+ uniqueItems: !0,
1436
+ items: S(t.valueType._def, {
1437
+ ...e,
1438
+ currentPath: [...e.currentPath, "items"]
1439
+ })
1440
+ };
1441
+ return t.minSize && (s.minItems = t.minSize.value), t.maxSize && (s.maxItems = t.maxSize.value), s;
1442
+ }
1443
+ function Er(t, e) {
1444
+ return t.rest ? {
1445
+ type: "array",
1446
+ minItems: t.items.length,
1447
+ items: t.items.map(
1448
+ (r, s) => S(r._def, {
1449
+ ...e,
1450
+ currentPath: [...e.currentPath, "items", `${s}`]
1451
+ })
1452
+ ).reduce(
1453
+ (r, s) => s === void 0 ? r : [...r, s],
1454
+ []
1455
+ ),
1456
+ additionalItems: S(t.rest._def, {
1457
+ ...e,
1458
+ currentPath: [...e.currentPath, "additionalItems"]
1459
+ })
1460
+ } : {
1461
+ type: "array",
1462
+ minItems: t.items.length,
1463
+ maxItems: t.items.length,
1464
+ items: t.items.map(
1465
+ (r, s) => S(r._def, {
1466
+ ...e,
1467
+ currentPath: [...e.currentPath, "items", `${s}`]
1468
+ })
1469
+ ).reduce(
1470
+ (r, s) => s === void 0 ? r : [...r, s],
1471
+ []
1472
+ )
1473
+ };
1474
+ }
1475
+ function Ar() {
1476
+ return {
1477
+ not: E()
1478
+ };
1479
+ }
1480
+ function kr() {
1481
+ return E();
1482
+ }
1483
+ var Or = (t, e) => S(t.innerType._def, e), Ir = (t, e, r) => {
1484
+ switch (e) {
1485
+ case w.ZodString:
1486
+ return Ve(t, r);
1487
+ case w.ZodNumber:
1488
+ return _r(t);
1489
+ case w.ZodObject:
1490
+ return br(t, r);
1491
+ case w.ZodBigInt:
1492
+ return tr(t);
1493
+ case w.ZodBoolean:
1494
+ return rr();
1495
+ case w.ZodDate:
1496
+ return Fe(t, r);
1497
+ case w.ZodUndefined:
1498
+ return Ar();
1499
+ case w.ZodNull:
1500
+ return gr();
1501
+ case w.ZodArray:
1502
+ return er(t, r);
1503
+ case w.ZodUnion:
1504
+ case w.ZodDiscriminatedUnion:
1505
+ return yr(t, r);
1506
+ case w.ZodIntersection:
1507
+ return lr(t, r);
1508
+ case w.ZodTuple:
1509
+ return Er(t, r);
1510
+ case w.ZodRecord:
1511
+ return Je(t, r);
1512
+ case w.ZodLiteral:
1513
+ return ur(t);
1514
+ case w.ZodEnum:
1515
+ return ir(t);
1516
+ case w.ZodNativeEnum:
1517
+ return mr(t);
1518
+ case w.ZodNullable:
1519
+ return wr(t, r);
1520
+ case w.ZodOptional:
1521
+ return Pr(t, r);
1522
+ case w.ZodMap:
1523
+ return hr(t, r);
1524
+ case w.ZodSet:
1525
+ return Mr(t, r);
1526
+ case w.ZodLazy:
1527
+ return () => t.getter()._def;
1528
+ case w.ZodPromise:
1529
+ return Rr(t, r);
1530
+ case w.ZodNaN:
1531
+ case w.ZodNever:
1532
+ return fr();
1533
+ case w.ZodEffects:
1534
+ return ar(t, r);
1535
+ case w.ZodAny:
1536
+ return E();
1537
+ case w.ZodUnknown:
1538
+ return kr();
1539
+ case w.ZodDefault:
1540
+ return or(t, r);
1541
+ case w.ZodBranded:
1542
+ return ze(t, r);
1543
+ case w.ZodReadonly:
1544
+ return Or(t, r);
1545
+ case w.ZodCatch:
1546
+ return sr(t, r);
1547
+ case w.ZodPipeline:
1548
+ return Cr(t, r);
1549
+ case w.ZodFunction:
1550
+ case w.ZodVoid:
1551
+ case w.ZodSymbol:
1552
+ return;
1553
+ default:
1554
+ return /* @__PURE__ */ ((s) => {
1555
+ })();
1556
+ }
1557
+ }, xr = (t, e) => {
1558
+ let r = 0;
1559
+ for (; r < t.length && r < e.length && t[r] === e[r]; r++)
1560
+ ;
1561
+ return [(t.length - r).toString(), ...e.slice(r)].join("/");
1562
+ };
1563
+ function S(t, e, r = !1) {
1564
+ var s;
1565
+ const n = e.seen.get(t);
1566
+ if (e.override) {
1567
+ const l = (s = e.override) == null ? void 0 : s.call(
1568
+ e,
1569
+ t,
1570
+ e,
1571
+ n,
1572
+ r
1573
+ );
1574
+ if (l !== Qt)
1575
+ return l;
1576
+ }
1577
+ if (n && !r) {
1578
+ const l = Lr(n, e);
1579
+ if (l !== void 0)
1580
+ return l;
1581
+ }
1582
+ const a = { def: t, path: e.currentPath, jsonSchema: void 0 };
1583
+ e.seen.set(t, a);
1584
+ const i = Ir(t, t.typeName, e), u = typeof i == "function" ? S(i(), e) : i;
1585
+ if (u && Ur(t, e, u), e.postProcess) {
1586
+ const l = e.postProcess(u, t, e);
1587
+ return a.jsonSchema = u, l;
1588
+ }
1589
+ return a.jsonSchema = u, u;
1590
+ }
1591
+ var Lr = (t, e) => {
1592
+ switch (e.$refStrategy) {
1593
+ case "root":
1594
+ return { $ref: t.path.join("/") };
1595
+ case "relative":
1596
+ return { $ref: xr(e.currentPath, t.path) };
1597
+ case "none":
1598
+ case "seen":
1599
+ return t.path.length < e.currentPath.length && t.path.every((r, s) => e.currentPath[s] === r) ? (console.warn(
1600
+ `Recursive reference detected at ${e.currentPath.join(
1601
+ "/"
1602
+ )}! Defaulting to any`
1603
+ ), E()) : e.$refStrategy === "seen" ? E() : void 0;
1604
+ }
1605
+ }, Ur = (t, e, r) => (t.description && (r.description = t.description), r), $r = (t) => {
1606
+ const e = Yt(t), r = e.name !== void 0 ? [...e.basePath, e.definitionPath, e.name] : e.basePath;
1607
+ return {
1608
+ ...e,
1609
+ currentPath: r,
1610
+ propertyPath: void 0,
1611
+ seen: new Map(
1612
+ Object.entries(e.definitions).map(([s, n]) => [
1613
+ n._def,
1614
+ {
1615
+ def: n._def,
1616
+ path: [...e.basePath, e.definitionPath, s],
1617
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1618
+ jsonSchema: void 0
1619
+ }
1620
+ ])
1621
+ )
1622
+ };
1623
+ }, jr = (t, e) => {
1624
+ var r;
1625
+ const s = $r(e);
1626
+ let n = typeof e == "object" && e.definitions ? Object.entries(e.definitions).reduce(
1627
+ (c, [p, g]) => {
1628
+ var d;
1629
+ return {
1630
+ ...c,
1631
+ [p]: (d = S(
1632
+ g._def,
1633
+ {
1634
+ ...s,
1635
+ currentPath: [...s.basePath, s.definitionPath, p]
1636
+ },
1637
+ !0
1638
+ )) != null ? d : E()
1639
+ };
1640
+ },
1641
+ {}
1642
+ ) : void 0;
1643
+ const a = typeof e == "string" ? e : e?.nameStrategy === "title" ? void 0 : e?.name, i = (r = S(
1644
+ t._def,
1645
+ a === void 0 ? s : {
1646
+ ...s,
1647
+ currentPath: [...s.basePath, s.definitionPath, a]
1648
+ },
1649
+ !1
1650
+ )) != null ? r : E(), u = typeof e == "object" && e.name !== void 0 && e.nameStrategy === "title" ? e.name : void 0;
1651
+ u !== void 0 && (i.title = u);
1652
+ const l = a === void 0 ? n ? {
1653
+ ...i,
1654
+ [s.definitionPath]: n
1655
+ } : i : {
1656
+ $ref: [
1657
+ ...s.$refStrategy === "relative" ? [] : s.basePath,
1658
+ s.definitionPath,
1659
+ a
1660
+ ].join("/"),
1661
+ [s.definitionPath]: {
1662
+ ...n,
1663
+ [a]: i
1664
+ }
1665
+ };
1666
+ return l.$schema = "http://json-schema.org/draft-07/schema#", l;
1667
+ }, fe = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
1668
+ function J(t, {
1669
+ validate: e
1670
+ } = {}) {
1671
+ return {
1672
+ [fe]: !0,
1673
+ _type: void 0,
1674
+ // should never be used directly
1675
+ get jsonSchema() {
1676
+ return typeof t == "function" && (t = t()), t;
1677
+ },
1678
+ validate: e
1679
+ };
1680
+ }
1681
+ function Nr(t) {
1682
+ return typeof t == "object" && t !== null && fe in t && t[fe] === !0 && "jsonSchema" in t && "validate" in t;
1683
+ }
1684
+ function We(t) {
1685
+ return t == null ? J({ properties: {}, additionalProperties: !1 }) : Nr(t) ? t : "~standard" in t ? t["~standard"].vendor === "zod" ? zr(t) : qr(t) : t();
1686
+ }
1687
+ function qr(t) {
1688
+ return J(
1689
+ () => ve(
1690
+ t["~standard"].jsonSchema.input({
1691
+ target: "draft-07"
1692
+ })
1693
+ ),
1694
+ {
1695
+ validate: async (e) => {
1696
+ const r = await t["~standard"].validate(e);
1697
+ return "value" in r ? { success: !0, value: r.value } : {
1698
+ success: !1,
1699
+ error: new pe({
1700
+ value: e,
1701
+ cause: r.issues
1702
+ })
1703
+ };
1704
+ }
1705
+ }
1706
+ );
1707
+ }
1708
+ function Hr(t, e) {
1709
+ var r;
1710
+ const s = (r = void 0) != null ? r : !1;
1711
+ return J(
1712
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1713
+ () => jr(t, {
1714
+ $refStrategy: s ? "root" : "none"
1715
+ }),
1716
+ {
1717
+ validate: async (n) => {
1718
+ const a = await t.safeParseAsync(n);
1719
+ return a.success ? { success: !0, value: a.data } : { success: !1, error: a.error };
1720
+ }
1721
+ }
1722
+ );
1723
+ }
1724
+ function Zr(t, e) {
1725
+ var r;
1726
+ const s = (r = void 0) != null ? r : !1;
1727
+ return J(
1728
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1729
+ () => ve(
1730
+ Re.toJSONSchema(t, {
1731
+ target: "draft-7",
1732
+ io: "input",
1733
+ reused: s ? "ref" : "inline"
1734
+ })
1735
+ ),
1736
+ {
1737
+ validate: async (n) => {
1738
+ const a = await Re.safeParseAsync(t, n);
1739
+ return a.success ? { success: !0, value: a.data } : { success: !1, error: a.error };
1740
+ }
1741
+ }
1742
+ );
1743
+ }
1744
+ function Dr(t) {
1745
+ return "_zod" in t;
1746
+ }
1747
+ function zr(t, e) {
1748
+ return Dr(t) ? Zr(t) : Hr(t);
1749
+ }
1750
+ async function Be({
1751
+ value: t,
1752
+ schema: e,
1753
+ context: r
1754
+ }) {
1755
+ const s = We(e);
1756
+ try {
1757
+ if (s.validate == null)
1758
+ return { success: !0, value: t, rawValue: t };
1759
+ const n = await s.validate(t);
1760
+ return n.success ? { success: !0, value: n.value, rawValue: t } : {
1761
+ success: !1,
1762
+ error: pe.wrap({ value: t, cause: n.error, context: r }),
1763
+ rawValue: t
1764
+ };
1765
+ } catch (n) {
1766
+ return {
1767
+ success: !1,
1768
+ error: pe.wrap({ value: t, cause: n, context: r }),
1769
+ rawValue: t
1770
+ };
1771
+ }
1772
+ }
1773
+ async function Fr({
1774
+ text: t,
1775
+ schema: e
1776
+ }) {
1777
+ try {
1778
+ const r = Xt(t);
1779
+ return e == null ? { success: !0, value: r, rawValue: r } : await Be({ value: r, schema: e });
1780
+ } catch (r) {
1781
+ return {
1782
+ success: !1,
1783
+ error: Ce.isInstance(r) ? r : new Ce({ text: t, cause: r }),
1784
+ rawValue: void 0
1785
+ };
1786
+ }
1787
+ }
1788
+ function Vr(t) {
1789
+ return { ...t, type: "dynamic" };
1790
+ }
1791
+ let we;
1792
+ we = globalThis.crypto;
1793
+ async function Jr(t) {
1794
+ return (await we).getRandomValues(new Uint8Array(t));
1795
+ }
1796
+ async function Wr(t) {
1797
+ const e = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~", r = Math.pow(2, 8) - Math.pow(2, 8) % e.length;
1798
+ let s = "";
1799
+ for (; s.length < t; ) {
1800
+ const n = await Jr(t - s.length);
1801
+ for (const a of n)
1802
+ a < r && (s += e[a % e.length]);
1803
+ }
1804
+ return s;
1805
+ }
1806
+ async function Br(t) {
1807
+ return await Wr(t);
1808
+ }
1809
+ async function Gr(t) {
1810
+ const e = await (await we).subtle.digest("SHA-256", new TextEncoder().encode(t));
1811
+ return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
1812
+ }
1813
+ async function Kr(t) {
1814
+ if (t || (t = 43), t < 43 || t > 128)
1815
+ throw `Expected a length between 43 and 128. Received ${t}.`;
1816
+ const e = await Br(t), r = await Gr(e);
1817
+ return {
1818
+ code_verifier: e,
1819
+ code_challenge: r
1820
+ };
1821
+ }
1822
+ var Xr = "AI_MCPClientError", Ge = `vercel.ai.error.${Xr}`, Qr = Symbol.for(Ge), Oe, Ie, _ = class extends (Ie = K, Oe = Qr, Ie) {
1823
+ constructor({
1824
+ name: t = "MCPClientError",
1825
+ message: e,
1826
+ cause: r,
1827
+ data: s,
1828
+ code: n
1829
+ }) {
1830
+ super({ name: t, message: e, cause: r }), this[Oe] = !0, this.data = s, this.code = n;
1831
+ }
1832
+ static isInstance(t) {
1833
+ return K.hasMarker(t, Ge);
1834
+ }
1835
+ }, D = "2025-11-25", Yr = [
1836
+ D,
1837
+ "2025-06-18",
1838
+ "2025-03-26",
1839
+ "2024-11-05"
1840
+ ], es = o.optional(o.record(o.string(), o.unknown())), ts = o.looseObject({
1841
+ name: o.string(),
1842
+ version: o.string()
1843
+ }), oe = o.looseObject({
1844
+ _meta: o.optional(o.object({}).loose())
1845
+ }), $ = oe, Ke = o.object({
1846
+ method: o.string(),
1847
+ params: o.optional(oe)
1848
+ }), Xe = o.object({
1849
+ applyDefaults: o.optional(o.boolean())
1850
+ }).loose(), rs = o.looseObject({
1851
+ experimental: o.optional(o.object({}).loose()),
1852
+ logging: o.optional(o.object({}).loose()),
1853
+ prompts: o.optional(
1854
+ o.looseObject({
1855
+ listChanged: o.optional(o.boolean())
1856
+ })
1857
+ ),
1858
+ resources: o.optional(
1859
+ o.looseObject({
1860
+ subscribe: o.optional(o.boolean()),
1861
+ listChanged: o.optional(o.boolean())
1862
+ })
1863
+ ),
1864
+ tools: o.optional(
1865
+ o.looseObject({
1866
+ listChanged: o.optional(o.boolean())
1867
+ })
1868
+ ),
1869
+ elicitation: o.optional(Xe)
1870
+ });
1871
+ o.object({
1872
+ elicitation: o.optional(Xe)
1873
+ }).loose();
1874
+ var ss = $.extend({
1875
+ protocolVersion: o.string(),
1876
+ capabilities: rs,
1877
+ serverInfo: ts,
1878
+ instructions: o.optional(o.string())
1879
+ }), _e = $.extend({
1880
+ nextCursor: o.optional(o.string())
1881
+ }), ns = o.object({
1882
+ name: o.string(),
1883
+ /**
1884
+ * @see https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool
1885
+ */
1886
+ title: o.optional(o.string()),
1887
+ description: o.optional(o.string()),
1888
+ inputSchema: o.object({
1889
+ type: o.literal("object"),
1890
+ properties: o.optional(o.object({}).loose())
1891
+ }).loose(),
1892
+ /**
1893
+ * @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema
1894
+ */
1895
+ outputSchema: o.optional(o.object({}).loose()),
1896
+ annotations: o.optional(
1897
+ o.object({
1898
+ title: o.optional(o.string())
1899
+ }).loose()
1900
+ ),
1901
+ _meta: es
1902
+ }).loose(), os = _e.extend({
1903
+ tools: o.array(ns)
1904
+ }), Qe = o.object({
1905
+ type: o.literal("text"),
1906
+ text: o.string()
1907
+ }).loose(), Ye = o.object({
1908
+ type: o.literal("image"),
1909
+ data: o.base64(),
1910
+ mimeType: o.string()
1911
+ }).loose(), as = o.object({
1912
+ uri: o.string(),
1913
+ name: o.string(),
1914
+ title: o.optional(o.string()),
1915
+ description: o.optional(o.string()),
1916
+ mimeType: o.optional(o.string()),
1917
+ size: o.optional(o.number())
1918
+ }).loose(), is = _e.extend({
1919
+ resources: o.array(as)
1920
+ }), et = o.object({
1921
+ /**
1922
+ * The URI of this resource.
1923
+ */
1924
+ uri: o.string(),
1925
+ /**
1926
+ * Optional display name of the resource content.
1927
+ */
1928
+ name: o.optional(o.string()),
1929
+ /**
1930
+ * Optional human readable title.
1931
+ */
1932
+ title: o.optional(o.string()),
1933
+ /**
1934
+ * The MIME type of this resource, if known.
1935
+ */
1936
+ mimeType: o.optional(o.string())
1937
+ }).loose(), tt = et.extend({
1938
+ text: o.string()
1939
+ }), rt = et.extend({
1940
+ blob: o.base64()
1941
+ }), st = o.object({
1942
+ type: o.literal("resource"),
1943
+ resource: o.union([tt, rt])
1944
+ }).loose(), cs = $.extend({
1945
+ content: o.array(
1946
+ o.union([Qe, Ye, st])
1947
+ ),
1948
+ /**
1949
+ * @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content
1950
+ */
1951
+ structuredContent: o.optional(o.unknown()),
1952
+ isError: o.boolean().default(!1).optional()
1953
+ }).or(
1954
+ $.extend({
1955
+ toolResult: o.unknown()
1956
+ })
1957
+ ), ls = o.object({
1958
+ uriTemplate: o.string(),
1959
+ name: o.string(),
1960
+ title: o.optional(o.string()),
1961
+ description: o.optional(o.string()),
1962
+ mimeType: o.optional(o.string())
1963
+ }).loose(), us = $.extend({
1964
+ resourceTemplates: o.array(ls)
1965
+ }), ds = $.extend({
1966
+ contents: o.array(
1967
+ o.union([tt, rt])
1968
+ )
1969
+ }), ps = o.object({
1970
+ name: o.string(),
1971
+ description: o.optional(o.string()),
1972
+ required: o.optional(o.boolean())
1973
+ }).loose(), hs = o.object({
1974
+ name: o.string(),
1975
+ title: o.optional(o.string()),
1976
+ description: o.optional(o.string()),
1977
+ arguments: o.optional(o.array(ps))
1978
+ }).loose(), ms = _e.extend({
1979
+ prompts: o.array(hs)
1980
+ }), fs = o.object({
1981
+ role: o.union([o.literal("user"), o.literal("assistant")]),
1982
+ content: o.union([
1983
+ Qe,
1984
+ Ye,
1985
+ st
1986
+ ])
1987
+ }).loose(), gs = $.extend({
1988
+ description: o.optional(o.string()),
1989
+ messages: o.array(fs)
1990
+ }), ys = oe.extend({
1991
+ message: o.string(),
1992
+ requestedSchema: o.unknown()
1993
+ }), xe = Ke.extend({
1994
+ method: o.literal("elicitation/create"),
1995
+ params: ys
1996
+ }), vs = $.extend({
1997
+ action: o.union([
1998
+ o.literal("accept"),
1999
+ o.literal("decline"),
2000
+ o.literal("cancel")
2001
+ ]),
2002
+ content: o.optional(o.record(o.string(), o.unknown()))
2003
+ }), ae = "2.0", ws = o.object({
2004
+ jsonrpc: o.literal(ae),
2005
+ id: o.union([o.string(), o.number().int()])
2006
+ }).merge(Ke).strict(), _s = o.object({
2007
+ jsonrpc: o.literal(ae),
2008
+ id: o.union([o.string(), o.number().int()]),
2009
+ result: $
2010
+ }).strict(), bs = o.object({
2011
+ jsonrpc: o.literal(ae),
2012
+ id: o.union([o.string(), o.number().int()]),
2013
+ error: o.object({
2014
+ code: o.number().int(),
2015
+ message: o.string(),
2016
+ data: o.optional(o.unknown())
2017
+ })
2018
+ }).strict(), Ss = o.object({
2019
+ jsonrpc: o.literal(ae)
2020
+ }).merge(
2021
+ o.object({
2022
+ method: o.string(),
2023
+ params: o.optional(oe)
2024
+ })
2025
+ ).strict(), V = o.union([
2026
+ ws,
2027
+ Ss,
2028
+ _s,
2029
+ bs
2030
+ ]), nt = typeof __PACKAGE_VERSION__ < "u" ? __PACKAGE_VERSION__ : "0.0.0-test", ot = o.object({
2031
+ access_token: o.string(),
2032
+ id_token: o.string().optional(),
2033
+ // Optional for OAuth 2.1, but necessary in OpenID Connect
2034
+ token_type: o.string(),
2035
+ expires_in: o.number().optional(),
2036
+ scope: o.string().optional(),
2037
+ refresh_token: o.string().optional()
2038
+ }).strip(), R = o.string().url().superRefine((t, e) => {
2039
+ if (!URL.canParse(t))
2040
+ return e.addIssue({
2041
+ code: o.ZodIssueCode.custom,
2042
+ message: "URL must be parseable",
2043
+ fatal: !0
2044
+ }), o.NEVER;
2045
+ }).refine(
2046
+ (t) => {
2047
+ const e = new URL(t);
2048
+ return e.protocol !== "javascript:" && e.protocol !== "data:" && e.protocol !== "vbscript:";
2049
+ },
2050
+ { message: "URL cannot use javascript:, data:, or vbscript: scheme" }
2051
+ ), Ts = o.object({
2052
+ resource: o.string().url(),
2053
+ authorization_servers: o.array(R).optional(),
2054
+ jwks_uri: o.string().url().optional(),
2055
+ scopes_supported: o.array(o.string()).optional(),
2056
+ bearer_methods_supported: o.array(o.string()).optional(),
2057
+ resource_signing_alg_values_supported: o.array(o.string()).optional(),
2058
+ resource_name: o.string().optional(),
2059
+ resource_documentation: o.string().optional(),
2060
+ resource_policy_uri: o.string().url().optional(),
2061
+ resource_tos_uri: o.string().url().optional(),
2062
+ tls_client_certificate_bound_access_tokens: o.boolean().optional(),
2063
+ authorization_details_types_supported: o.array(o.string()).optional(),
2064
+ dpop_signing_alg_values_supported: o.array(o.string()).optional(),
2065
+ dpop_bound_access_tokens_required: o.boolean().optional()
2066
+ }).passthrough(), at = o.object({
2067
+ issuer: o.string(),
2068
+ authorization_endpoint: R,
2069
+ token_endpoint: R,
2070
+ registration_endpoint: R.optional(),
2071
+ scopes_supported: o.array(o.string()).optional(),
2072
+ response_types_supported: o.array(o.string()),
2073
+ grant_types_supported: o.array(o.string()).optional(),
2074
+ code_challenge_methods_supported: o.array(o.string()),
2075
+ token_endpoint_auth_methods_supported: o.array(o.string()).optional(),
2076
+ token_endpoint_auth_signing_alg_values_supported: o.array(o.string()).optional()
2077
+ }).passthrough(), Ps = o.object({
2078
+ issuer: o.string(),
2079
+ authorization_endpoint: R,
2080
+ token_endpoint: R,
2081
+ userinfo_endpoint: R.optional(),
2082
+ jwks_uri: R,
2083
+ registration_endpoint: R.optional(),
2084
+ scopes_supported: o.array(o.string()).optional(),
2085
+ response_types_supported: o.array(o.string()),
2086
+ grant_types_supported: o.array(o.string()).optional(),
2087
+ subject_types_supported: o.array(o.string()),
2088
+ id_token_signing_alg_values_supported: o.array(o.string()),
2089
+ claims_supported: o.array(o.string()).optional(),
2090
+ token_endpoint_auth_methods_supported: o.array(o.string()).optional()
2091
+ }).passthrough(), Cs = Ps.merge(
2092
+ at.pick({
2093
+ code_challenge_methods_supported: !0
2094
+ })
2095
+ ), Rs = o.object({
2096
+ client_id: o.string(),
2097
+ client_secret: o.string().optional(),
2098
+ client_id_issued_at: o.number().optional(),
2099
+ client_secret_expires_at: o.number().optional()
2100
+ }).strip(), Ms = o.object({
2101
+ redirect_uris: o.array(R),
2102
+ token_endpoint_auth_method: o.string().optional(),
2103
+ grant_types: o.array(o.string()).optional(),
2104
+ response_types: o.array(o.string()).optional(),
2105
+ client_name: o.string().optional(),
2106
+ client_uri: R.optional(),
2107
+ logo_uri: R.optional(),
2108
+ scope: o.string().optional(),
2109
+ contacts: o.array(o.string()).optional(),
2110
+ tos_uri: R.optional(),
2111
+ policy_uri: o.string().optional(),
2112
+ jwks_uri: R.optional(),
2113
+ jwks: o.any().optional(),
2114
+ software_id: o.string().optional(),
2115
+ software_version: o.string().optional(),
2116
+ software_statement: o.string().optional()
2117
+ }).strip(), Es = o.object({
2118
+ error: o.string(),
2119
+ error_description: o.string().optional(),
2120
+ error_uri: o.string().optional()
2121
+ }), As = Ms.merge(
2122
+ Rs
2123
+ ), ks = "AI_MCPClientOAuthError", it = `vercel.ai.error.${ks}`, Os = Symbol.for(it), Le, Ue, W = class extends (Ue = K, Le = Os, Ue) {
2124
+ constructor({
2125
+ name: t = "MCPClientOAuthError",
2126
+ message: e,
2127
+ cause: r
2128
+ }) {
2129
+ super({ name: t, message: e, cause: r }), this[Le] = !0;
2130
+ }
2131
+ static isInstance(t) {
2132
+ return K.hasMarker(t, it);
2133
+ }
2134
+ }, Z = class extends W {
2135
+ };
2136
+ Z.errorCode = "server_error";
2137
+ var X = class extends W {
2138
+ };
2139
+ X.errorCode = "invalid_client";
2140
+ var Q = class extends W {
2141
+ };
2142
+ Q.errorCode = "invalid_grant";
2143
+ var Y = class extends W {
2144
+ };
2145
+ Y.errorCode = "unauthorized_client";
2146
+ var Is = {
2147
+ [Z.errorCode]: Z,
2148
+ [X.errorCode]: X,
2149
+ [Q.errorCode]: Q,
2150
+ [Y.errorCode]: Y
2151
+ };
2152
+ function xs(t) {
2153
+ const e = typeof t == "string" ? new URL(t) : new URL(t.href);
2154
+ return e.hash = "", e;
2155
+ }
2156
+ function Ls({
2157
+ requestedResource: t,
2158
+ configuredResource: e
2159
+ }) {
2160
+ const r = typeof t == "string" ? new URL(t) : new URL(t.href), s = typeof e == "string" ? new URL(e) : new URL(e.href);
2161
+ if (r.origin !== s.origin || r.pathname.length < s.pathname.length)
2162
+ return !1;
2163
+ const n = r.pathname.endsWith("/") ? r.pathname : r.pathname + "/", a = s.pathname.endsWith("/") ? s.pathname : s.pathname + "/";
2164
+ return n.startsWith(a);
2165
+ }
2166
+ var ee = class extends Error {
2167
+ constructor(t = "Unauthorized") {
2168
+ super(t), this.name = "UnauthorizedError";
2169
+ }
2170
+ };
2171
+ function te(t) {
2172
+ var e;
2173
+ const r = (e = t.headers.get("www-authenticate")) != null ? e : t.headers.get("WWW-Authenticate");
2174
+ if (!r)
2175
+ return;
2176
+ const [s, n] = r.split(" ");
2177
+ if (s.toLowerCase() !== "bearer" || !n)
2178
+ return;
2179
+ const a = /resource_metadata="([^"]*)"/, i = r.match(a);
2180
+ if (i)
2181
+ try {
2182
+ return new URL(i[1]);
2183
+ } catch {
2184
+ return;
2185
+ }
2186
+ }
2187
+ function Us(t, e = "", r = {}) {
2188
+ return e.endsWith("/") && (e = e.slice(0, -1)), r.prependPathname ? `${e}/.well-known/${t}` : `/.well-known/${t}${e}`;
2189
+ }
2190
+ async function be(t, e, r = fetch) {
2191
+ try {
2192
+ return await r(t, { headers: e });
2193
+ } catch (s) {
2194
+ if (s instanceof TypeError)
2195
+ return e ? be(t, void 0, r) : void 0;
2196
+ throw s;
2197
+ }
2198
+ }
2199
+ async function $e(t, e, r = fetch) {
2200
+ return await be(t, {
2201
+ "MCP-Protocol-Version": e
2202
+ }, r);
2203
+ }
2204
+ function $s(t, e) {
2205
+ return !t || t.status >= 400 && t.status < 500 && e !== "/";
2206
+ }
2207
+ async function js(t, e, r, s) {
2208
+ var n, a;
2209
+ const i = new URL(t), u = (n = s?.protocolVersion) != null ? n : D;
2210
+ let l;
2211
+ if (s?.metadataUrl)
2212
+ l = new URL(s.metadataUrl);
2213
+ else {
2214
+ const p = Us(e, i.pathname);
2215
+ l = new URL(p, (a = s?.metadataServerUrl) != null ? a : i), l.search = i.search;
2216
+ }
2217
+ let c = await $e(l, u, r);
2218
+ if (!s?.metadataUrl && $s(c, i.pathname)) {
2219
+ const p = new URL(`/.well-known/${e}`, i);
2220
+ c = await $e(p, u, r);
2221
+ }
2222
+ return c;
2223
+ }
2224
+ async function Ns(t, e, r = fetch) {
2225
+ const s = await js(
2226
+ t,
2227
+ "oauth-protected-resource",
2228
+ r,
2229
+ {
2230
+ protocolVersion: e?.protocolVersion,
2231
+ metadataUrl: e?.resourceMetadataUrl
2232
+ }
2233
+ );
2234
+ if (!s || s.status === 404)
2235
+ throw new Error(
2236
+ "Resource server does not implement OAuth 2.0 Protected Resource Metadata."
2237
+ );
2238
+ if (!s.ok)
2239
+ throw new Error(
2240
+ `HTTP ${s.status} trying to load well-known OAuth protected resource metadata.`
2241
+ );
2242
+ return Ts.parse(await s.json());
2243
+ }
2244
+ function qs(t) {
2245
+ const e = typeof t == "string" ? new URL(t) : t, r = e.pathname !== "/", s = [];
2246
+ if (!r)
2247
+ return s.push({
2248
+ url: new URL("/.well-known/oauth-authorization-server", e.origin),
2249
+ type: "oauth"
2250
+ }), s.push({
2251
+ url: new URL("/.well-known/openid-configuration", e.origin),
2252
+ type: "oidc"
2253
+ }), s;
2254
+ let n = e.pathname;
2255
+ return n.endsWith("/") && (n = n.slice(0, -1)), s.push({
2256
+ url: new URL(
2257
+ `/.well-known/oauth-authorization-server${n}`,
2258
+ e.origin
2259
+ ),
2260
+ type: "oauth"
2261
+ }), s.push({
2262
+ url: new URL("/.well-known/oauth-authorization-server", e.origin),
2263
+ type: "oauth"
2264
+ }), s.push({
2265
+ url: new URL(`/.well-known/openid-configuration${n}`, e.origin),
2266
+ type: "oidc"
2267
+ }), s.push({
2268
+ url: new URL(`${n}/.well-known/openid-configuration`, e.origin),
2269
+ type: "oidc"
2270
+ }), s;
2271
+ }
2272
+ async function Hs(t, {
2273
+ fetchFn: e = fetch,
2274
+ protocolVersion: r = D
2275
+ } = {}) {
2276
+ var s;
2277
+ const n = { "MCP-Protocol-Version": r }, a = qs(t);
2278
+ for (const { url: i, type: u } of a) {
2279
+ const l = await be(i, n, e);
2280
+ if (l) {
2281
+ if (!l.ok) {
2282
+ if (l.status >= 400 && l.status < 500)
2283
+ continue;
2284
+ throw new Error(
2285
+ `HTTP ${l.status} trying to load ${u === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${i}`
2286
+ );
2287
+ }
2288
+ if (u === "oauth")
2289
+ return at.parse(await l.json());
2290
+ {
2291
+ const c = Cs.parse(
2292
+ await l.json()
2293
+ );
2294
+ if (!((s = c.code_challenge_methods_supported) != null && s.includes("S256")))
2295
+ throw new Error(
2296
+ `Incompatible OIDC provider at ${i}: does not support S256 code challenge method required by MCP specification`
2297
+ );
2298
+ return c;
2299
+ }
2300
+ }
2301
+ }
2302
+ }
2303
+ async function Zs(t, {
2304
+ metadata: e,
2305
+ clientInformation: r,
2306
+ redirectUrl: s,
2307
+ scope: n,
2308
+ state: a,
2309
+ resource: i
2310
+ }) {
2311
+ const u = "code", l = "S256";
2312
+ let c;
2313
+ if (e) {
2314
+ if (c = new URL(e.authorization_endpoint), !e.response_types_supported.includes(u))
2315
+ throw new Error(
2316
+ `Incompatible auth server: does not support response type ${u}`
2317
+ );
2318
+ if (!e.code_challenge_methods_supported || !e.code_challenge_methods_supported.includes(l))
2319
+ throw new Error(
2320
+ `Incompatible auth server: does not support code challenge method ${l}`
2321
+ );
2322
+ } else
2323
+ c = new URL("/authorize", t);
2324
+ const p = await Kr(), g = p.code_verifier, d = p.code_challenge;
2325
+ return c.searchParams.set("response_type", u), c.searchParams.set("client_id", r.client_id), c.searchParams.set("code_challenge", d), c.searchParams.set(
2326
+ "code_challenge_method",
2327
+ l
2328
+ ), c.searchParams.set("redirect_uri", String(s)), a && c.searchParams.set("state", a), n && c.searchParams.set("scope", n), n?.includes("offline_access") && c.searchParams.append("prompt", "consent"), i && c.searchParams.set("resource", i.href), { authorizationUrl: c, codeVerifier: g };
2329
+ }
2330
+ function ct(t, e) {
2331
+ const r = t.client_secret !== void 0;
2332
+ return e.length === 0 ? r ? "client_secret_post" : "none" : r && e.includes("client_secret_basic") ? "client_secret_basic" : r && e.includes("client_secret_post") ? "client_secret_post" : e.includes("none") ? "none" : r ? "client_secret_post" : "none";
2333
+ }
2334
+ function lt(t, e, r, s) {
2335
+ const { client_id: n, client_secret: a } = e;
2336
+ switch (t) {
2337
+ case "client_secret_basic":
2338
+ Ds(n, a, r);
2339
+ return;
2340
+ case "client_secret_post":
2341
+ zs(n, a, s);
2342
+ return;
2343
+ case "none":
2344
+ Fs(n, s);
2345
+ return;
2346
+ default:
2347
+ throw new Error(`Unsupported client authentication method: ${t}`);
2348
+ }
2349
+ }
2350
+ function Ds(t, e, r) {
2351
+ if (!e)
2352
+ throw new Error(
2353
+ "client_secret_basic authentication requires a client_secret"
2354
+ );
2355
+ const s = btoa(`${t}:${e}`);
2356
+ r.set("Authorization", `Basic ${s}`);
2357
+ }
2358
+ function zs(t, e, r) {
2359
+ r.set("client_id", t), e && r.set("client_secret", e);
2360
+ }
2361
+ function Fs(t, e) {
2362
+ e.set("client_id", t);
2363
+ }
2364
+ async function Se(t) {
2365
+ const e = t instanceof Response ? t.status : void 0, r = t instanceof Response ? await t.text() : t;
2366
+ try {
2367
+ const s = Es.parse(JSON.parse(r)), { error: n, error_description: a, error_uri: i } = s, u = Is[n] || Z;
2368
+ return new u({
2369
+ message: a || "",
2370
+ cause: i
2371
+ });
2372
+ } catch (s) {
2373
+ const n = `${e ? `HTTP ${e}: ` : ""}Invalid OAuth error response: ${s}. Raw body: ${r}`;
2374
+ return new Z({ message: n });
2375
+ }
2376
+ }
2377
+ async function Vs(t, {
2378
+ metadata: e,
2379
+ clientInformation: r,
2380
+ authorizationCode: s,
2381
+ codeVerifier: n,
2382
+ redirectUri: a,
2383
+ resource: i,
2384
+ addClientAuthentication: u,
2385
+ fetchFn: l
2386
+ }) {
2387
+ var c;
2388
+ const p = "authorization_code", g = e?.token_endpoint ? new URL(e.token_endpoint) : new URL("/token", t);
2389
+ if (e?.grant_types_supported && !e.grant_types_supported.includes(p))
2390
+ throw new Error(
2391
+ `Incompatible auth server: does not support grant type ${p}`
2392
+ );
2393
+ const d = new Headers({
2394
+ "Content-Type": "application/x-www-form-urlencoded",
2395
+ Accept: "application/json"
2396
+ }), m = new URLSearchParams({
2397
+ grant_type: p,
2398
+ code: s,
2399
+ code_verifier: n,
2400
+ redirect_uri: String(a)
2401
+ });
2402
+ if (u)
2403
+ u(d, m, t, e);
2404
+ else {
2405
+ const h = (c = e?.token_endpoint_auth_methods_supported) != null ? c : [], f = ct(
2406
+ r,
2407
+ h
2408
+ );
2409
+ lt(f, r, d, m);
2410
+ }
2411
+ i && m.set("resource", i.href);
2412
+ const y = await (l ?? fetch)(g, {
2413
+ method: "POST",
2414
+ headers: d,
2415
+ body: m
2416
+ });
2417
+ if (!y.ok)
2418
+ throw await Se(y);
2419
+ return ot.parse(await y.json());
2420
+ }
2421
+ async function Js(t, {
2422
+ metadata: e,
2423
+ clientInformation: r,
2424
+ refreshToken: s,
2425
+ resource: n,
2426
+ addClientAuthentication: a,
2427
+ fetchFn: i
2428
+ }) {
2429
+ var u;
2430
+ const l = "refresh_token";
2431
+ let c;
2432
+ if (e) {
2433
+ if (c = new URL(e.token_endpoint), e.grant_types_supported && !e.grant_types_supported.includes(l))
2434
+ throw new Error(
2435
+ `Incompatible auth server: does not support grant type ${l}`
2436
+ );
2437
+ } else
2438
+ c = new URL("/token", t);
2439
+ const p = new Headers({
2440
+ "Content-Type": "application/x-www-form-urlencoded",
2441
+ Accept: "application/json"
2442
+ }), g = new URLSearchParams({
2443
+ grant_type: l,
2444
+ refresh_token: s
2445
+ });
2446
+ if (a)
2447
+ a(p, g, t, e);
2448
+ else {
2449
+ const m = (u = e?.token_endpoint_auth_methods_supported) != null ? u : [], y = ct(
2450
+ r,
2451
+ m
2452
+ );
2453
+ lt(y, r, p, g);
2454
+ }
2455
+ n && g.set("resource", n.href);
2456
+ const d = await (i ?? fetch)(c, {
2457
+ method: "POST",
2458
+ headers: p,
2459
+ body: g
2460
+ });
2461
+ if (!d.ok)
2462
+ throw await Se(d);
2463
+ return ot.parse({
2464
+ refresh_token: s,
2465
+ ...await d.json()
2466
+ });
2467
+ }
2468
+ async function Ws(t, {
2469
+ metadata: e,
2470
+ clientMetadata: r,
2471
+ fetchFn: s
2472
+ }) {
2473
+ let n;
2474
+ if (e) {
2475
+ if (!e.registration_endpoint)
2476
+ throw new Error(
2477
+ "Incompatible auth server: does not support dynamic client registration"
2478
+ );
2479
+ n = new URL(e.registration_endpoint);
2480
+ } else
2481
+ n = new URL("/register", t);
2482
+ const a = await (s ?? fetch)(n, {
2483
+ method: "POST",
2484
+ headers: {
2485
+ "Content-Type": "application/json"
2486
+ },
2487
+ body: JSON.stringify(r)
2488
+ });
2489
+ if (!a.ok)
2490
+ throw await Se(a);
2491
+ return As.parse(await a.json());
2492
+ }
2493
+ async function re(t, e) {
2494
+ var r, s;
2495
+ try {
2496
+ return await de(t, e);
2497
+ } catch (n) {
2498
+ if (n instanceof X || n instanceof Y)
2499
+ return await ((r = t.invalidateCredentials) == null ? void 0 : r.call(t, "all")), await de(t, e);
2500
+ if (n instanceof Q)
2501
+ return await ((s = t.invalidateCredentials) == null ? void 0 : s.call(t, "tokens")), await de(t, e);
2502
+ throw n;
2503
+ }
2504
+ }
2505
+ async function Bs(t, e, r) {
2506
+ const s = xs(t);
2507
+ if (e.validateResourceURL)
2508
+ return await e.validateResourceURL(
2509
+ s,
2510
+ r?.resource
2511
+ );
2512
+ if (r) {
2513
+ if (!Ls({
2514
+ requestedResource: s,
2515
+ configuredResource: r.resource
2516
+ }))
2517
+ throw new Error(
2518
+ `Protected resource ${r.resource} does not match expected ${s} (or origin)`
2519
+ );
2520
+ return new URL(r.resource);
2521
+ }
2522
+ }
2523
+ async function de(t, {
2524
+ serverUrl: e,
2525
+ authorizationCode: r,
2526
+ callbackState: s,
2527
+ scope: n,
2528
+ resourceMetadataUrl: a,
2529
+ fetchFn: i
2530
+ }) {
2531
+ let u, l;
2532
+ try {
2533
+ u = await Ns(
2534
+ e,
2535
+ { resourceMetadataUrl: a },
2536
+ i
2537
+ ), u.authorization_servers && u.authorization_servers.length > 0 && (l = u.authorization_servers[0]);
2538
+ } catch {
2539
+ }
2540
+ l || (l = e);
2541
+ const c = await Bs(
2542
+ e,
2543
+ t,
2544
+ u
2545
+ ), p = await Hs(
2546
+ l,
2547
+ {
2548
+ fetchFn: i
2549
+ }
2550
+ );
2551
+ let g = await Promise.resolve(t.clientInformation());
2552
+ if (!g) {
2553
+ if (r !== void 0)
2554
+ throw new Error(
2555
+ "Existing OAuth client information is required when exchanging an authorization code"
2556
+ );
2557
+ if (!t.saveClientInformation)
2558
+ throw new Error(
2559
+ "OAuth client information must be saveable for dynamic registration"
2560
+ );
2561
+ const f = await Ws(l, {
2562
+ metadata: p,
2563
+ clientMetadata: t.clientMetadata,
2564
+ fetchFn: i
2565
+ });
2566
+ await t.saveClientInformation(f), g = f;
2567
+ }
2568
+ if (r !== void 0) {
2569
+ if (t.storedState) {
2570
+ const b = await t.storedState();
2571
+ if (b !== void 0 && b !== s)
2572
+ throw new Error(
2573
+ "OAuth state parameter mismatch - possible CSRF attack"
2574
+ );
2575
+ }
2576
+ const f = await t.codeVerifier(), v = await Vs(l, {
2577
+ metadata: p,
2578
+ clientInformation: g,
2579
+ authorizationCode: r,
2580
+ codeVerifier: f,
2581
+ redirectUri: t.redirectUrl,
2582
+ resource: c,
2583
+ addClientAuthentication: t.addClientAuthentication,
2584
+ fetchFn: i
2585
+ });
2586
+ return await t.saveTokens(v), "AUTHORIZED";
2587
+ }
2588
+ const d = await t.tokens();
2589
+ if (d?.refresh_token)
2590
+ try {
2591
+ const f = await Js(l, {
2592
+ metadata: p,
2593
+ clientInformation: g,
2594
+ refreshToken: d.refresh_token,
2595
+ resource: c,
2596
+ addClientAuthentication: t.addClientAuthentication,
2597
+ fetchFn: i
2598
+ });
2599
+ return await t.saveTokens(f), "AUTHORIZED";
2600
+ } catch (f) {
2601
+ if (
2602
+ // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry.
2603
+ !(!(f instanceof W) || f instanceof Z)
2604
+ ) throw f;
2605
+ }
2606
+ const m = t.state ? await t.state() : void 0;
2607
+ m && t.saveState && await t.saveState(m);
2608
+ const { authorizationUrl: y, codeVerifier: h } = await Zs(
2609
+ l,
2610
+ {
2611
+ metadata: p,
2612
+ clientInformation: g,
2613
+ state: m,
2614
+ redirectUrl: t.redirectUrl,
2615
+ scope: n || t.clientMetadata.scope,
2616
+ resource: c
2617
+ }
2618
+ );
2619
+ return await t.saveCodeVerifier(h), await t.redirectToAuthorization(y), "REDIRECT";
2620
+ }
2621
+ var Gs = class {
2622
+ constructor({
2623
+ url: t,
2624
+ headers: e,
2625
+ authProvider: r,
2626
+ redirect: s = "follow"
2627
+ }) {
2628
+ this.connected = !1, this.url = new URL(t), this.headers = e, this.authProvider = r, this.redirectMode = s;
2629
+ }
2630
+ async commonHeaders(t) {
2631
+ const e = {
2632
+ ...this.headers,
2633
+ ...t,
2634
+ "mcp-protocol-version": D
2635
+ };
2636
+ if (this.authProvider) {
2637
+ const r = await this.authProvider.tokens();
2638
+ r?.access_token && (e.Authorization = `Bearer ${r.access_token}`);
2639
+ }
2640
+ return De(
2641
+ e,
2642
+ `ai-sdk/${nt}`,
2643
+ Ze()
2644
+ );
2645
+ }
2646
+ async start() {
2647
+ return new Promise((t, e) => {
2648
+ if (this.connected)
2649
+ return t();
2650
+ this.abortController = new AbortController();
2651
+ const r = async (s = !1) => {
2652
+ var n, a, i, u, l;
2653
+ try {
2654
+ const c = await this.commonHeaders({
2655
+ Accept: "text/event-stream"
2656
+ }), p = await fetch(this.url.href, {
2657
+ headers: c,
2658
+ signal: (n = this.abortController) == null ? void 0 : n.signal,
2659
+ redirect: this.redirectMode
2660
+ });
2661
+ if (p.status === 401 && this.authProvider && !s) {
2662
+ this.resourceMetadataUrl = te(p);
2663
+ try {
2664
+ if (await re(this.authProvider, {
2665
+ serverUrl: this.url,
2666
+ resourceMetadataUrl: this.resourceMetadataUrl
2667
+ }) !== "AUTHORIZED") {
2668
+ const h = new ee();
2669
+ return (a = this.onerror) == null || a.call(this, h), e(h);
2670
+ }
2671
+ } catch (y) {
2672
+ return (i = this.onerror) == null || i.call(this, y), e(y);
2673
+ }
2674
+ return r(!0);
2675
+ }
2676
+ if (!p.ok || !p.body) {
2677
+ let y = `MCP SSE Transport Error: ${p.status} ${p.statusText}`;
2678
+ p.status === 405 && (y += ". This server does not support SSE transport. Try using `http` transport instead");
2679
+ const h = new _({
2680
+ message: y
2681
+ });
2682
+ return (u = this.onerror) == null || u.call(this, h), e(h);
2683
+ }
2684
+ const d = p.body.pipeThrough(new TextDecoderStream()).pipeThrough(new he()).getReader(), m = async () => {
2685
+ var y, h, f;
2686
+ try {
2687
+ for (; ; ) {
2688
+ const { done: v, value: b } = await d.read();
2689
+ if (v) {
2690
+ if (this.connected)
2691
+ throw this.connected = !1, new _({
2692
+ message: "MCP SSE Transport Error: Connection closed unexpectedly"
2693
+ });
2694
+ return;
2695
+ }
2696
+ const { event: T, data: A } = b;
2697
+ if (T === "endpoint") {
2698
+ if (this.endpoint = new URL(A, this.url), this.endpoint.origin !== this.url.origin)
2699
+ throw new _({
2700
+ message: `MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`
2701
+ });
2702
+ this.connected = !0, t();
2703
+ } else if (T === "message")
2704
+ try {
2705
+ const M = V.parse(
2706
+ JSON.parse(A)
2707
+ );
2708
+ (y = this.onmessage) == null || y.call(this, M);
2709
+ } catch (M) {
2710
+ const k = new _({
2711
+ message: "MCP SSE Transport Error: Failed to parse message",
2712
+ cause: M
2713
+ });
2714
+ (h = this.onerror) == null || h.call(this, k);
2715
+ }
2716
+ }
2717
+ } catch (v) {
2718
+ if (v instanceof Error && v.name === "AbortError")
2719
+ return;
2720
+ (f = this.onerror) == null || f.call(this, v), e(v);
2721
+ }
2722
+ };
2723
+ this.sseConnection = {
2724
+ close: () => d.cancel()
2725
+ }, m();
2726
+ } catch (c) {
2727
+ if (c instanceof Error && c.name === "AbortError")
2728
+ return;
2729
+ (l = this.onerror) == null || l.call(this, c), e(c);
2730
+ }
2731
+ };
2732
+ r();
2733
+ });
2734
+ }
2735
+ async close() {
2736
+ var t, e, r;
2737
+ this.connected = !1, (t = this.sseConnection) == null || t.close(), (e = this.abortController) == null || e.abort(), (r = this.onclose) == null || r.call(this);
2738
+ }
2739
+ async send(t) {
2740
+ if (!this.endpoint || !this.connected)
2741
+ throw new _({
2742
+ message: "MCP SSE Transport Error: Not connected"
2743
+ });
2744
+ const e = this.endpoint, r = async (s = !1) => {
2745
+ var n, a, i, u, l;
2746
+ try {
2747
+ const p = {
2748
+ method: "POST",
2749
+ headers: await this.commonHeaders({
2750
+ "Content-Type": "application/json"
2751
+ }),
2752
+ body: JSON.stringify(t),
2753
+ signal: (n = this.abortController) == null ? void 0 : n.signal,
2754
+ redirect: this.redirectMode
2755
+ }, g = await fetch(e, p);
2756
+ if (g.status === 401 && this.authProvider && !s) {
2757
+ this.resourceMetadataUrl = te(g);
2758
+ try {
2759
+ if (await re(this.authProvider, {
2760
+ serverUrl: this.url,
2761
+ resourceMetadataUrl: this.resourceMetadataUrl
2762
+ }) !== "AUTHORIZED") {
2763
+ const m = new ee();
2764
+ (a = this.onerror) == null || a.call(this, m);
2765
+ return;
2766
+ }
2767
+ } catch (d) {
2768
+ (i = this.onerror) == null || i.call(this, d);
2769
+ return;
2770
+ }
2771
+ return r(!0);
2772
+ }
2773
+ if (!g.ok) {
2774
+ const d = await g.text().catch(() => null), m = new _({
2775
+ message: `MCP SSE Transport Error: POSTing to endpoint (HTTP ${g.status}): ${d}`
2776
+ });
2777
+ (u = this.onerror) == null || u.call(this, m);
2778
+ return;
2779
+ }
2780
+ } catch (c) {
2781
+ (l = this.onerror) == null || l.call(this, c);
2782
+ return;
2783
+ }
2784
+ };
2785
+ await r();
2786
+ }
2787
+ }, Ks = class {
2788
+ constructor({
2789
+ url: t,
2790
+ headers: e,
2791
+ authProvider: r,
2792
+ redirect: s = "follow"
2793
+ }) {
2794
+ this.inboundReconnectAttempts = 0, this.reconnectionOptions = {
2795
+ initialReconnectionDelay: 1e3,
2796
+ maxReconnectionDelay: 3e4,
2797
+ reconnectionDelayGrowFactor: 1.5,
2798
+ maxRetries: 2
2799
+ }, this.url = new URL(t), this.headers = e, this.authProvider = r, this.redirectMode = s;
2800
+ }
2801
+ async commonHeaders(t) {
2802
+ const e = {
2803
+ ...this.headers,
2804
+ ...t,
2805
+ "mcp-protocol-version": D
2806
+ };
2807
+ if (this.sessionId && (e["mcp-session-id"] = this.sessionId), this.authProvider) {
2808
+ const r = await this.authProvider.tokens();
2809
+ r?.access_token && (e.Authorization = `Bearer ${r.access_token}`);
2810
+ }
2811
+ return De(
2812
+ e,
2813
+ `ai-sdk/${nt}`,
2814
+ Ze()
2815
+ );
2816
+ }
2817
+ async start() {
2818
+ if (this.abortController)
2819
+ throw new _({
2820
+ message: "MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."
2821
+ });
2822
+ this.abortController = new AbortController(), this.openInboundSse();
2823
+ }
2824
+ async close() {
2825
+ var t, e, r;
2826
+ (t = this.inboundSseConnection) == null || t.close();
2827
+ try {
2828
+ if (this.sessionId && this.abortController && !this.abortController.signal.aborted) {
2829
+ const s = await this.commonHeaders({});
2830
+ await fetch(this.url, {
2831
+ method: "DELETE",
2832
+ headers: s,
2833
+ signal: this.abortController.signal,
2834
+ redirect: this.redirectMode
2835
+ }).catch(() => {
2836
+ });
2837
+ }
2838
+ } catch {
2839
+ }
2840
+ (e = this.abortController) == null || e.abort(), (r = this.onclose) == null || r.call(this);
2841
+ }
2842
+ async send(t) {
2843
+ const e = async (r = !1) => {
2844
+ var s, n, a, i, u, l, c;
2845
+ try {
2846
+ const g = {
2847
+ method: "POST",
2848
+ headers: await this.commonHeaders({
2849
+ "Content-Type": "application/json",
2850
+ Accept: "application/json, text/event-stream"
2851
+ }),
2852
+ body: JSON.stringify(t),
2853
+ signal: (s = this.abortController) == null ? void 0 : s.signal,
2854
+ redirect: this.redirectMode
2855
+ }, d = await fetch(this.url, g), m = d.headers.get("mcp-session-id");
2856
+ if (m && (this.sessionId = m), d.status === 401 && this.authProvider && !r) {
2857
+ this.resourceMetadataUrl = te(d);
2858
+ try {
2859
+ if (await re(this.authProvider, {
2860
+ serverUrl: this.url,
2861
+ resourceMetadataUrl: this.resourceMetadataUrl
2862
+ }) !== "AUTHORIZED")
2863
+ throw new ee();
2864
+ } catch (v) {
2865
+ throw (n = this.onerror) == null || n.call(this, v), v;
2866
+ }
2867
+ return e(!0);
2868
+ }
2869
+ if (d.status === 202) {
2870
+ this.inboundSseConnection || this.openInboundSse();
2871
+ return;
2872
+ }
2873
+ if (!d.ok) {
2874
+ const v = await d.text().catch(() => null);
2875
+ let b = `MCP HTTP Transport Error: POSTing to endpoint (HTTP ${d.status}): ${v}`;
2876
+ d.status === 404 && (b += ". This server does not support HTTP transport. Try using `sse` transport instead");
2877
+ const T = new _({
2878
+ message: b
2879
+ });
2880
+ throw (a = this.onerror) == null || a.call(this, T), T;
2881
+ }
2882
+ if (!("id" in t))
2883
+ return;
2884
+ const h = d.headers.get("content-type") || "";
2885
+ if (h.includes("application/json")) {
2886
+ const v = await d.json(), b = Array.isArray(v) ? v.map((T) => V.parse(T)) : [V.parse(v)];
2887
+ for (const T of b) (i = this.onmessage) == null || i.call(this, T);
2888
+ return;
2889
+ }
2890
+ if (h.includes("text/event-stream")) {
2891
+ if (!d.body) {
2892
+ const A = new _({
2893
+ message: "MCP HTTP Transport Error: text/event-stream response without body"
2894
+ });
2895
+ throw (u = this.onerror) == null || u.call(this, A), A;
2896
+ }
2897
+ const b = d.body.pipeThrough(new TextDecoderStream()).pipeThrough(new he()).getReader();
2898
+ (async () => {
2899
+ var A, M, k;
2900
+ try {
2901
+ for (; ; ) {
2902
+ const { done: O, value: H } = await b.read();
2903
+ if (O) return;
2904
+ const { event: I, data: j } = H;
2905
+ if (I === "message")
2906
+ try {
2907
+ const z = V.parse(JSON.parse(j));
2908
+ (A = this.onmessage) == null || A.call(this, z);
2909
+ } catch (z) {
2910
+ const x = new _({
2911
+ message: "MCP HTTP Transport Error: Failed to parse message",
2912
+ cause: z
2913
+ });
2914
+ (M = this.onerror) == null || M.call(this, x);
2915
+ }
2916
+ }
2917
+ } catch (O) {
2918
+ if (O instanceof Error && O.name === "AbortError")
2919
+ return;
2920
+ (k = this.onerror) == null || k.call(this, O);
2921
+ }
2922
+ })();
2923
+ return;
2924
+ }
2925
+ const f = new _({
2926
+ message: `MCP HTTP Transport Error: Unexpected content type: ${h}`
2927
+ });
2928
+ throw (l = this.onerror) == null || l.call(this, f), f;
2929
+ } catch (p) {
2930
+ throw (c = this.onerror) == null || c.call(this, p), p;
2931
+ }
2932
+ };
2933
+ await e();
2934
+ }
2935
+ getNextReconnectionDelay(t) {
2936
+ const {
2937
+ initialReconnectionDelay: e,
2938
+ reconnectionDelayGrowFactor: r,
2939
+ maxReconnectionDelay: s
2940
+ } = this.reconnectionOptions;
2941
+ return Math.min(
2942
+ e * Math.pow(r, t),
2943
+ s
2944
+ );
2945
+ }
2946
+ scheduleInboundSseReconnection() {
2947
+ var t;
2948
+ const { maxRetries: e } = this.reconnectionOptions;
2949
+ if (e > 0 && this.inboundReconnectAttempts >= e) {
2950
+ (t = this.onerror) == null || t.call(
2951
+ this,
2952
+ new _({
2953
+ message: `MCP HTTP Transport Error: Maximum reconnection attempts (${e}) exceeded.`
2954
+ })
2955
+ );
2956
+ return;
2957
+ }
2958
+ const r = this.getNextReconnectionDelay(this.inboundReconnectAttempts);
2959
+ this.inboundReconnectAttempts += 1, setTimeout(async () => {
2960
+ var s;
2961
+ (s = this.abortController) != null && s.signal.aborted || await this.openInboundSse(!1, this.lastInboundEventId);
2962
+ }, r);
2963
+ }
2964
+ // Open optional inbound SSE stream; best-effort and resumable
2965
+ async openInboundSse(t = !1, e) {
2966
+ var r, s, n, a, i, u;
2967
+ try {
2968
+ const l = await this.commonHeaders({
2969
+ Accept: "text/event-stream"
2970
+ });
2971
+ e && (l["last-event-id"] = e);
2972
+ const c = await fetch(this.url.href, {
2973
+ method: "GET",
2974
+ headers: l,
2975
+ signal: (r = this.abortController) == null ? void 0 : r.signal,
2976
+ redirect: this.redirectMode
2977
+ }), p = c.headers.get("mcp-session-id");
2978
+ if (p && (this.sessionId = p), c.status === 401 && this.authProvider && !t) {
2979
+ this.resourceMetadataUrl = te(c);
2980
+ try {
2981
+ if (await re(this.authProvider, {
2982
+ serverUrl: this.url,
2983
+ resourceMetadataUrl: this.resourceMetadataUrl
2984
+ }) !== "AUTHORIZED") {
2985
+ const h = new ee();
2986
+ (s = this.onerror) == null || s.call(this, h);
2987
+ return;
2988
+ }
2989
+ } catch (y) {
2990
+ (n = this.onerror) == null || n.call(this, y);
2991
+ return;
2992
+ }
2993
+ return this.openInboundSse(!0, e);
2994
+ }
2995
+ if (c.status === 405)
2996
+ return;
2997
+ if (!c.ok || !c.body) {
2998
+ const y = new _({
2999
+ message: `MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`
3000
+ });
3001
+ (a = this.onerror) == null || a.call(this, y);
3002
+ return;
3003
+ }
3004
+ const d = c.body.pipeThrough(new TextDecoderStream()).pipeThrough(new he()).getReader(), m = async () => {
3005
+ var y, h, f, v;
3006
+ try {
3007
+ for (; ; ) {
3008
+ const { done: b, value: T } = await d.read();
3009
+ if (b) return;
3010
+ const { event: A, data: M, id: k } = T;
3011
+ if (k && (this.lastInboundEventId = k), A === "message")
3012
+ try {
3013
+ const O = V.parse(JSON.parse(M));
3014
+ (y = this.onmessage) == null || y.call(this, O);
3015
+ } catch (O) {
3016
+ const H = new _({
3017
+ message: "MCP HTTP Transport Error: Failed to parse message",
3018
+ cause: O
3019
+ });
3020
+ (h = this.onerror) == null || h.call(this, H);
3021
+ }
3022
+ }
3023
+ } catch (b) {
3024
+ if (b instanceof Error && b.name === "AbortError")
3025
+ return;
3026
+ (f = this.onerror) == null || f.call(this, b), (v = this.abortController) != null && v.signal.aborted || this.scheduleInboundSseReconnection();
3027
+ }
3028
+ };
3029
+ this.inboundSseConnection = {
3030
+ close: () => d.cancel()
3031
+ }, this.inboundReconnectAttempts = 0, m();
3032
+ } catch (l) {
3033
+ if (l instanceof Error && l.name === "AbortError")
3034
+ return;
3035
+ (i = this.onerror) == null || i.call(this, l), (u = this.abortController) != null && u.signal.aborted || this.scheduleInboundSseReconnection();
3036
+ }
3037
+ }
3038
+ };
3039
+ function Xs(t) {
3040
+ switch (t.type) {
3041
+ case "sse":
3042
+ return new Gs(t);
3043
+ case "http":
3044
+ return new Ks(t);
3045
+ default:
3046
+ throw new _({
3047
+ message: "Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."
3048
+ });
3049
+ }
3050
+ }
3051
+ function Qs(t) {
3052
+ return "start" in t && typeof t.start == "function" && "send" in t && typeof t.send == "function" && "close" in t && typeof t.close == "function";
3053
+ }
3054
+ var Ys = "1.0.0";
3055
+ function je({
3056
+ output: t
3057
+ }) {
3058
+ const e = t;
3059
+ return !("content" in e) || !Array.isArray(e.content) ? { type: "json", value: e } : { type: "content", value: e.content.map(
3060
+ (s) => s.type === "text" && "text" in s ? { type: "text", text: s.text } : s.type === "image" && "data" in s && "mimeType" in s ? {
3061
+ type: "image-data",
3062
+ data: s.data,
3063
+ mediaType: s.mimeType
3064
+ } : { type: "text", text: JSON.stringify(s) }
3065
+ ) };
3066
+ }
3067
+ async function en(t) {
3068
+ const e = new tn(t);
3069
+ return await e.init(), e;
3070
+ }
3071
+ var tn = class {
3072
+ constructor({
3073
+ transport: t,
3074
+ name: e = "ai-sdk-mcp-client",
3075
+ version: r = Ys,
3076
+ onUncaughtError: s,
3077
+ capabilities: n
3078
+ }) {
3079
+ this.requestMessageId = 0, this.responseHandlers = /* @__PURE__ */ new Map(), this.serverCapabilities = {}, this.isClosed = !0, this.onUncaughtError = s, this.clientCapabilities = n ?? {}, Qs(t) ? this.transport = t : this.transport = Xs(t), this.transport.onclose = () => this.onClose(), this.transport.onerror = (a) => this.onError(a), this.transport.onmessage = (a) => {
3080
+ if ("method" in a) {
3081
+ "id" in a ? this.onRequestMessage(a) : this.onError(
3082
+ new _({
3083
+ message: "Unsupported message type"
3084
+ })
3085
+ );
3086
+ return;
3087
+ }
3088
+ this.onResponse(a);
3089
+ }, this.clientInfo = {
3090
+ name: e,
3091
+ version: r
3092
+ };
3093
+ }
3094
+ async init() {
3095
+ try {
3096
+ await this.transport.start(), this.isClosed = !1;
3097
+ const t = await this.request({
3098
+ request: {
3099
+ method: "initialize",
3100
+ params: {
3101
+ protocolVersion: D,
3102
+ capabilities: this.clientCapabilities,
3103
+ clientInfo: this.clientInfo
3104
+ }
3105
+ },
3106
+ resultSchema: ss
3107
+ });
3108
+ if (t === void 0)
3109
+ throw new _({
3110
+ message: "Server sent invalid initialize result"
3111
+ });
3112
+ if (!Yr.includes(t.protocolVersion))
3113
+ throw new _({
3114
+ message: `Server's protocol version is not supported: ${t.protocolVersion}`
3115
+ });
3116
+ return this.serverCapabilities = t.capabilities, await this.notification({
3117
+ method: "notifications/initialized"
3118
+ }), this;
3119
+ } catch (t) {
3120
+ throw await this.close(), t;
3121
+ }
3122
+ }
3123
+ async close() {
3124
+ var t;
3125
+ this.isClosed || (await ((t = this.transport) == null ? void 0 : t.close()), this.onClose());
3126
+ }
3127
+ assertCapability(t) {
3128
+ switch (t) {
3129
+ case "initialize":
3130
+ break;
3131
+ case "tools/list":
3132
+ case "tools/call":
3133
+ if (!this.serverCapabilities.tools)
3134
+ throw new _({
3135
+ message: "Server does not support tools"
3136
+ });
3137
+ break;
3138
+ case "resources/list":
3139
+ case "resources/read":
3140
+ case "resources/templates/list":
3141
+ if (!this.serverCapabilities.resources)
3142
+ throw new _({
3143
+ message: "Server does not support resources"
3144
+ });
3145
+ break;
3146
+ case "prompts/list":
3147
+ case "prompts/get":
3148
+ if (!this.serverCapabilities.prompts)
3149
+ throw new _({
3150
+ message: "Server does not support prompts"
3151
+ });
3152
+ break;
3153
+ default:
3154
+ throw new _({
3155
+ message: `Unsupported method: ${t}`
3156
+ });
3157
+ }
3158
+ }
3159
+ async request({
3160
+ request: t,
3161
+ resultSchema: e,
3162
+ options: r
3163
+ }) {
3164
+ return new Promise((s, n) => {
3165
+ if (this.isClosed)
3166
+ return n(
3167
+ new _({
3168
+ message: "Attempted to send a request from a closed client"
3169
+ })
3170
+ );
3171
+ this.assertCapability(t.method);
3172
+ const a = r?.signal;
3173
+ a?.throwIfAborted();
3174
+ const i = this.requestMessageId++, u = {
3175
+ ...t,
3176
+ jsonrpc: "2.0",
3177
+ id: i
3178
+ }, l = () => {
3179
+ this.responseHandlers.delete(i);
3180
+ };
3181
+ this.responseHandlers.set(i, (c) => {
3182
+ if (a?.aborted)
3183
+ return n(
3184
+ new _({
3185
+ message: "Request was aborted",
3186
+ cause: a.reason
3187
+ })
3188
+ );
3189
+ if (c instanceof Error)
3190
+ return n(c);
3191
+ try {
3192
+ const p = e.parse(c.result);
3193
+ s(p);
3194
+ } catch (p) {
3195
+ const g = new _({
3196
+ message: "Failed to parse server response",
3197
+ cause: p
3198
+ });
3199
+ n(g);
3200
+ }
3201
+ }), this.transport.send(u).catch((c) => {
3202
+ l(), n(c);
3203
+ });
3204
+ });
3205
+ }
3206
+ async listTools({
3207
+ params: t,
3208
+ options: e
3209
+ } = {}) {
3210
+ return this.request({
3211
+ request: { method: "tools/list", params: t },
3212
+ resultSchema: os,
3213
+ options: e
3214
+ });
3215
+ }
3216
+ async callTool({
3217
+ name: t,
3218
+ args: e,
3219
+ options: r
3220
+ }) {
3221
+ try {
3222
+ return this.request({
3223
+ request: { method: "tools/call", params: { name: t, arguments: e } },
3224
+ resultSchema: cs,
3225
+ options: {
3226
+ signal: r?.abortSignal
3227
+ }
3228
+ });
3229
+ } catch (s) {
3230
+ throw s;
3231
+ }
3232
+ }
3233
+ async listResourcesInternal({
3234
+ params: t,
3235
+ options: e
3236
+ } = {}) {
3237
+ try {
3238
+ return this.request({
3239
+ request: { method: "resources/list", params: t },
3240
+ resultSchema: is,
3241
+ options: e
3242
+ });
3243
+ } catch (r) {
3244
+ throw r;
3245
+ }
3246
+ }
3247
+ async readResourceInternal({
3248
+ uri: t,
3249
+ options: e
3250
+ }) {
3251
+ try {
3252
+ return this.request({
3253
+ request: { method: "resources/read", params: { uri: t } },
3254
+ resultSchema: ds,
3255
+ options: e
3256
+ });
3257
+ } catch (r) {
3258
+ throw r;
3259
+ }
3260
+ }
3261
+ async listResourceTemplatesInternal({
3262
+ options: t
3263
+ } = {}) {
3264
+ try {
3265
+ return this.request({
3266
+ request: { method: "resources/templates/list" },
3267
+ resultSchema: us,
3268
+ options: t
3269
+ });
3270
+ } catch (e) {
3271
+ throw e;
3272
+ }
3273
+ }
3274
+ async listPromptsInternal({
3275
+ params: t,
3276
+ options: e
3277
+ } = {}) {
3278
+ try {
3279
+ return this.request({
3280
+ request: { method: "prompts/list", params: t },
3281
+ resultSchema: ms,
3282
+ options: e
3283
+ });
3284
+ } catch (r) {
3285
+ throw r;
3286
+ }
3287
+ }
3288
+ async getPromptInternal({
3289
+ name: t,
3290
+ args: e,
3291
+ options: r
3292
+ }) {
3293
+ try {
3294
+ return this.request({
3295
+ request: { method: "prompts/get", params: { name: t, arguments: e } },
3296
+ resultSchema: gs,
3297
+ options: r
3298
+ });
3299
+ } catch (s) {
3300
+ throw s;
3301
+ }
3302
+ }
3303
+ async notification(t) {
3304
+ const e = {
3305
+ ...t,
3306
+ jsonrpc: "2.0"
3307
+ };
3308
+ await this.transport.send(e);
3309
+ }
3310
+ /**
3311
+ * Returns a set of AI SDK tools from the MCP server.
3312
+ * This fetches tool definitions and wraps them with execute functions.
3313
+ * @returns A record of tool names to their implementations
3314
+ */
3315
+ async tools({
3316
+ schemas: t = "automatic"
3317
+ } = {}) {
3318
+ const e = await this.listTools();
3319
+ return this.toolsFromDefinitions(e, {
3320
+ schemas: t
3321
+ });
3322
+ }
3323
+ /**
3324
+ * Creates AI SDK tools from tool definitions without fetching from the server.
3325
+ */
3326
+ toolsFromDefinitions(t, { schemas: e = "automatic" } = {}) {
3327
+ var r, s;
3328
+ const n = {};
3329
+ for (const {
3330
+ name: a,
3331
+ title: i,
3332
+ description: u,
3333
+ inputSchema: l,
3334
+ annotations: c,
3335
+ _meta: p
3336
+ } of t.tools) {
3337
+ const g = i ?? c?.title;
3338
+ if (e !== "automatic" && !(a in e))
3339
+ continue;
3340
+ const d = this, m = e !== "automatic" ? (r = e[a]) == null ? void 0 : r.outputSchema : void 0, y = async (f, v) => {
3341
+ var b;
3342
+ (b = v?.abortSignal) == null || b.throwIfAborted();
3343
+ const T = await d.callTool({ name: a, args: f, options: v });
3344
+ return m != null ? d.extractStructuredContent(T, m, a) : T;
3345
+ }, h = e === "automatic" ? Vr({
3346
+ description: u,
3347
+ title: g,
3348
+ inputSchema: J({
3349
+ ...l,
3350
+ properties: (s = l.properties) != null ? s : {},
3351
+ additionalProperties: !1
3352
+ }),
3353
+ execute: y,
3354
+ toModelOutput: je
3355
+ }) : {
3356
+ description: u,
3357
+ title: g,
3358
+ inputSchema: e[a].inputSchema,
3359
+ ...m != null ? { outputSchema: m } : {},
3360
+ execute: y,
3361
+ toModelOutput: je
3362
+ };
3363
+ n[a] = { ...h, _meta: p };
3364
+ }
3365
+ return n;
3366
+ }
3367
+ /**
3368
+ * Extracts and validates structuredContent from a tool result.
3369
+ */
3370
+ async extractStructuredContent(t, e, r) {
3371
+ if ("structuredContent" in t && t.structuredContent != null) {
3372
+ const s = await Be({
3373
+ value: t.structuredContent,
3374
+ schema: We(e)
3375
+ });
3376
+ if (!s.success)
3377
+ throw new _({
3378
+ message: `Tool "${r}" returned structuredContent that does not match the expected outputSchema`,
3379
+ cause: s.error
3380
+ });
3381
+ return s.value;
3382
+ }
3383
+ if ("content" in t && Array.isArray(t.content)) {
3384
+ const s = t.content.find((n) => n.type === "text");
3385
+ if (s && "text" in s) {
3386
+ const n = await Fr({
3387
+ text: s.text,
3388
+ schema: e
3389
+ });
3390
+ if (!n.success)
3391
+ throw new _({
3392
+ message: `Tool "${r}" returned content that does not match the expected outputSchema`,
3393
+ cause: n.error
3394
+ });
3395
+ return n.value;
3396
+ }
3397
+ }
3398
+ throw new _({
3399
+ message: `Tool "${r}" did not return structuredContent or parseable text content`
3400
+ });
3401
+ }
3402
+ listResources({
3403
+ params: t,
3404
+ options: e
3405
+ } = {}) {
3406
+ return this.listResourcesInternal({ params: t, options: e });
3407
+ }
3408
+ readResource({
3409
+ uri: t,
3410
+ options: e
3411
+ }) {
3412
+ return this.readResourceInternal({ uri: t, options: e });
3413
+ }
3414
+ listResourceTemplates({
3415
+ options: t
3416
+ } = {}) {
3417
+ return this.listResourceTemplatesInternal({ options: t });
3418
+ }
3419
+ experimental_listPrompts({
3420
+ params: t,
3421
+ options: e
3422
+ } = {}) {
3423
+ return this.listPromptsInternal({ params: t, options: e });
3424
+ }
3425
+ experimental_getPrompt({
3426
+ name: t,
3427
+ arguments: e,
3428
+ options: r
3429
+ }) {
3430
+ return this.getPromptInternal({ name: t, args: e, options: r });
3431
+ }
3432
+ onElicitationRequest(t, e) {
3433
+ if (t !== xe)
3434
+ throw new _({
3435
+ message: "Unsupported request schema. Only ElicitationRequestSchema is supported."
3436
+ });
3437
+ this.elicitationRequestHandler = e;
3438
+ }
3439
+ async onRequestMessage(t) {
3440
+ try {
3441
+ if (t.method !== "elicitation/create") {
3442
+ await this.transport.send({
3443
+ jsonrpc: "2.0",
3444
+ id: t.id,
3445
+ error: {
3446
+ code: -32601,
3447
+ message: `Unsupported request method: ${t.method}`
3448
+ }
3449
+ });
3450
+ return;
3451
+ }
3452
+ if (!this.elicitationRequestHandler) {
3453
+ await this.transport.send({
3454
+ jsonrpc: "2.0",
3455
+ id: t.id,
3456
+ error: {
3457
+ code: -32601,
3458
+ message: "No elicitation handler registered on client"
3459
+ }
3460
+ });
3461
+ return;
3462
+ }
3463
+ const e = xe.safeParse({
3464
+ method: t.method,
3465
+ params: t.params
3466
+ });
3467
+ if (!e.success) {
3468
+ await this.transport.send({
3469
+ jsonrpc: "2.0",
3470
+ id: t.id,
3471
+ error: {
3472
+ code: -32602,
3473
+ message: `Invalid elicitation request: ${e.error.message}`,
3474
+ data: e.error.issues
3475
+ }
3476
+ });
3477
+ return;
3478
+ }
3479
+ try {
3480
+ const r = await this.elicitationRequestHandler(e.data), s = vs.parse(r);
3481
+ await this.transport.send({
3482
+ jsonrpc: "2.0",
3483
+ id: t.id,
3484
+ result: s
3485
+ });
3486
+ } catch (r) {
3487
+ await this.transport.send({
3488
+ jsonrpc: "2.0",
3489
+ id: t.id,
3490
+ error: {
3491
+ code: -32603,
3492
+ message: r instanceof Error ? r.message : "Failed to handle elicitation request"
3493
+ }
3494
+ }), this.onError(r);
3495
+ }
3496
+ } catch (e) {
3497
+ this.onError(e);
3498
+ }
3499
+ }
3500
+ onClose() {
3501
+ if (this.isClosed) return;
3502
+ this.isClosed = !0;
3503
+ const t = new _({
3504
+ message: "Connection closed"
3505
+ });
3506
+ for (const e of this.responseHandlers.values())
3507
+ e(t);
3508
+ this.responseHandlers.clear();
3509
+ }
3510
+ onError(t) {
3511
+ this.onUncaughtError && this.onUncaughtError(t);
3512
+ }
3513
+ onResponse(t) {
3514
+ const e = Number(t.id), r = this.responseHandlers.get(e);
3515
+ if (r === void 0)
3516
+ throw new _({
3517
+ message: `Protocol error: Received a response for an unknown message ID: ${JSON.stringify(
3518
+ t
3519
+ )}`
3520
+ });
3521
+ this.responseHandlers.delete(e), r(
3522
+ "result" in t ? t : new _({
3523
+ message: t.error.message,
3524
+ code: t.error.code,
3525
+ data: t.error.data,
3526
+ cause: t.error
3527
+ })
3528
+ );
3529
+ }
3530
+ };
3531
+ const rn = async (t) => {
3532
+ const e = {};
3533
+ try {
3534
+ const r = await t.listTools();
3535
+ for (const { name: s, description: n, inputSchema: a } of r.tools) {
3536
+ const i = async (u, l) => t.callTool({ name: s, arguments: u }, { signal: l?.abortSignal });
3537
+ e[s] = Ot({
3538
+ description: n,
3539
+ inputSchema: It({
3540
+ ...a,
3541
+ properties: a.properties ?? {},
3542
+ additionalProperties: !1
3543
+ }),
3544
+ execute: i
3545
+ });
3546
+ }
3547
+ return e;
3548
+ } catch (r) {
3549
+ throw r;
3550
+ }
3551
+ };
3552
+ function sn(t) {
3553
+ const e = Object.entries(t);
3554
+ if (e.length === 0)
3555
+ return "";
3556
+ let r = `
3557
+ # 工具调用
3558
+
3559
+ 你可以根据需要调用以下工具:
3560
+
3561
+ <tools>
3562
+ `;
3563
+ return e.forEach(([s, n]) => {
3564
+ const a = n, i = a.description || "无描述", u = a.parameters || a.inputSchema || {};
3565
+ r += `${JSON.stringify({
3566
+ name: s,
3567
+ description: i,
3568
+ parameters: u
3569
+ }, null, 2)}
3570
+ `;
3571
+ }), r += `
3572
+ </tools>
3573
+
3574
+ ## 工具调用格式
3575
+
3576
+ 要调用工具,请使用以下 XML 格式:
3577
+ Thought: [你的思考过程]
3578
+ <tool_call>
3579
+ {"name": "toolName", "arguments": {"arg1": "value1"}}
3580
+ </tool_call>
3581
+
3582
+ 工具执行后,你将收到 <tool_response> 格式的结果。你可以继续思考或调用其他工具。
3583
+
3584
+ ## 使用示例
3585
+
3586
+ 如果用户要求"获取今天的日期",你可以这样调用工具:
3587
+ Thought: 用户想要获取今天的日期,我需要调用日期相关的工具。
3588
+ <tool_call>{"name": "get-today", "arguments": {}}</tool_call>
3589
+
3590
+ 然后等待工具返回结果(Observation),再根据结果给出最终答案。
3591
+
3592
+ ## 任务完成
3593
+
3594
+ 当任务完成或无法继续时,直接给出最终答案即可。
3595
+
3596
+ **重要提示**:
3597
+ - 必须严格按照 XML 格式调用工具
3598
+ - arguments 必须是有效的 JSON 格式
3599
+ - 如果不需要调用工具,直接给出最终答案即可
3600
+ `, r;
3601
+ }
3602
+ function Ne(t, e) {
3603
+ if (!t || typeof t != "string")
3604
+ return null;
3605
+ const r = t.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);
3606
+ if (r)
3607
+ try {
3608
+ const s = r[1].trim(), n = JSON.parse(s), a = n.name || n.action || n.tool, i = n.arguments || n.args || n.input || {};
3609
+ if (a && e[a])
3610
+ return { toolName: a, arguments: i };
3611
+ } catch {
3612
+ }
3613
+ return null;
3614
+ }
3615
+ const nn = {
3616
+ openai: $t,
3617
+ deepseek: jt
3618
+ };
3619
+ class xn {
3620
+ constructor({ llmConfig: e, mcpServers: r }) {
3621
+ if (this.mcpServers = {}, this.mcpClients = {}, this.mcpTools = {}, this.ignoreToolnames = [], this.responseMessages = [], this.useReActMode = !1, !e)
3622
+ throw new Error("llmConfig is required to initialize AgentModelProvider");
3623
+ if (this.mcpServers = r || {}, this.mcpClients = {}, this.mcpTools = {}, e.llm)
3624
+ this.llm = e.llm;
3625
+ else if (e.providerType) {
3626
+ const s = e.providerType;
3627
+ let n;
3628
+ typeof s == "string" ? n = nn[s] : n = s, this.llm = n({
3629
+ apiKey: e.apiKey,
3630
+ baseURL: e.baseURL
3631
+ });
3632
+ } else
3633
+ throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided");
3634
+ this.useReActMode = e.useReActMode ?? !1;
3635
+ }
3636
+ /** 创建一个 ai-sdk的 mcpClient, 创建失败则返回 null */
3637
+ async _createOneClient(e) {
3638
+ try {
3639
+ let r;
3640
+ if ("type" in e && e.type.toLocaleLowerCase() === "streamablehttp") {
3641
+ const n = e, a = n.headers ? { headers: n.headers } : void 0;
3642
+ r = new se(new URL(n.url), { requestInit: a });
3643
+ } else if ("type" in e && e.type === "sse") {
3644
+ const n = e, a = n.headers ? { headers: n.headers } : void 0;
3645
+ r = new ne(new URL(n.url), { requestInit: a });
3646
+ } else "type" in e && e.type === "extension" ? r = new zt(e.sessionId) : "transport" in e ? r = e.transport : r = e;
3647
+ if (e.useAISdkClient ?? !1) {
3648
+ const n = await en({ transport: r });
3649
+ return n.__transport__ = r, n;
3650
+ } else {
3651
+ const n = new qt(
3652
+ { name: "mcp-web-client", version: "1.0.0" },
3653
+ { capabilities: { roots: { listChanged: !0 }, sampling: {}, elicitation: {} } }
3654
+ );
3655
+ return await n.connect(r), n.__transport__ = r, n;
3656
+ }
3657
+ } catch (r) {
3658
+ return this.onError && this.onError(r?.message || "Failed to create MCP client", r), console.error("Failed to create MCP client", e, r), null;
3659
+ }
3660
+ }
3661
+ /** 关闭一个 mcpClient */
3662
+ async _closeOneClient(e) {
3663
+ try {
3664
+ const r = e.__transport__;
3665
+ if (r && r instanceof Ut || r && r instanceof gt)
3666
+ return;
3667
+ await r?.terminateSession?.(), await r?.close?.(), await e?.close?.();
3668
+ } catch {
3669
+ }
3670
+ }
3671
+ /** 创建所有 mcpClients */
3672
+ async _createMpcClients() {
3673
+ const e = Object.entries(this.mcpServers), r = await Promise.all(
3674
+ e.map(async ([s, n]) => {
3675
+ const a = await this._createOneClient(n);
3676
+ return { serverName: s, client: a };
3677
+ })
3678
+ );
3679
+ this.mcpClients = {}, r.forEach(({ serverName: s, client: n }) => {
3680
+ this.mcpClients[s] = n;
3681
+ });
3682
+ }
3683
+ /** 兼容两种 client 类型的 tools 获取方法 */
3684
+ async _getClientTools(e, r) {
3685
+ if (!e)
3686
+ return null;
3687
+ try {
3688
+ return typeof e.tools == "function" ? await e.tools() : await rn(e);
3689
+ } catch (s) {
3690
+ return this.onError && this.onError(s?.message || `Failed to query tools for ${r}`, s), console.error(`Failed to query tools for ${r}`, s), null;
3691
+ }
3692
+ }
3693
+ /** 查询所有 mcpClients 的 tools, 失败则保存为null */
3694
+ async _createMpcTools() {
3695
+ const e = Object.entries(this.mcpClients), r = await Promise.all(
3696
+ e.map(async ([s, n]) => {
3697
+ const a = await this._getClientTools(n, s);
3698
+ return { serverName: s, tools: a };
3699
+ })
3700
+ );
3701
+ this.mcpTools = {}, r.forEach(({ serverName: s, tools: n }) => {
3702
+ const a = n && typeof n == "object" ? n : {};
3703
+ this.mcpTools[s] = a;
3704
+ });
3705
+ }
3706
+ /** 关闭所有的 clients */
3707
+ async closeAll() {
3708
+ await Promise.all(
3709
+ Object.values(this.mcpClients).map(async (e) => {
3710
+ try {
3711
+ await this._closeOneClient(e);
3712
+ } catch (r) {
3713
+ this.onError && this.onError(r?.message || "Failed to close client", r), console.error("Failed to close client", r);
3714
+ }
3715
+ })
3716
+ );
3717
+ }
3718
+ /** 创建所有的 mcpClients,并更新它们的tools */
3719
+ async initClientsAndTools() {
3720
+ await this._createMpcClients(), await this._createMpcTools(), this.onUpdatedTools?.();
3721
+ }
3722
+ /** 仅刷新已连接 clients 的 tools(不重建 client,适合工具目录动态变化场景) */
3723
+ async refreshTools() {
3724
+ await this._createMpcTools(), this.onUpdatedTools?.();
3725
+ }
3726
+ /** 全量更新所有的 mcpServers */
3727
+ async updateMcpServers(e) {
3728
+ await this.closeAll(), this.mcpServers = e || this.mcpServers, await this.initClientsAndTools();
3729
+ }
3730
+ /** 插入一个新的mcpServer,如果已经存在则返回false */
3731
+ async insertMcpServer(e, r) {
3732
+ if (this.mcpServers[e])
3733
+ return !1;
3734
+ const s = await this._createOneClient(r);
3735
+ if (!s)
3736
+ return this.onError?.(`Failed to create MCP client: ${e}`), null;
3737
+ this.mcpClients[e] = s;
3738
+ const n = await this._getClientTools(s, e);
3739
+ return this.mcpTools[e] = n && typeof n == "object" ? n : {}, this.mcpServers[e] = r, this.onUpdatedTools?.(), s;
3740
+ }
3741
+ /** 通过服务器名称删除mcpServer: mcpServers mcpClients mcpTools ignoreToolnames */
3742
+ async removeMcpServer(e) {
3743
+ if (!this.mcpServers[e])
3744
+ return;
3745
+ delete this.mcpServers[e];
3746
+ const r = this.mcpClients[e];
3747
+ delete this.mcpClients[e];
3748
+ try {
3749
+ await this._closeOneClient(r);
3750
+ } catch {
3751
+ }
3752
+ const s = this.mcpTools[e];
3753
+ delete this.mcpTools[e], s && Object.keys(s).forEach((n) => {
3754
+ this.ignoreToolnames = this.ignoreToolnames.filter((a) => a !== n);
3755
+ }), this.onUpdatedTools?.();
3756
+ }
3757
+ /** 创建临时允许调用的 tools 集合,合并 mcpTools 与 extraTool */
3758
+ _tempMergeTools(e = {}, r = !0) {
3759
+ const s = Object.values(this.mcpTools).reduce(
3760
+ (n, a) => ({ ...n, ...a }),
3761
+ {}
3762
+ );
3763
+ return Object.assign(s, e), r && this.ignoreToolnames.forEach((n) => {
3764
+ delete s[n];
3765
+ }), s;
3766
+ }
3767
+ /** 获取当前激活的 tools 名称列表(过滤 ignoreToolnames) */
3768
+ _getActiveToolNames(e) {
3769
+ return Object.keys(e).filter((r) => !this.ignoreToolnames.includes(r));
3770
+ }
3771
+ /** 生成 ReAct 模式的系统提示词(包含工具描述) */
3772
+ _generateReActSystemPrompt(e, r, s) {
3773
+ const n = sn(e);
3774
+ return s ? `${s}${n}` : `你是一个智能助手,可以通过调用工具来完成任务。
3775
+ ${n}`;
3776
+ }
3777
+ /** 执行 ReAct 模式下的工具调用 */
3778
+ async _executeReActToolCall(e, r, s) {
3779
+ const n = s[e];
3780
+ if (!n)
3781
+ return { success: !1, error: `工具 ${e} 不存在` };
3782
+ try {
3783
+ const a = n, i = a.execute || a.call;
3784
+ return typeof i != "function" ? { success: !1, error: `工具 ${e} 没有可执行的函数` } : { success: !0, result: await i(r, {}) };
3785
+ } catch (a) {
3786
+ return { success: !1, error: a?.message || String(a) || "工具执行失败" };
3787
+ }
3788
+ }
3789
+ /** ReAct 模式的对话实现 */
3790
+ async _chatReAct(e, { model: r, maxSteps: s = 5, ...n }) {
3791
+ if (!this.llm)
3792
+ throw new Error("LLM is not initialized");
3793
+ await this.initClientsAndTools();
3794
+ const a = this._tempMergeTools(n.tools);
3795
+ if (Object.keys(a).length === 0)
3796
+ return this._chat(e, { model: r, maxSteps: s, ...n });
3797
+ let u = [];
3798
+ n.message && !n.messages ? u.push({ role: "user", content: n.message }) : n.messages ? u = [...n.messages] : u = [...this.responseMessages];
3799
+ const l = typeof r == "string" ? r : r?.modelId || "default-model", p = { role: "system", content: this._generateReActSystemPrompt(a, l, n.system) }, g = u[0]?.role === "system" ? u : [p, ...u];
3800
+ return e === ie ? this._chatReActStream(g, a, l, s, n) : this._chatReActNonStream(g, a, l, s, n);
3801
+ }
3802
+ /**
3803
+ * 检查消息内容是否包含图片
3804
+ * @param content 消息内容
3805
+ * @returns 是否包含图片
3806
+ */
3807
+ _messageHasImage(e) {
3808
+ return e && Array.isArray(e) ? e.some((r) => r && r.type === "image") : !1;
3809
+ }
3810
+ /**
3811
+ * 从消息中移除图片,但保留文本内容
3812
+ * @param message 原始消息
3813
+ * @returns 移除图片后的消息(如果只有图片没有文本,返回 null)
3814
+ */
3815
+ _removeImageFromMessage(e) {
3816
+ if (!e || !e.content)
3817
+ return null;
3818
+ if (!Array.isArray(e.content))
3819
+ return e;
3820
+ const r = e.content.filter((s) => s && s.type !== "image");
3821
+ return r.length === 0 ? null : {
3822
+ ...e,
3823
+ content: r
3824
+ };
3825
+ }
3826
+ /**
3827
+ * 构建用于模型调用的消息列表
3828
+ * 策略:保留所有文本消息,仅限制图片数量(类似 magentic-ui 的 maybe_remove_old_screenshots)
3829
+ *
3830
+ * @param systemMessage 系统提示词
3831
+ * @param allMessages 所有消息历史(包括初始消息和后续对话)
3832
+ * @param maxImages 最多保留的图片数量(默认3张)
3833
+ * @returns 构建好的消息列表
3834
+ */
3835
+ _buildMessagesForModel(e, r, s = 3) {
3836
+ const n = [];
3837
+ e && n.push(e);
3838
+ let a = 0;
3839
+ const i = [];
3840
+ for (let u = r.length - 1; u >= 0; u--) {
3841
+ const l = r[u];
3842
+ if (this._messageHasImage(l.content))
3843
+ if (a < s)
3844
+ i.unshift(l), a++;
3845
+ else {
3846
+ const p = this._removeImageFromMessage(l);
3847
+ p && i.unshift(p);
3848
+ }
3849
+ else
3850
+ i.unshift(l);
3851
+ }
3852
+ return n.push(...i), n;
3853
+ }
3854
+ /** ReAct 模式非流式对话 */
3855
+ async _chatReActNonStream(e, r, s, n, a) {
3856
+ let i = [...e];
3857
+ const u = e[0]?.role === "system" ? e[0] : null, l = u ? e.slice(1) : e;
3858
+ let c = 0;
3859
+ const p = a.maxImages ?? 3;
3860
+ for (; c < n; ) {
3861
+ c++;
3862
+ const d = this._buildMessagesForModel(u, l, p), { tools: m, ...y } = a, f = (await Pe({
3863
+ // @ts-ignore ProviderV2 是所有llm的父类,在每一个具体的llm类都有一个选择model的函数用法
3864
+ model: this.llm(s),
3865
+ messages: d,
3866
+ ...y
3867
+ })).text, v = { role: "assistant", content: f };
3868
+ l.push(v), i.push(v);
3869
+ const b = Ne(f, r);
3870
+ if (!b)
3871
+ return this.responseMessages = i, {
3872
+ text: f,
3873
+ response: { messages: i }
3874
+ };
3875
+ const T = await this._executeReActToolCall(b.toolName, b.arguments, r), k = {
3876
+ role: "user",
3877
+ content: `<tool_response>
3878
+ ${T.success ? JSON.stringify(T.result) : `工具执行失败 - ${T.error}`}
3879
+ </tool_response>`
3880
+ };
3881
+ l.push(k), i.push(k);
3882
+ }
3883
+ return this.responseMessages = i, {
3884
+ text: i[i.length - 2]?.content || "",
3885
+ response: { messages: i }
3886
+ };
3887
+ }
3888
+ /** ReAct 模式流式对话 */
3889
+ _chatReActStream(e, r, s, n, a) {
3890
+ const i = this, u = this.llm(s);
3891
+ let l, c;
3892
+ const p = new Promise((d, m) => {
3893
+ l = d, c = m;
3894
+ });
3895
+ return {
3896
+ fullStream: new ReadableStream({
3897
+ async start(d) {
3898
+ let m = [...e];
3899
+ const y = e[0]?.role === "system" ? e[0] : null, h = y ? e.slice(1) : [...e];
3900
+ let f = 0, v = "";
3901
+ const b = a.maxImages ?? 3;
3902
+ d.enqueue({ type: "start" }), d.enqueue({ type: "start-step" });
3903
+ try {
3904
+ for (; f < n; ) {
3905
+ f++;
3906
+ const T = i._buildMessagesForModel(y, h, b), { tools: A, ...M } = a;
3907
+ delete M.system, delete M.onFinish;
3908
+ const k = await ie({
3909
+ ...M,
3910
+ model: u,
3911
+ messages: T
3912
+ });
3913
+ let O = "";
3914
+ for await (const P of k.fullStream)
3915
+ P.type === "text-delta" ? (O += P.text || "", d.enqueue({
3916
+ type: "text-delta",
3917
+ text: P.text
3918
+ })) : P.type === "text-start" ? d.enqueue({ type: "text-start" }) : P.type === "text-end" || P.type === "finish-step" || P.type === "finish" || P.type === "start" || P.type === "start-step" || d.enqueue(P);
3919
+ v += O;
3920
+ const H = { role: "assistant", content: v };
3921
+ h.push(H), m.push(H);
3922
+ const I = Ne(v, r);
3923
+ if (!I) {
3924
+ d.enqueue({ type: "text-end" }), d.enqueue({ type: "finish-step" }), d.enqueue({ type: "finish" }), d.close(), i.responseMessages = m, l({ messages: m });
3925
+ return;
3926
+ }
3927
+ if (I.toolName === "computer" && I.arguments?.action === "terminate") {
3928
+ d.enqueue({ type: "text-end" }), d.enqueue({ type: "finish-step" }), d.enqueue({ type: "finish" }), d.close(), i.responseMessages = m, l({ messages: m });
3929
+ return;
3930
+ }
3931
+ const j = `react-${Date.now()}`;
3932
+ d.enqueue({
3933
+ type: "tool-input-start",
3934
+ id: j,
3935
+ toolName: I.toolName
3936
+ });
3937
+ const z = JSON.stringify(I.arguments, null, 2);
3938
+ d.enqueue({
3939
+ type: "tool-input-delta",
3940
+ id: j,
3941
+ delta: z
3942
+ }), d.enqueue({
3943
+ type: "tool-input-end",
3944
+ id: j
3945
+ }), d.enqueue({
3946
+ type: "tool-call",
3947
+ toolCallId: j,
3948
+ toolName: I.toolName,
3949
+ input: I.arguments
3950
+ });
3951
+ const x = await i._executeReActToolCall(I.toolName, I.arguments, r);
3952
+ let B, N = x.result;
3953
+ if (x.success && x.result && typeof x.result == "object" && x.result.screenshot) {
3954
+ B = x.result.screenshot;
3955
+ const { screenshot: P, ...G } = x.result;
3956
+ N = G;
3957
+ }
3958
+ let F = "";
3959
+ if (x.success) {
3960
+ N && Array.isArray(N.content) && N.content.length > 0 && N.content[0].text ? F = N.content[0].text : F = JSON.stringify(N);
3961
+ let P = `<tool_response>
3962
+ ${F}
3963
+ </tool_response>`;
3964
+ B && (P += `
3965
+ 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`), d.enqueue({
3966
+ type: "tool-result",
3967
+ toolCallId: j,
3968
+ result: P
3969
+ });
3970
+ const G = B ? {
3971
+ role: "user",
3972
+ content: [
3973
+ { type: "text", text: P },
3974
+ { type: "image", image: B }
3975
+ ]
3976
+ } : {
3977
+ role: "user",
3978
+ content: P
3979
+ };
3980
+ h.push(G), m.push(G), v = "";
3981
+ } else
3982
+ F = `工具执行失败 - ${x.error}`, d.enqueue({
3983
+ type: "tool-error",
3984
+ toolCallId: j,
3985
+ input: I.arguments,
3986
+ error: { message: F }
3987
+ });
3988
+ }
3989
+ d.enqueue({ type: "text-end" }), d.enqueue({ type: "finish-step" }), d.enqueue({ type: "finish" }), d.close(), i.responseMessages = m, l({ messages: m });
3990
+ } catch (T) {
3991
+ d.error(T), c(T);
3992
+ }
3993
+ }
3994
+ }),
3995
+ response: p
3996
+ };
3997
+ }
3998
+ async _chat(e, { model: r, maxSteps: s = 5, ...n }) {
3999
+ if (this.useReActMode)
4000
+ return this._chatReAct(e, { model: r, maxSteps: s, ...n });
4001
+ if (!this.llm)
4002
+ throw new Error("LLM is not initialized");
4003
+ await this.initClientsAndTools();
4004
+ const a = n.tools || {}, i = this._tempMergeTools(a, !1), u = () => {
4005
+ const m = this._tempMergeTools(a, !1);
4006
+ Object.entries(m).forEach(([y, h]) => {
4007
+ i[y] = h;
4008
+ }), Object.keys(i).forEach((y) => {
4009
+ y in m || delete i[y];
4010
+ });
4011
+ }, l = n.prepareStep, c = async (m) => {
4012
+ u();
4013
+ const y = this._getActiveToolNames(i), h = typeof l == "function" ? await l(m) : void 0, f = h && typeof h == "object" ? h : {};
4014
+ return {
4015
+ ...f,
4016
+ activeTools: Array.isArray(f.activeTools) ? f.activeTools.filter((v) => y.includes(v)) : y
4017
+ };
4018
+ }, p = {
4019
+ // @ts-ignore ProviderV2 是所有llm的父类, 在每一个具体的llm 类都有一个选择model的函数用法
4020
+ model: this.llm(r),
4021
+ stopWhen: xt(s),
4022
+ ...n,
4023
+ tools: i,
4024
+ prepareStep: c,
4025
+ activeTools: this._getActiveToolNames(i)
4026
+ };
4027
+ let g = null;
4028
+ if (n.message && !n.messages)
4029
+ g = { role: "user", content: n.message }, this.responseMessages.push(g), p.messages = [...this.responseMessages];
4030
+ else if (n.messages && n.messages.length > 0) {
4031
+ const m = n.messages[n.messages.length - 1];
4032
+ m.role === "user" && (g = m);
4033
+ }
4034
+ const d = e(p);
4035
+ return d?.response?.then((m) => {
4036
+ const y = m.messages?.[0];
4037
+ g && y?.role !== "user" && this.responseMessages.push(g), this.responseMessages.push(...m.messages);
4038
+ }), d;
4039
+ }
4040
+ async chat(e) {
4041
+ return this._chat(Pe, e);
4042
+ }
4043
+ async chatStream(e) {
4044
+ return this._chat(ie, e);
4045
+ }
4046
+ }
4047
+ export {
4048
+ xn as A,
4049
+ zt as E,
4050
+ _n as W,
4051
+ Sn as a,
4052
+ Pn as b,
4053
+ bn as c,
4054
+ qt as d,
4055
+ Cn as e,
4056
+ Rn as f,
4057
+ rn as g,
4058
+ Mn as h,
4059
+ Tn as i,
4060
+ En as j,
4061
+ Ht as k,
4062
+ An as l,
4063
+ kn as m,
4064
+ Dt as n,
4065
+ In as o,
4066
+ Zt as p,
4067
+ On as s
4068
+ };