@mcp-use/inspector 20.0.0-beta.14 → 20.0.0-beta.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/dist/cdn/inspector.js +76858 -9272
  2. package/dist/cli.js +1 -1
  3. package/dist/server/cdn-shell.js +2 -2
  4. package/dist/server/{chunk-3XD7J5NX.js → chunk-WNQGHIZ3.js} +1 -1
  5. package/dist/server/{chunk-DLHO3Q42.js → chunk-XKCUJ6ZJ.js} +1 -1
  6. package/dist/server/{chunk-N3VXWLT6.js → chunk-ZPGABKXL.js} +1 -1
  7. package/dist/server/cli.js +2 -2
  8. package/dist/server/index.js +3 -3
  9. package/dist/server/middleware.js +3 -3
  10. package/dist/server/version.js +1 -1
  11. package/dist/web/assets/index-Bqfsh_Rp.js +643 -0
  12. package/dist/web/index.html +2 -10
  13. package/package.json +1 -1
  14. package/dist/cdn/AnimatePresence-D1bZ5_-l.js +0 -394
  15. package/dist/cdn/ChatTab-D_2TXR3X.js +0 -6811
  16. package/dist/cdn/CheckboxIndicator-BjF73mGX.js +0 -252
  17. package/dist/cdn/ConnectionSettingsForm-BqH0PcZF.js +0 -929
  18. package/dist/cdn/ConnectionSettingsTab-Duhb1uQP.js +0 -151
  19. package/dist/cdn/ElicitationTab-PEmEDvC5.js +0 -655
  20. package/dist/cdn/FormContext-NtUiZclE.js +0 -135
  21. package/dist/cdn/InspectorContext-BBKCdfmK.js +0 -123
  22. package/dist/cdn/JSONDisplay-BJqMz7Ny.js +0 -324
  23. package/dist/cdn/ListTabHeader-DzmTtN1e.js +0 -89
  24. package/dist/cdn/MCPAppsDebugControls-w5NRWhlZ.js +0 -2174
  25. package/dist/cdn/ManufactOAuthCallback-ChbbjFIT.js +0 -31
  26. package/dist/cdn/MarkdownRenderer-BIsUE0bf.js +0 -3610
  27. package/dist/cdn/McpAppsViewPanel-B3_76u7O.js +0 -56
  28. package/dist/cdn/NotificationsTab-B7uebqMV.js +0 -290
  29. package/dist/cdn/OAuthCallback-CtLoXa3h.js +0 -58
  30. package/dist/cdn/PromptsTab-DpE0XLzk.js +0 -902
  31. package/dist/cdn/ResourcesTab-DQS24z5p.js +0 -566
  32. package/dist/cdn/SamplingTab-ZDeu0CjJ.js +0 -659
  33. package/dist/cdn/ServerMetadataTab-BM3VhSLf.js +0 -244
  34. package/dist/cdn/StatusIcon-Q3n3YRtE.js +0 -65
  35. package/dist/cdn/ToolsTab-LtviZSWA.js +0 -2045
  36. package/dist/cdn/ViewPreview-BwC_tbF_.js +0 -238
  37. package/dist/cdn/WidgetDebugContext-B6yoOVVV.js +0 -314
  38. package/dist/cdn/WidgetWrapper-BlbQAh_X.js +0 -12
  39. package/dist/cdn/basePath-B8HuhIMu.js +0 -25
  40. package/dist/cdn/bell-GrTZcnD2.js +0 -10
  41. package/dist/cdn/browser-DG2Z8392.js +0 -42
  42. package/dist/cdn/brush-CelVvMGp.js +0 -17
  43. package/dist/cdn/button-CB4uOoUV.js +0 -2509
  44. package/dist/cdn/card-BA-DQk-G.js +0 -41
  45. package/dist/cdn/cfWorker-Bxcs9rNe.js +0 -10799
  46. package/dist/cdn/checkbox-kwVa4gRX.js +0 -20
  47. package/dist/cdn/chunk-QUQL4437-XnDcYQEx.js +0 -1508
  48. package/dist/cdn/clock-YMF8Gtw5.js +0 -12
  49. package/dist/cdn/code-C8sN2OGR.js +0 -10
  50. package/dist/cdn/createLucideIcon-BONxC1L5.js +0 -213
  51. package/dist/cdn/dialog-CJGnC5Ag.js +0 -1028
  52. package/dist/cdn/dist-CHKts0NS.js +0 -2307
  53. package/dist/cdn/dist-CTJnCYmk.js +0 -616
  54. package/dist/cdn/external-link-Bo4lQxr1.js +0 -17
  55. package/dist/cdn/eye-pSGG7nvf.js +0 -29
  56. package/dist/cdn/folder-open-aM8CPtBO.js +0 -7
  57. package/dist/cdn/hash-DDs2vE1k.js +0 -33
  58. package/dist/cdn/history-BfUFpL1d.js +0 -17
  59. package/dist/cdn/index-browser-DO-sd0TA.js +0 -1853
  60. package/dist/cdn/info-BMkB68mB.js +0 -19
  61. package/dist/cdn/input-BCpgLXU1.js +0 -9654
  62. package/dist/cdn/inspector-settings-layout-0VDsjeqb.js +0 -4
  63. package/dist/cdn/label-A0UGV8FE.js +0 -60
  64. package/dist/cdn/loader-circle-BKRHJEB7.js +0 -7
  65. package/dist/cdn/manufact-auth-BQMHhbLV.js +0 -423
  66. package/dist/cdn/maximize-2-DdrB_spi.js +0 -21
  67. package/dist/cdn/maximize-hSOCz133.js +0 -21
  68. package/dist/cdn/message-square-D3tKB3uJ.js +0 -7
  69. package/dist/cdn/not-found-BajFyZpp.js +0 -32
  70. package/dist/cdn/play-B1leulYf.js +0 -7
  71. package/dist/cdn/providerMeta-CjGU4rID.js +0 -436
  72. package/dist/cdn/react-BDA-xrgK.js +0 -5421
  73. package/dist/cdn/react-BIs9pQ3H.js +0 -926
  74. package/dist/cdn/refresh-cw-CyvXrS91.js +0 -21
  75. package/dist/cdn/save-CmdEPUAm.js +0 -34
  76. package/dist/cdn/schemaHelpers-DTV38jGq.js +0 -16
  77. package/dist/cdn/select-CCFHjOGk.js +0 -2595
  78. package/dist/cdn/servers-Dd0Vcp81.js +0 -30
  79. package/dist/cdn/shared-CJVHJhag.js +0 -1700
  80. package/dist/cdn/sheet-oyq1mIyg.js +0 -2078
  81. package/dist/cdn/sparkles-CxeZpVtX.js +0 -23
  82. package/dist/cdn/spinner-Be1GlSGX.js +0 -15
  83. package/dist/cdn/square-check-big-C_4wbfwF.js +0 -10
  84. package/dist/cdn/switch-DHXEA_N5.js +0 -665
  85. package/dist/cdn/tabs-subtle-Dubd6Kj8.js +0 -788
  86. package/dist/cdn/telemetry-e4uEESP7.js +0 -208
  87. package/dist/cdn/textarea-CwmI8_uI.js +0 -14
  88. package/dist/cdn/trash-2-BhumJAFE.js +0 -25
  89. package/dist/cdn/useAriaLabelledBy-Cra6w3YY.js +0 -30
  90. package/dist/cdn/useCompositeItem-Dhnm-7el.js +0 -26
  91. package/dist/cdn/useConfig-Dw_6Ztzr.js +0 -235
  92. package/dist/cdn/useSavedRequests-mSIsDd4c.js +0 -51
  93. package/dist/cdn/useViewHostProps-BPApUBaM.js +0 -364
  94. package/dist/cdn/wrench-DvK20LUT.js +0 -7
  95. package/dist/cdn/x-EilKPiCX.js +0 -10
  96. package/dist/cdn/zap-0Wr9QO7N.js +0 -10
  97. package/dist/web/assets/AnimatePresence-FfDQQNFJ.js +0 -9
  98. package/dist/web/assets/ChatTab-BhoU_ges.js +0 -18
  99. package/dist/web/assets/ConnectionSettingsTab-vJcr7uI3.js +0 -1
  100. package/dist/web/assets/ElicitationTab-4my-wtXf.js +0 -1
  101. package/dist/web/assets/FormContext-sV-yByKz.js +0 -1
  102. package/dist/web/assets/ListTabHeader-CrGae306.js +0 -1
  103. package/dist/web/assets/MCPAppsDebugControls-Cd4s9mr1.js +0 -34
  104. package/dist/web/assets/ManufactOAuthCallback-CCRWJhuT.js +0 -1
  105. package/dist/web/assets/MarkdownRenderer-BUDZYHqm.js +0 -47
  106. package/dist/web/assets/McpAppsViewPanel-Cil7Fdy4.js +0 -1
  107. package/dist/web/assets/NotificationsTab-Bl3O5PRb.js +0 -1
  108. package/dist/web/assets/OAuthCallback-CceVgo-9.js +0 -1
  109. package/dist/web/assets/PromptsTab-8lSxb8x-.js +0 -15
  110. package/dist/web/assets/ResourcesTab-DtGfgsPv.js +0 -2
  111. package/dist/web/assets/SamplingTab-XC-DTfOo.js +0 -1
  112. package/dist/web/assets/ServerMetadataTab-C5d_dI3_.js +0 -1
  113. package/dist/web/assets/ToolsTab-DuHPXItY.js +0 -8
  114. package/dist/web/assets/ViewPreview-DXswO9q8.js +0 -1
  115. package/dist/web/assets/WidgetWrapper-cv_BM1bY.js +0 -1
  116. package/dist/web/assets/brush-DX0UZ_pI.js +0 -1
  117. package/dist/web/assets/button-C8Xa2k4x.js +0 -1
  118. package/dist/web/assets/checkbox-DAfdiGl1.js +0 -1
  119. package/dist/web/assets/code-B14rVdNt.js +0 -1
  120. package/dist/web/assets/createLucideIcon-BEHeJH0M.js +0 -1
  121. package/dist/web/assets/dist-C2Y1wkk6.js +0 -21
  122. package/dist/web/assets/index-tu5-QdSJ.js +0 -499
  123. package/dist/web/assets/input-C0OQCUZy.js +0 -1
  124. package/dist/web/assets/inspector-settings-layout-yjKRJDai.js +0 -1
  125. package/dist/web/assets/label-CI7JWQOo.js +0 -1
  126. package/dist/web/assets/maximize-2-Br1WQzT2.js +0 -1
  127. package/dist/web/assets/maximize-CJNgRe6S.js +0 -1
  128. package/dist/web/assets/react-CU_d2d5K.js +0 -1
  129. package/dist/web/assets/refresh-cw-B5iaAZKn.js +0 -1
  130. package/dist/web/assets/save-TM6fvNrt.js +0 -1
  131. package/dist/web/assets/schemaHelpers-DLNTQr_6.js +0 -1
  132. package/dist/web/assets/select-D6jzbLJn.js +0 -1
  133. package/dist/web/assets/shared-c1Yr-wvV.js +0 -1
  134. package/dist/web/assets/sparkles-BGYTDThM.js +0 -1
  135. package/dist/web/assets/tabs-subtle-CHvFXVIA.js +0 -1
  136. package/dist/web/assets/textarea-CRTXuRmE.js +0 -1
  137. package/dist/web/assets/useConfig-9UVqLmR_.js +0 -1
  138. package/dist/web/assets/useViewHostProps-BBoPQYEl.js +0 -1
  139. package/dist/web/assets/zap-BDWHCVHU.js +0 -1
@@ -1,2307 +0,0 @@
1
- import { F as e } from "./cfWorker-Bxcs9rNe.js";
2
- import { r as t } from "./index-browser-DO-sd0TA.js";
3
- //#region ../agent/dist/index.js
4
- var n = class {
5
- disallowedTools;
6
- connectorToolMap = /* @__PURE__ */ new Map();
7
- constructor(e) {
8
- this.disallowedTools = e ?? [];
9
- }
10
- static async createTools(e, n) {
11
- let r = new this(n);
12
- (!e.activeSessions || Object.keys(e.activeSessions).length === 0) && (t.debug("No active sessions found, creating new ones..."), await e.createAllSessions());
13
- let i = e.getAllActiveSessions(), a = Object.values(i).map((e) => e.connector);
14
- return r.createToolsFromConnectors(a);
15
- }
16
- async loadToolsForConnector(e) {
17
- if (this.connectorToolMap.has(e)) {
18
- let n = this.connectorToolMap.get(e);
19
- return t.debug(`Returning ${n.length} existing tools for connector`), n;
20
- }
21
- let n = [];
22
- if (!await this.ensureConnectorInitialized(e)) return [];
23
- for (let t of e.tools) {
24
- let r = this.convertTool(t, e);
25
- r && n.push(r);
26
- }
27
- return this.connectorToolMap.set(e, n), t.debug(`Loaded ${n.length} new tools for connector: ${n.map((e) => e?.name ?? String(e)).join(", ")}`), n;
28
- }
29
- async createToolsFromConnectors(e) {
30
- let n = [];
31
- for (let t of e) {
32
- let e = await this.loadToolsForConnector(t);
33
- n.push(...e);
34
- }
35
- return t.debug(`Available tools: ${n.length}`), n;
36
- }
37
- async loadResourcesForConnector(e) {
38
- let n = [];
39
- if (!await this.ensureConnectorInitialized(e)) return [];
40
- try {
41
- let r = (await e.listAllResources())?.resources || [];
42
- if (this.convertResource) for (let t of r) {
43
- let r = this.convertResource(t, e);
44
- r && n.push(r);
45
- }
46
- t.debug(`Loaded ${n.length} new resources for connector: ${n.map((e) => e?.name ?? String(e)).join(", ")}`);
47
- } catch (e) {
48
- t.warn(`Error loading resources for connector: ${e}`);
49
- }
50
- return n;
51
- }
52
- async loadPromptsForConnector(e) {
53
- let n = [];
54
- if (!await this.ensureConnectorInitialized(e)) return [];
55
- try {
56
- let r = (await e.listPrompts())?.prompts || [];
57
- if (this.convertPrompt) for (let t of r) {
58
- let r = this.convertPrompt(t, e);
59
- r && n.push(r);
60
- }
61
- t.debug(`Loaded ${n.length} new prompts for connector: ${n.map((e) => e?.name ?? String(e)).join(", ")}`);
62
- } catch (e) {
63
- t.warn(`Error loading prompts for connector: ${e}`);
64
- }
65
- return n;
66
- }
67
- async createResourcesFromConnectors(e) {
68
- let n = [];
69
- for (let t of e) {
70
- let e = await this.loadResourcesForConnector(t);
71
- n.push(...e);
72
- }
73
- return t.debug(`Available resources: ${n.length}`), n;
74
- }
75
- async createPromptsFromConnectors(e) {
76
- let n = [];
77
- for (let t of e) {
78
- let e = await this.loadPromptsForConnector(t);
79
- n.push(...e);
80
- }
81
- return t.debug(`Available prompts: ${n.length}`), n;
82
- }
83
- checkConnectorInitialized(e) {
84
- return !!(e.tools && e.tools.length);
85
- }
86
- async ensureConnectorInitialized(e) {
87
- if (!this.checkConnectorInitialized(e)) {
88
- t.debug("Connector doesn't have tools, initializing it");
89
- try {
90
- return await e.initialize(), !0;
91
- } catch (e) {
92
- return t.error(`Error initializing connector: ${e}`), !1;
93
- }
94
- }
95
- return !0;
96
- }
97
- };
98
- function r(e) {
99
- return e.replace(/[^A-Za-z0-9_]+/g, "_").toLowerCase().replace(/^_+|_+$/g, "");
100
- }
101
- var i = class extends n {
102
- usedToolNames = /* @__PURE__ */ new Set();
103
- handlers = /* @__PURE__ */ new Map();
104
- constructor(e = []) {
105
- super(e);
106
- }
107
- async createToolsFromConnectors(e) {
108
- return this.usedToolNames.clear(), this.handlers.clear(), super.createToolsFromConnectors(e);
109
- }
110
- createCallTool() {
111
- let e = this.handlers;
112
- return async (n, r) => {
113
- let i = e.get(n);
114
- if (!i) throw Error(`Unknown tool: ${n}`);
115
- try {
116
- if (i.kind === "tool") return await i.connector.callTool(i.mcpName, r);
117
- if (i.kind === "resource") {
118
- let e = i.resourceUri ?? i.mcpName;
119
- return await i.connector.readResource(e);
120
- }
121
- return await i.connector.getPrompt(i.mcpName, r);
122
- } catch (e) {
123
- throw t.error(`Error executing native MCP tool ${n}: ${e}`), e;
124
- }
125
- };
126
- }
127
- toProviderTools(e) {
128
- return e.map(({ name: e, description: t, inputSchema: n }) => ({
129
- name: e,
130
- description: t,
131
- inputSchema: n
132
- }));
133
- }
134
- reserveName(e, t) {
135
- if (!this.usedToolNames.has(e)) return this.usedToolNames.add(e), e;
136
- if (t) {
137
- let n = `${t}_${e}`;
138
- if (!this.usedToolNames.has(n)) return this.usedToolNames.add(n), n;
139
- let r = 2;
140
- for (; this.usedToolNames.has(`${n}_${r}`);) r++;
141
- let i = `${n}_${r}`;
142
- return this.usedToolNames.add(i), i;
143
- }
144
- let n = 2;
145
- for (; this.usedToolNames.has(`${e}_${n}`);) n++;
146
- let r = `${e}_${n}`;
147
- return this.usedToolNames.add(r), r;
148
- }
149
- register(e, t) {
150
- return this.handlers.set(e.name, t), e;
151
- }
152
- convertTool(e, t) {
153
- if (this.disallowedTools.includes(e.name)) return null;
154
- let n = this.reserveName(e.name ?? "tool"), r = {
155
- name: n,
156
- dispatchKey: n,
157
- description: e.description ?? "",
158
- inputSchema: e.inputSchema ?? {
159
- type: "object",
160
- properties: {}
161
- }
162
- };
163
- return this.register(r, {
164
- connector: t,
165
- kind: "tool",
166
- mcpName: e.name
167
- });
168
- }
169
- convertResource(e, t) {
170
- let n = r(e.name || e.uri) || "resource", i = this.reserveName(n, "resource"), a = {
171
- name: i,
172
- dispatchKey: i,
173
- description: e.description || `Return the content of the resource located at URI ${e.uri}.`,
174
- inputSchema: {
175
- type: "object",
176
- properties: {}
177
- }
178
- };
179
- return this.register(a, {
180
- connector: t,
181
- kind: "resource",
182
- mcpName: e.uri,
183
- resourceUri: e.uri
184
- });
185
- }
186
- convertPrompt(e, t) {
187
- let n = {}, i = [];
188
- if (e.arguments?.length) for (let t of e.arguments) n[t.name] = {
189
- type: "string",
190
- description: t.description
191
- }, t.required !== !1 && i.push(t.name);
192
- let a = r(e.name || "prompt") || "prompt", o = this.reserveName(a, "prompt"), s = {
193
- name: o,
194
- dispatchKey: o,
195
- description: e.description || "",
196
- inputSchema: {
197
- type: "object",
198
- properties: n,
199
- ...i.length > 0 ? { required: i } : {}
200
- }
201
- };
202
- return this.register(s, {
203
- connector: t,
204
- kind: "prompt",
205
- mcpName: e.name
206
- });
207
- }
208
- };
209
- function a(e) {
210
- return {
211
- type: "text",
212
- text: e
213
- };
214
- }
215
- function o(e, t) {
216
- return {
217
- type: "image",
218
- url: `data:${t};base64,${e}`,
219
- mimeType: t,
220
- data: e
221
- };
222
- }
223
- function s(e) {
224
- if (!e || typeof e != "object") return !1;
225
- let t = e;
226
- return Array.isArray(t.content) ? !0 : "structuredContent" in t;
227
- }
228
- function c(e) {
229
- return typeof e == "object" && !!e && e.isError === !0;
230
- }
231
- function l(e) {
232
- if (!e || typeof e != "object") return null;
233
- switch (e.type) {
234
- case "text": {
235
- let t = e.text;
236
- return typeof t == "string" && t.length > 0 ? a(t) : null;
237
- }
238
- case "image": {
239
- let t = e;
240
- if (typeof t.data != "string" || !t.data) return null;
241
- let n = typeof t.mimeType == "string" && t.mimeType ? t.mimeType : "image/png";
242
- return o(t.data, n);
243
- }
244
- case "audio": {
245
- let t = e;
246
- return a(`[audio: ${typeof t.mimeType == "string" && t.mimeType ? t.mimeType : "audio/*"}, base64 omitted (${typeof t.data == "string" ? t.data.length : 0} chars)]`);
247
- }
248
- case "resource": {
249
- let t = e.resource ?? {};
250
- return typeof t.text == "string" && t.text.length > 0 ? a(t.text) : typeof t.blob == "string" && typeof t.mimeType == "string" && t.mimeType.startsWith("image/") ? o(t.blob, t.mimeType) : a(`[resource: ${typeof t.uri == "string" ? t.uri : "<unknown>"} (${typeof t.mimeType == "string" ? t.mimeType : "unknown"})]`);
251
- }
252
- case "resource_link": {
253
- let t = e, n = typeof t.uri == "string" ? t.uri : "<unknown>";
254
- return a(`[resource_link${typeof t.name == "string" ? ` "${t.name}"` : ""}: ${n}]`);
255
- }
256
- default: return a(`[unsupported tool content block: ${String(e.type)}]`);
257
- }
258
- }
259
- function u(e) {
260
- if (e && typeof e == "object" && !Array.isArray(e)) {
261
- let { _meta: t, ...n } = e;
262
- return n;
263
- }
264
- return e;
265
- }
266
- function ee(e) {
267
- let t = u(e);
268
- if (typeof t == "string") return t.length > 0 ? [a(t)] : [];
269
- if (s(t)) {
270
- let e = t, n = [];
271
- if (Array.isArray(e.content)) for (let t of e.content) {
272
- let e = l(t);
273
- e && n.push(e);
274
- }
275
- if (e.structuredContent !== void 0) try {
276
- n.push(a(`structuredContent: ${JSON.stringify(e.structuredContent)}`));
277
- } catch {}
278
- return e.isError && n.unshift(a("[tool reported isError=true]")), n;
279
- }
280
- try {
281
- return [a(JSON.stringify(t))];
282
- } catch {
283
- return [a(String(t))];
284
- }
285
- }
286
- function te(e) {
287
- return e.length === 0 ? "" : e.every((e) => e.type === "text") ? e.map((e) => e.text).join("\n") : null;
288
- }
289
- function d(e) {
290
- let t = ee(e), n = te(t);
291
- return n === null ? t : n;
292
- }
293
- function f(e) {
294
- if (typeof e == "string") return {
295
- text: e,
296
- imageParts: [],
297
- isString: !0
298
- };
299
- let t = [], n = [];
300
- for (let r of e) r.type === "text" ? r.text && t.push(r.text) : r.type === "image" && n.push(r);
301
- return {
302
- text: t.join("\n"),
303
- imageParts: n,
304
- isString: !1
305
- };
306
- }
307
- function p(e, t) {
308
- return `(Tool "${e ?? "<tool>"}" returned the following image${t === 1 ? "" : "s"}:)`;
309
- }
310
- function m(e) {
311
- let t = typeof e.content == "string" ? e.content : Array.isArray(e.content) ? e.content.map((e) => e?.text ?? "").join("\n") : JSON.stringify(e.content ?? "");
312
- return t.trim() ? t.trim() : e.parts?.length ? e.parts.filter((e) => e.type === "text" && e.text).map((e) => e.text).join("").trim() : "";
313
- }
314
- function ne(e) {
315
- let t = [];
316
- return e.forEach((e, n) => {
317
- if (e.role === "user") {
318
- let n = m(e) || "[no content]";
319
- if (e.attachments?.length) {
320
- let r = [{
321
- type: "text",
322
- text: n
323
- }];
324
- for (let t of e.attachments) t.type === "image" && r.push({
325
- type: "image",
326
- url: `data:${t.mimeType};base64,${t.data}`,
327
- mimeType: t.mimeType,
328
- data: t.data
329
- });
330
- t.push({
331
- role: "user",
332
- content: r
333
- });
334
- } else t.push({
335
- role: "user",
336
- content: n
337
- });
338
- return;
339
- }
340
- let r = (e.parts ?? []).filter((e) => e.type === "tool-invocation" && e.toolInvocation && e.toolInvocation.result !== void 0);
341
- if (r.length === 0) {
342
- let n = m(e) || "[no content]";
343
- t.push({
344
- role: "assistant",
345
- content: n
346
- });
347
- return;
348
- }
349
- let i = m(e), a = r.map((e, t) => ({
350
- id: `call_${n}_${t}_${e.toolInvocation.toolName}`,
351
- name: e.toolInvocation.toolName,
352
- args: e.toolInvocation.args
353
- }));
354
- t.push({
355
- role: "assistant",
356
- content: i,
357
- toolCalls: a
358
- }), r.forEach((e, r) => {
359
- let i = e.toolInvocation.result;
360
- t.push({
361
- role: "tool",
362
- content: d(i),
363
- toolCallId: `call_${n}_${r}_${e.toolInvocation.toolName}`,
364
- toolName: e.toolInvocation.toolName,
365
- toolResult: i,
366
- toolIsError: c(i)
367
- });
368
- });
369
- }), t;
370
- }
371
- function re(e) {
372
- let t = [], n = [];
373
- for (let r of e) if (r.role === "system") {
374
- if (typeof r.content == "string") t.push(r.content);
375
- else if (Array.isArray(r.content)) for (let e of r.content) e.type === "text" && t.push(e.text);
376
- } else n.push(r);
377
- return {
378
- system: t.length > 0 ? t.join("\n\n") : void 0,
379
- rest: n
380
- };
381
- }
382
- function h(e) {
383
- let t = e.match(/^data:([^;,]+);base64,(.+)$/);
384
- return t ? {
385
- mimeType: t[1],
386
- data: t[2]
387
- } : null;
388
- }
389
- async function* g(e, t) {
390
- let n = e.getReader(), r = new TextDecoder("utf-8"), i = "";
391
- try {
392
- for (;;) {
393
- if (t?.aborted) return;
394
- let { value: e, done: a } = await n.read();
395
- if (a) break;
396
- i += r.decode(e, { stream: !0 });
397
- let o;
398
- for (; (o = ie(i)) !== -1;) {
399
- let e = i.slice(0, o);
400
- i = i.slice(o).replace(/^(\r\n\r\n|\n\n|\r\r)/, "");
401
- let t = _(e);
402
- t && (yield t);
403
- }
404
- }
405
- if (i.trim()) {
406
- let e = _(i);
407
- e && (yield e);
408
- }
409
- } finally {
410
- try {
411
- n.releaseLock();
412
- } catch {}
413
- }
414
- }
415
- function ie(e) {
416
- let t = e.indexOf("\n\n"), n = e.indexOf("\r\n\r\n");
417
- return t === -1 ? n : n === -1 ? t : Math.min(t, n);
418
- }
419
- function _(e) {
420
- let t, n = [];
421
- for (let r of e.split(/\r?\n/)) {
422
- if (!r || r.startsWith(":")) continue;
423
- let e = r.indexOf(":"), i = e === -1 ? r : r.slice(0, e), a = e === -1 ? "" : r.slice(e + 1);
424
- a.startsWith(" ") && (a = a.slice(1)), i === "event" ? t = a : i === "data" && n.push(a);
425
- }
426
- return n.length === 0 ? null : {
427
- event: t,
428
- data: n.join("\n")
429
- };
430
- }
431
- function v(e, ...t) {
432
- for (let n of t) {
433
- let t = e[n];
434
- if (typeof t == "number" && Number.isFinite(t)) return t;
435
- }
436
- }
437
- function y(e) {
438
- if (!e || typeof e != "object") return;
439
- let t = e, n = v(t, "inputTokens", "input_tokens", "prompt_tokens", "promptTokenCount", "prompt_eval_count"), r = v(t, "outputTokens", "output_tokens", "completion_tokens", "candidatesTokenCount", "eval_count"), i = v(t, "totalTokens", "total_tokens", "totalTokenCount") ?? (n !== void 0 && r !== void 0 ? n + r : void 0), a = t.input_tokens_details && typeof t.input_tokens_details == "object" ? t.input_tokens_details : void 0, o = t.output_tokens_details && typeof t.output_tokens_details == "object" ? t.output_tokens_details : void 0, s = v(t, "cachedInputTokens", "cache_read_input_tokens") ?? (a ? v(a, "cached_tokens") : void 0), c = v(t, "reasoningTokens", "thoughtsTokenCount") ?? (o ? v(o, "reasoning_tokens") : void 0);
440
- if (!(n === void 0 && r === void 0 && i === void 0 && s === void 0 && c === void 0)) return {
441
- inputTokens: n,
442
- outputTokens: r,
443
- totalTokens: i,
444
- cachedInputTokens: s,
445
- reasoningTokens: c
446
- };
447
- }
448
- var ae = "https://api.anthropic.com/v1/messages", oe = "2023-06-01", se = 4096;
449
- function b(e) {
450
- if (e.type !== "image") return null;
451
- if (e.data && e.mimeType) return {
452
- type: "image",
453
- source: {
454
- type: "base64",
455
- media_type: e.mimeType,
456
- data: e.data
457
- }
458
- };
459
- let t = h(e.url);
460
- return t ? {
461
- type: "image",
462
- source: {
463
- type: "base64",
464
- media_type: t.mimeType,
465
- data: t.data
466
- }
467
- } : {
468
- type: "image",
469
- source: {
470
- type: "url",
471
- url: e.url
472
- }
473
- };
474
- }
475
- function ce(e) {
476
- if (typeof e == "string") return [{
477
- type: "text",
478
- text: e || "[no content]"
479
- }];
480
- let t = [];
481
- for (let n of e) if (n.type === "text") n.text && t.push({
482
- type: "text",
483
- text: n.text
484
- });
485
- else {
486
- let e = b(n);
487
- e && t.push(e);
488
- }
489
- return t.length === 0 && t.push({
490
- type: "text",
491
- text: "[no content]"
492
- }), t;
493
- }
494
- function le(e) {
495
- if (typeof e == "string") return e;
496
- let t = [];
497
- for (let n of e) if (n.type === "text") n.text && t.push({
498
- type: "text",
499
- text: n.text
500
- });
501
- else if (n.type === "image") {
502
- let e = b(n);
503
- e && t.push(e);
504
- }
505
- return t.length === 0 ? "[no content]" : t;
506
- }
507
- function ue(e) {
508
- let t = [];
509
- for (let n of e) {
510
- if (n.role === "tool") {
511
- let e = t[t.length - 1], r = {
512
- type: "tool_result",
513
- tool_use_id: n.toolCallId,
514
- content: le(n.content),
515
- ...n.toolIsError ? { is_error: !0 } : {}
516
- };
517
- e && e.role === "user" && Array.isArray(e.content) ? e.content.push(r) : t.push({
518
- role: "user",
519
- content: [r]
520
- });
521
- continue;
522
- }
523
- if (n.role === "assistant") {
524
- let e = [], r = typeof n.content == "string" ? n.content : Array.isArray(n.content) ? n.content.map((e) => e.type === "text" ? e.text : "").join("") : "";
525
- if (r && e.push({
526
- type: "text",
527
- text: r
528
- }), n.toolCalls?.length) for (let t of n.toolCalls) e.push({
529
- type: "tool_use",
530
- id: t.id,
531
- name: t.name,
532
- input: t.args ?? {}
533
- });
534
- e.length === 0 && e.push({
535
- type: "text",
536
- text: "[no content]"
537
- }), t.push({
538
- role: "assistant",
539
- content: e
540
- });
541
- continue;
542
- }
543
- t.push({
544
- role: "user",
545
- content: ce(n.content)
546
- });
547
- }
548
- return t;
549
- }
550
- function x(e, t) {
551
- let { config: n, messages: r, tools: i } = e, { system: a, rest: o } = re(r), s = {
552
- model: n.model,
553
- max_tokens: n.maxTokens ?? se,
554
- messages: ue(o),
555
- ...t ? { stream: !0 } : {}
556
- };
557
- return n.temperature !== void 0 && (s.temperature = n.temperature), a && (s.system = a), i && i.length > 0 && (s.tools = i.map((e) => ({
558
- name: e.name,
559
- description: e.description,
560
- input_schema: e.inputSchema,
561
- ...t ? { eager_input_streaming: !0 } : {}
562
- }))), s;
563
- }
564
- async function* de(e) {
565
- let { config: t, signal: n } = e, r = await fetch(ae, {
566
- method: "POST",
567
- headers: {
568
- "Content-Type": "application/json",
569
- "x-api-key": t.apiKey,
570
- "anthropic-version": oe,
571
- "anthropic-dangerous-direct-browser-access": "true"
572
- },
573
- body: JSON.stringify(x(e, !0)),
574
- signal: n
575
- });
576
- if (!r.ok || !r.body) {
577
- let e = await r.text().catch(() => "");
578
- throw Error(`Anthropic request failed (${r.status} ${r.statusText}): ${e}`);
579
- }
580
- let i = /* @__PURE__ */ new Map(), a;
581
- for await (let e of g(r.body, n)) {
582
- let t;
583
- try {
584
- t = JSON.parse(e.data);
585
- } catch {
586
- continue;
587
- }
588
- let n = t?.type;
589
- if (n === "message_start") a = y(t?.message?.usage);
590
- else if (n === "message_delta") {
591
- let e = y(t?.usage);
592
- e && (a = {
593
- ...a,
594
- ...e
595
- });
596
- } else if (n === "content_block_start") {
597
- let e = t.index, n = t.content_block ?? {};
598
- if (n.type === "tool_use") {
599
- i.set(e, {
600
- kind: "tool_use",
601
- id: n.id,
602
- name: n.name,
603
- argsJson: "",
604
- emittedStart: !1
605
- }), yield {
606
- type: "tool-call-start",
607
- index: e,
608
- toolCallId: n.id,
609
- toolName: n.name
610
- };
611
- let t = i.get(e);
612
- t && (t.emittedStart = !0);
613
- } else i.set(e, {
614
- kind: "text",
615
- argsJson: "",
616
- emittedStart: !1
617
- });
618
- } else if (n === "content_block_delta") {
619
- let e = t.index, n = t.delta ?? {}, r = i.get(e);
620
- if (!r) continue;
621
- n.type === "text_delta" && typeof n.text == "string" ? yield {
622
- type: "text-delta",
623
- delta: n.text
624
- } : n.type === "input_json_delta" && typeof n.partial_json == "string" && r.kind === "tool_use" && (r.argsJson += n.partial_json, yield {
625
- type: "tool-call-args-delta",
626
- index: e,
627
- toolCallId: r.id,
628
- toolName: r.name,
629
- argsDelta: n.partial_json
630
- });
631
- } else if (n === "content_block_stop") {
632
- let e = t.index, n = i.get(e);
633
- if (n && n.kind === "tool_use" && n.id && n.name) {
634
- let t = {};
635
- if (n.argsJson) try {
636
- t = JSON.parse(n.argsJson);
637
- } catch {
638
- t = {};
639
- }
640
- yield {
641
- type: "tool-call-ready",
642
- index: e,
643
- toolCallId: n.id,
644
- toolName: n.name,
645
- args: t
646
- };
647
- }
648
- } else if (n === "message_stop") {
649
- if (a) {
650
- let e = a.totalTokens ?? (a.inputTokens !== void 0 && a.outputTokens !== void 0 ? a.inputTokens + a.outputTokens : void 0);
651
- yield {
652
- type: "usage",
653
- usage: {
654
- ...a,
655
- totalTokens: e
656
- }
657
- };
658
- }
659
- } else n === "error" && (yield {
660
- type: "error",
661
- message: t?.error?.message ?? "Anthropic stream error"
662
- });
663
- }
664
- yield { type: "done" };
665
- }
666
- async function fe(e) {
667
- let { config: t, signal: n } = e, r = await fetch(ae, {
668
- method: "POST",
669
- headers: {
670
- "Content-Type": "application/json",
671
- "x-api-key": t.apiKey,
672
- "anthropic-version": oe,
673
- "anthropic-dangerous-direct-browser-access": "true"
674
- },
675
- body: JSON.stringify(x(e, !1)),
676
- signal: n
677
- });
678
- if (!r.ok) {
679
- let e = await r.text().catch(() => "");
680
- throw Error(`Anthropic request failed (${r.status} ${r.statusText}): ${e}`);
681
- }
682
- let i = await r.json(), a = "", o = [];
683
- for (let e of i?.content ?? []) e.type === "text" && typeof e.text == "string" ? a += e.text : e.type === "tool_use" && o.push({
684
- id: e.id,
685
- name: e.name,
686
- args: e.input && typeof e.input == "object" ? e.input : {}
687
- });
688
- return {
689
- text: a,
690
- toolCalls: o
691
- };
692
- }
693
- var pe = /* @__PURE__ */ new Set([
694
- "type",
695
- "description",
696
- "enum",
697
- "properties",
698
- "required",
699
- "items",
700
- "format",
701
- "nullable",
702
- "minimum",
703
- "maximum",
704
- "minItems",
705
- "maxItems",
706
- "minLength",
707
- "maxLength",
708
- "pattern"
709
- ]);
710
- function me(e) {
711
- if (!e || typeof e != "object") return { type: "object" };
712
- let t = S(e);
713
- if (typeof t != "object" || !t) return { type: "object" };
714
- let n = t;
715
- return n.type ||= "object", n;
716
- }
717
- function S(e) {
718
- if (Array.isArray(e)) return e.map(S);
719
- if (!e || typeof e != "object") return e;
720
- let t = e;
721
- for (let e of [
722
- "oneOf",
723
- "anyOf",
724
- "allOf"
725
- ]) {
726
- let n = t[e];
727
- if (Array.isArray(n) && n.length === 1) return S(n[0]);
728
- }
729
- let n = {};
730
- for (let [e, r] of Object.entries(t)) if (pe.has(e)) if (e === "properties" && r && typeof r == "object") {
731
- let t = {};
732
- for (let [e, n] of Object.entries(r)) t[e] = S(n);
733
- n[e] = t;
734
- } else e === "items" ? n[e] = S(r) : n[e] = r;
735
- return n;
736
- }
737
- function he(e) {
738
- let t = e.trim();
739
- return t.startsWith("models/") ? t.slice(7) : t;
740
- }
741
- function C(e, t) {
742
- let n = t === "stream" ? "streamGenerateContent?alt=sse" : "generateContent";
743
- return `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(he(e))}:${n}`;
744
- }
745
- function w(e) {
746
- if (e.type !== "image") return null;
747
- if (e.data && e.mimeType) return { inlineData: {
748
- mimeType: e.mimeType,
749
- data: e.data
750
- } };
751
- let t = h(e.url);
752
- return t ? { inlineData: {
753
- mimeType: t.mimeType,
754
- data: t.data
755
- } } : null;
756
- }
757
- function ge(e) {
758
- if (typeof e == "string") return [{ text: e || "[no content]" }];
759
- let t = [];
760
- for (let n of e) if (n.type === "text") n.text && t.push({ text: n.text });
761
- else {
762
- let e = w(n);
763
- e && t.push(e);
764
- }
765
- return t.length === 0 && t.push({ text: "[no content]" }), t;
766
- }
767
- function _e(e) {
768
- if (typeof e == "string") {
769
- let t;
770
- try {
771
- t = JSON.parse(e);
772
- } catch {
773
- t = { result: e };
774
- }
775
- return (!t || typeof t != "object") && (t = { result: t }), {
776
- response: t,
777
- imageParts: []
778
- };
779
- }
780
- let { text: t, imageParts: n } = f(e), r = {};
781
- return t && (r.text = t), n.length > 0 && (r.images = n.map((e) => ({
782
- mimeType: e.mimeType ?? "image/*",
783
- omitted: !0
784
- })), r.note = "Image bytes were sent in the next user turn as inlineData."), Object.keys(r).length === 0 && (r.result = null), {
785
- response: r,
786
- imageParts: n
787
- };
788
- }
789
- function ve(e) {
790
- let t = [];
791
- for (let n of e) {
792
- if (n.role === "tool") {
793
- let { response: e, imageParts: r } = _e(n.content), i = t[t.length - 1], a = { functionResponse: {
794
- name: n.toolName,
795
- response: e
796
- } };
797
- if (i && i.role === "function" ? i.parts.push(a) : t.push({
798
- role: "function",
799
- parts: [a]
800
- }), r.length > 0) {
801
- let e = [{ text: p(n.toolName, r.length) }];
802
- for (let t of r) {
803
- let n = w(t);
804
- n && e.push(n);
805
- }
806
- t.push({
807
- role: "user",
808
- parts: e
809
- });
810
- }
811
- continue;
812
- }
813
- if (n.role === "assistant") {
814
- let e = [], r = typeof n.content == "string" ? n.content : Array.isArray(n.content) ? n.content.map((e) => e.type === "text" ? e.text : "").join("") : "";
815
- if (r && e.push({ text: r }), n.toolCalls?.length) for (let t of n.toolCalls) e.push({ functionCall: {
816
- name: t.name,
817
- args: t.args ?? {}
818
- } });
819
- e.length === 0 && e.push({ text: "[no content]" }), t.push({
820
- role: "model",
821
- parts: e
822
- });
823
- continue;
824
- }
825
- t.push({
826
- role: "user",
827
- parts: ge(n.content)
828
- });
829
- }
830
- return t;
831
- }
832
- function T(e) {
833
- let { config: t, messages: n, tools: r } = e, { system: i, rest: a } = re(n), o = { contents: ve(a) };
834
- i && (o.systemInstruction = { parts: [{ text: i }] });
835
- let s = {};
836
- return t.temperature !== void 0 && (s.temperature = t.temperature), t.maxTokens !== void 0 && (s.maxOutputTokens = t.maxTokens), Object.keys(s).length > 0 && (o.generationConfig = s), r && r.length > 0 && (o.tools = [{ functionDeclarations: r.map((e) => ({
837
- name: e.name,
838
- description: e.description,
839
- parameters: me(e.inputSchema)
840
- })) }]), o;
841
- }
842
- async function* ye(e) {
843
- let { config: t, signal: n } = e, r = `${C(t.model, "stream")}&key=${encodeURIComponent(t.apiKey)}`, i = await fetch(r, {
844
- method: "POST",
845
- headers: { "Content-Type": "application/json" },
846
- body: JSON.stringify(T(e)),
847
- signal: n
848
- });
849
- if (!i.ok || !i.body) {
850
- let e = await i.text().catch(() => "");
851
- throw Error(`Google request failed (${i.status} ${i.statusText}): ${e}`);
852
- }
853
- let a = 0, o;
854
- for await (let e of g(i.body, n)) {
855
- let t;
856
- try {
857
- t = JSON.parse(e.data);
858
- } catch {
859
- continue;
860
- }
861
- o = y(t?.usageMetadata) ?? o;
862
- let n = t?.candidates?.[0]?.content?.parts ?? [];
863
- for (let e of n) if (typeof e.text == "string" && e.text.length > 0) yield {
864
- type: "text-delta",
865
- delta: e.text
866
- };
867
- else if (e.functionCall && typeof e.functionCall == "object") {
868
- let t = a++, n = `call_${t}_${e.functionCall.name ?? "tool"}`, r = e.functionCall.name ?? "", i = e.functionCall.args && typeof e.functionCall.args == "object" ? e.functionCall.args : {};
869
- yield {
870
- type: "tool-call-start",
871
- index: t,
872
- toolCallId: n,
873
- toolName: r
874
- };
875
- let o = JSON.stringify(i);
876
- o && o !== "{}" && (yield {
877
- type: "tool-call-args-delta",
878
- index: t,
879
- toolCallId: n,
880
- toolName: r,
881
- argsDelta: o
882
- }), yield {
883
- type: "tool-call-ready",
884
- index: t,
885
- toolCallId: n,
886
- toolName: r,
887
- args: i
888
- };
889
- }
890
- }
891
- o && (yield {
892
- type: "usage",
893
- usage: o
894
- }), yield { type: "done" };
895
- }
896
- async function be(e) {
897
- let { config: t, signal: n } = e, r = `${C(t.model, "single")}?key=${encodeURIComponent(t.apiKey)}`, i = await fetch(r, {
898
- method: "POST",
899
- headers: { "Content-Type": "application/json" },
900
- body: JSON.stringify(T(e)),
901
- signal: n
902
- });
903
- if (!i.ok) {
904
- let e = await i.text().catch(() => "");
905
- throw Error(`Google request failed (${i.status} ${i.statusText}): ${e}`);
906
- }
907
- let a = await i.json(), o = "", s = [], c = a?.candidates?.[0]?.content?.parts ?? [];
908
- for (let e of c) typeof e.text == "string" ? o += e.text : e.functionCall && s.push({
909
- id: `call_${s.length}_${e.functionCall.name ?? "tool"}`,
910
- name: e.functionCall.name ?? "",
911
- args: e.functionCall.args && typeof e.functionCall.args == "object" ? e.functionCall.args : {}
912
- });
913
- return {
914
- text: o,
915
- toolCalls: s
916
- };
917
- }
918
- async function* xe(e, t) {
919
- let n = e.getReader(), r = new TextDecoder(), i = "";
920
- try {
921
- for (;;) {
922
- if (t?.aborted) return;
923
- let { done: e, value: a } = await n.read();
924
- if (e) break;
925
- i += r.decode(a, { stream: !0 });
926
- let o = i.split("\n");
927
- i = o.pop() ?? "";
928
- for (let e of o) {
929
- let t = e.trim();
930
- if (t) try {
931
- yield JSON.parse(t);
932
- } catch {}
933
- }
934
- }
935
- let e = i.trim();
936
- if (e) try {
937
- yield JSON.parse(e);
938
- } catch {}
939
- } finally {
940
- n.releaseLock();
941
- }
942
- }
943
- var Se = "http://localhost:11434";
944
- function E(e) {
945
- let t = (e || "http://localhost:11434").trim(), n = t.length;
946
- for (; n > 0 && t.charCodeAt(n - 1) === 47;) n--;
947
- let r = t.slice(0, n);
948
- return r.endsWith("/api") ? r.slice(0, -4) : r;
949
- }
950
- function D(e, t) {
951
- return `${E(e)}${t}`;
952
- }
953
- var Ce = class extends Error {
954
- constructor(e) {
955
- super("Could not reach Ollama. If it's running, allow this origin by starting Ollama with `OLLAMA_ORIGINS=*` (or your inspector origin) and try again."), this.name = "OllamaCorsError", this.cause = e;
956
- }
957
- };
958
- function we(e) {
959
- let t = [];
960
- for (let n of e) {
961
- if (n.type !== "image") continue;
962
- if (n.data) {
963
- t.push(n.data);
964
- continue;
965
- }
966
- let e = h(n.url);
967
- e?.data && t.push(e.data);
968
- }
969
- return t;
970
- }
971
- function O(e) {
972
- if (typeof e == "string") return { content: e };
973
- let t = e.filter((e) => e.type === "text").map((e) => e.text).join(""), n = we(e);
974
- return {
975
- content: t,
976
- ...n.length > 0 ? { images: n } : {}
977
- };
978
- }
979
- function Te(e) {
980
- return e.map((e) => e.role === "tool" ? {
981
- role: "tool",
982
- tool_name: e.toolName,
983
- content: typeof e.content == "string" ? e.content : JSON.stringify(e.toolResult ?? e.content)
984
- } : e.role === "assistant" ? {
985
- role: "assistant",
986
- ...typeof e.content == "string" ? { content: e.content } : O(e.content),
987
- ...e.toolCalls?.length ? { tool_calls: e.toolCalls.map((e, t) => ({
988
- type: "function",
989
- function: {
990
- index: t,
991
- name: e.name,
992
- arguments: e.args
993
- }
994
- })) } : {}
995
- } : {
996
- role: e.role,
997
- ...O(e.content)
998
- });
999
- }
1000
- function k(e, t) {
1001
- let { config: n, messages: r, tools: i } = e, a = {
1002
- model: n.model,
1003
- messages: Te(r),
1004
- stream: t
1005
- }, o = {};
1006
- return n.temperature !== void 0 && (o.temperature = n.temperature), n.maxTokens !== void 0 && (o.num_predict = n.maxTokens), Object.keys(o).length > 0 && (a.options = o), i && i.length > 0 && (a.tools = i.map((e) => ({
1007
- type: "function",
1008
- function: {
1009
- name: e.name,
1010
- description: e.description,
1011
- parameters: e.inputSchema
1012
- }
1013
- }))), a;
1014
- }
1015
- function A(e) {
1016
- return {
1017
- "Content-Type": "application/json",
1018
- ...e.apiKey.trim() ? { Authorization: `Bearer ${e.apiKey.trim()}` } : {}
1019
- };
1020
- }
1021
- function j(e) {
1022
- return Array.isArray(e) ? e.map((e) => {
1023
- let t = e && typeof e == "object" ? e.function : void 0, n = typeof t?.name == "string" ? t.name : "", r = t?.arguments;
1024
- return {
1025
- name: n,
1026
- args: r && typeof r == "object" ? r : {}
1027
- };
1028
- }).filter((e) => e.name) : [];
1029
- }
1030
- async function* Ee(e) {
1031
- let { config: t, signal: n } = e, r = await fetch(D(t.baseUrl, "/api/chat"), {
1032
- method: "POST",
1033
- headers: A(t),
1034
- body: JSON.stringify(k(e, !0)),
1035
- signal: n
1036
- });
1037
- if (!r.ok || !r.body) {
1038
- let e = await r.text().catch(() => "");
1039
- throw Error(`Ollama request failed (${r.status} ${r.statusText}): ${e}`);
1040
- }
1041
- let i = !1, a;
1042
- for await (let e of xe(r.body, n)) {
1043
- let t = e && typeof e == "object" ? e.message : void 0;
1044
- if (typeof t?.content == "string" && t.content.length > 0 && (yield {
1045
- type: "text-delta",
1046
- delta: t.content
1047
- }), !i) {
1048
- let e = j(t?.tool_calls);
1049
- if (e.length > 0) {
1050
- for (let [t, n] of e.entries()) {
1051
- let e = `call_${t}_${n.name || "tool"}`;
1052
- yield {
1053
- type: "tool-call-start",
1054
- index: t,
1055
- toolCallId: e,
1056
- toolName: n.name
1057
- };
1058
- let r = JSON.stringify(n.args);
1059
- r && r !== "{}" && (yield {
1060
- type: "tool-call-args-delta",
1061
- index: t,
1062
- toolCallId: e,
1063
- toolName: n.name,
1064
- argsDelta: r
1065
- }), yield {
1066
- type: "tool-call-ready",
1067
- index: t,
1068
- toolCallId: e,
1069
- toolName: n.name,
1070
- args: n.args
1071
- };
1072
- }
1073
- i = !0;
1074
- }
1075
- }
1076
- e && typeof e == "object" && e.error && (yield {
1077
- type: "error",
1078
- message: String(e.error)
1079
- }), a = y(e) ?? a;
1080
- }
1081
- a && (yield {
1082
- type: "usage",
1083
- usage: a
1084
- }), yield { type: "done" };
1085
- }
1086
- async function De(e) {
1087
- let { config: t, signal: n } = e, r = await fetch(D(t.baseUrl, "/api/chat"), {
1088
- method: "POST",
1089
- headers: A(t),
1090
- body: JSON.stringify(k(e, !1)),
1091
- signal: n
1092
- });
1093
- if (!r.ok) {
1094
- let e = await r.text().catch(() => "");
1095
- throw Error(`Ollama request failed (${r.status} ${r.statusText}): ${e}`);
1096
- }
1097
- let i = (await r.json())?.message ?? {};
1098
- return {
1099
- text: typeof i.content == "string" ? i.content : "",
1100
- toolCalls: j(i.tool_calls).map((e, t) => ({
1101
- id: `call_${t}_${e.name || "tool"}`,
1102
- name: e.name,
1103
- args: e.args
1104
- }))
1105
- };
1106
- }
1107
- var M = class extends Error {
1108
- status;
1109
- body;
1110
- constructor(e, t, n) {
1111
- super(t), this.name = "LlmRequestError", this.status = e, this.body = n;
1112
- }
1113
- };
1114
- async function N(e) {
1115
- let t = await e.text().catch(() => ""), n = t;
1116
- if (t) try {
1117
- n = JSON.parse(t);
1118
- } catch {}
1119
- throw new M(e.status, `OpenAI request failed (${e.status} ${e.statusText}): ${t}`, n);
1120
- }
1121
- var Oe = "https://api.openai.com/v1";
1122
- function P(e, t) {
1123
- return `${e.baseUrl ?? Oe}${t}`;
1124
- }
1125
- function F(e) {
1126
- let t = {
1127
- "Content-Type": "application/json",
1128
- ...e.extraHeaders
1129
- };
1130
- return e.apiKey && (t.Authorization = `Bearer ${e.apiKey}`), t;
1131
- }
1132
- function ke(e) {
1133
- return typeof e == "string" ? e : e.map((e) => e.type === "text" ? {
1134
- type: "text",
1135
- text: e.text
1136
- } : {
1137
- type: "image_url",
1138
- image_url: { url: e.url }
1139
- });
1140
- }
1141
- function I(e) {
1142
- let t = [];
1143
- for (let n of e) {
1144
- if (n.role === "tool") {
1145
- let { text: e, imageParts: r } = f(n.content), i = r.length > 0 ? "[image content; see next message]" : "[no content]";
1146
- if (t.push({
1147
- role: "tool",
1148
- tool_call_id: n.toolCallId,
1149
- content: e || i
1150
- }), r.length > 0) {
1151
- let e = [{
1152
- type: "text",
1153
- text: p(n.toolName, r.length)
1154
- }, ...r.map((e) => ({
1155
- type: "image_url",
1156
- image_url: { url: e.url }
1157
- }))];
1158
- t.push({
1159
- role: "user",
1160
- content: e
1161
- });
1162
- }
1163
- continue;
1164
- }
1165
- if (n.role === "assistant") {
1166
- let e = {
1167
- role: "assistant",
1168
- content: typeof n.content == "string" && n.content.length > 0 ? n.content : null
1169
- };
1170
- n.toolCalls?.length && (e.tool_calls = n.toolCalls.map((e) => ({
1171
- id: e.id,
1172
- type: "function",
1173
- function: {
1174
- name: e.name,
1175
- arguments: JSON.stringify(e.args)
1176
- }
1177
- }))), t.push(e);
1178
- continue;
1179
- }
1180
- t.push({
1181
- role: n.role,
1182
- content: ke(n.content)
1183
- });
1184
- }
1185
- return t;
1186
- }
1187
- async function* L(e) {
1188
- let { config: t, messages: n, tools: r, signal: i } = e, a = {
1189
- model: t.model,
1190
- messages: I(n),
1191
- stream: !0
1192
- };
1193
- t.provider === "openrouter" && (a.stream_options = { include_usage: !0 }), t.temperature !== void 0 && (a.temperature = t.temperature), t.maxTokens !== void 0 && (a.max_tokens = t.maxTokens), r && r.length > 0 && (a.tools = r.map((e) => ({
1194
- type: "function",
1195
- function: {
1196
- name: e.name,
1197
- description: e.description,
1198
- parameters: e.inputSchema
1199
- }
1200
- })));
1201
- let o = P(t, "/chat/completions"), s = await fetch(o, {
1202
- method: "POST",
1203
- headers: F(t),
1204
- body: JSON.stringify(a),
1205
- signal: i,
1206
- ...t.credentials ? { credentials: t.credentials } : {}
1207
- }), c = s.body;
1208
- s.ok || await N(s), c || await N(s);
1209
- let l = c, u = /* @__PURE__ */ new Map();
1210
- for await (let e of g(l, i)) {
1211
- if (!e.data || e.data === "[DONE]") continue;
1212
- let t;
1213
- try {
1214
- t = JSON.parse(e.data);
1215
- } catch {
1216
- continue;
1217
- }
1218
- let n = y(t?.usage);
1219
- n && (yield {
1220
- type: "usage",
1221
- usage: n
1222
- });
1223
- let r = t?.choices?.[0];
1224
- if (!r) continue;
1225
- let i = r.delta ?? {};
1226
- if (typeof i.content == "string" && i.content.length > 0 && (yield {
1227
- type: "text-delta",
1228
- delta: i.content
1229
- }), Array.isArray(i.tool_calls)) for (let e of i.tool_calls) {
1230
- let t = typeof e.index == "number" ? e.index : 0, n = u.get(t);
1231
- n || (n = {
1232
- id: e.id ?? `call_${t}`,
1233
- name: e.function?.name ?? "",
1234
- argsJson: "",
1235
- started: !1
1236
- }, u.set(t, n)), (e.id && !n.id.startsWith("call_") || e.id) && (n.id = e.id), e.function?.name && (n.name = e.function.name), !n.started && n.name && (n.started = !0, yield {
1237
- type: "tool-call-start",
1238
- index: t,
1239
- toolCallId: n.id,
1240
- toolName: n.name
1241
- });
1242
- let r = e.function?.arguments;
1243
- typeof r == "string" && r.length > 0 && (n.argsJson += r, n.started && (yield {
1244
- type: "tool-call-args-delta",
1245
- index: t,
1246
- toolCallId: n.id,
1247
- toolName: n.name,
1248
- argsDelta: r
1249
- }));
1250
- }
1251
- if (r.finish_reason) {
1252
- for (let [e, t] of u) {
1253
- let n = {};
1254
- if (t.argsJson) try {
1255
- n = JSON.parse(t.argsJson);
1256
- } catch {
1257
- n = {};
1258
- }
1259
- yield {
1260
- type: "tool-call-ready",
1261
- index: e,
1262
- toolCallId: t.id,
1263
- toolName: t.name,
1264
- args: n
1265
- };
1266
- }
1267
- u.clear();
1268
- }
1269
- }
1270
- yield { type: "done" };
1271
- }
1272
- async function R(e) {
1273
- let { config: t, messages: n, tools: r, signal: i } = e, a = {
1274
- model: t.model,
1275
- messages: I(n)
1276
- };
1277
- t.temperature !== void 0 && (a.temperature = t.temperature), t.maxTokens !== void 0 && (a.max_tokens = t.maxTokens), r && r.length > 0 && (a.tools = r.map((e) => ({
1278
- type: "function",
1279
- function: {
1280
- name: e.name,
1281
- description: e.description,
1282
- parameters: e.inputSchema
1283
- }
1284
- })));
1285
- let o = P(t, "/chat/completions"), s = await fetch(o, {
1286
- method: "POST",
1287
- headers: F(t),
1288
- body: JSON.stringify(a),
1289
- signal: i,
1290
- ...t.credentials ? { credentials: t.credentials } : {}
1291
- });
1292
- s.ok || await N(s);
1293
- let c = (await s.json())?.choices?.[0]?.message;
1294
- return {
1295
- text: typeof c?.content == "string" ? c.content : "",
1296
- toolCalls: Array.isArray(c?.tool_calls) ? c.tool_calls.map((e) => {
1297
- let t = {};
1298
- try {
1299
- t = JSON.parse(e?.function?.arguments ?? "{}");
1300
- } catch {
1301
- t = {};
1302
- }
1303
- return {
1304
- id: e.id,
1305
- name: e.function?.name ?? "",
1306
- args: t
1307
- };
1308
- }) : []
1309
- };
1310
- }
1311
- function z(e) {
1312
- return {
1313
- ...e,
1314
- config: {
1315
- ...e.config,
1316
- baseUrl: "https://openrouter.ai/api/v1",
1317
- extraHeaders: {
1318
- "HTTP-Referer": "https://inspector.mcp-use.com",
1319
- "X-Title": "mcp-use Inspector"
1320
- }
1321
- }
1322
- };
1323
- }
1324
- function Ae(e) {
1325
- switch (e.config.provider) {
1326
- case "openai": throw Error("provider 'openai' uses the Responses API via OpenAIResponsesDriver, not streamChat");
1327
- case "openai-compatible": return L(e);
1328
- case "anthropic": return de(e);
1329
- case "google": return ye(e);
1330
- case "openrouter": return L(z(e));
1331
- case "ollama": return Ee(e);
1332
- default: throw Error(`Unsupported LLM provider: ${e.config.provider}`);
1333
- }
1334
- }
1335
- function je(e) {
1336
- switch (e.config.provider) {
1337
- case "openai": throw Error("provider 'openai' uses the Responses API via OpenAIResponsesDriver, not chat");
1338
- case "openai-compatible": return R(e);
1339
- case "anthropic": return fe(e);
1340
- case "google": return be(e);
1341
- case "openrouter": return R(z(e));
1342
- case "ollama": return De(e);
1343
- default: throw Error(`Unsupported LLM provider: ${e.config.provider}`);
1344
- }
1345
- }
1346
- var Me = "https://api.openai.com/v1";
1347
- function B(e, t) {
1348
- return `${(e.baseUrl ?? Me).replace(/\/$/, "")}${t}`;
1349
- }
1350
- function V(e) {
1351
- let t = {
1352
- "Content-Type": "application/json",
1353
- ...e.extraHeaders
1354
- };
1355
- return e.apiKey && (t.Authorization = `Bearer ${e.apiKey}`), t;
1356
- }
1357
- async function H(e) {
1358
- let t = await e.text().catch(() => "");
1359
- return `OpenAI request failed (${e.status} ${e.statusText}): ${t}`;
1360
- }
1361
- function Ne(e) {
1362
- return typeof e == "string" ? e : e.map((e) => e.type === "text" ? {
1363
- type: "input_text",
1364
- text: e.text
1365
- } : {
1366
- type: "input_image",
1367
- image_url: e.url
1368
- });
1369
- }
1370
- function U(e) {
1371
- let t = [], n = [];
1372
- for (let r of e) {
1373
- if (r.role === "system") {
1374
- let e = typeof r.content == "string" ? r.content : r.content.filter((e) => e.type === "text").map((e) => e.text).join("\n");
1375
- e && t.push(e);
1376
- continue;
1377
- }
1378
- if (r.role === "user") {
1379
- n.push({
1380
- role: "user",
1381
- content: Ne(r.content)
1382
- });
1383
- continue;
1384
- }
1385
- if (r.role === "assistant") {
1386
- typeof r.content == "string" && r.content.length > 0 && n.push({
1387
- type: "message",
1388
- role: "assistant",
1389
- content: [{
1390
- type: "output_text",
1391
- text: r.content
1392
- }]
1393
- });
1394
- for (let e of r.toolCalls ?? []) n.push({
1395
- type: "function_call",
1396
- call_id: e.id,
1397
- name: e.name,
1398
- arguments: JSON.stringify(e.args)
1399
- });
1400
- continue;
1401
- }
1402
- if (r.role === "tool") {
1403
- let { text: e, imageParts: t } = f(r.content), i = t.length > 0 ? "[image content; see next message]" : "[no content]";
1404
- n.push({
1405
- type: "function_call_output",
1406
- call_id: r.toolCallId,
1407
- output: e || i
1408
- }), t.length > 0 && n.push({
1409
- role: "user",
1410
- content: [{
1411
- type: "input_text",
1412
- text: p(r.toolName, t.length)
1413
- }, ...t.map((e) => ({
1414
- type: "input_image",
1415
- image_url: e.url
1416
- }))]
1417
- });
1418
- }
1419
- }
1420
- return {
1421
- instructions: t.length > 0 ? t.join("\n\n") : void 0,
1422
- input: n
1423
- };
1424
- }
1425
- function Pe(e) {
1426
- return e.map((e) => ({
1427
- type: "function",
1428
- name: e.name,
1429
- description: e.description,
1430
- parameters: e.inputSchema,
1431
- strict: !1
1432
- }));
1433
- }
1434
- function W(e, t, n, r) {
1435
- let i = d(r);
1436
- if (typeof i == "string") {
1437
- e.push({
1438
- type: "function_call_output",
1439
- call_id: t,
1440
- output: i
1441
- });
1442
- return;
1443
- }
1444
- let { text: a, imageParts: o } = f(i);
1445
- e.push({
1446
- type: "function_call_output",
1447
- call_id: t,
1448
- output: a || "[image content; see next message]"
1449
- }), o.length > 0 && e.push({
1450
- role: "user",
1451
- content: [{
1452
- type: "input_text",
1453
- text: p(n, o.length)
1454
- }, ...o.map((e) => ({
1455
- type: "input_image",
1456
- image_url: e.url
1457
- }))]
1458
- });
1459
- }
1460
- function G(e, t) {
1461
- let n = {
1462
- model: e.config.model,
1463
- input: e.input,
1464
- store: !1,
1465
- include: ["reasoning.encrypted_content"],
1466
- reasoning: { effort: e.config.reasoningEffort ?? "low" },
1467
- stream: t
1468
- };
1469
- return e.instructions && (n.instructions = e.instructions), e.tools && e.tools.length > 0 && (n.tools = Pe(e.tools)), e.config.maxTokens !== void 0 && (n.max_output_tokens = e.config.maxTokens), n;
1470
- }
1471
- function K(e) {
1472
- let t = [];
1473
- for (let n of e) {
1474
- if (!n || typeof n != "object") continue;
1475
- let e = n;
1476
- e.type === "function_call" && (typeof e.call_id != "string" || typeof e.name != "string" || t.push({
1477
- call_id: e.call_id,
1478
- name: e.name,
1479
- arguments: typeof e.arguments == "string" ? e.arguments : "{}"
1480
- }));
1481
- }
1482
- return t;
1483
- }
1484
- function Fe(e) {
1485
- let t = [];
1486
- for (let n of e) {
1487
- if (!n || typeof n != "object") continue;
1488
- let e = n;
1489
- if (e.type !== "message" || e.role !== "assistant") continue;
1490
- let r = e.content;
1491
- if (Array.isArray(r)) for (let e of r) {
1492
- if (!e || typeof e != "object") continue;
1493
- let n = e;
1494
- n.type === "output_text" && typeof n.text == "string" && t.push(n.text);
1495
- }
1496
- }
1497
- return t.join("");
1498
- }
1499
- function q(e) {
1500
- if (!e) return {};
1501
- try {
1502
- return JSON.parse(e);
1503
- } catch {
1504
- return {};
1505
- }
1506
- }
1507
- async function* J(e) {
1508
- let t = await fetch(B(e.config, "/responses"), {
1509
- method: "POST",
1510
- headers: V(e.config),
1511
- body: JSON.stringify(G(e, !0)),
1512
- signal: e.signal
1513
- });
1514
- if (!t.ok || !t.body) throw Error(await H(t));
1515
- let n = /* @__PURE__ */ new Map(), r = 0, i = [];
1516
- for await (let a of g(t.body, e.signal)) {
1517
- if (!a.data || a.data === "[DONE]") continue;
1518
- let e;
1519
- try {
1520
- e = JSON.parse(a.data);
1521
- } catch {
1522
- continue;
1523
- }
1524
- let t = typeof e.type == "string" ? e.type : a.event;
1525
- if (t === "response.output_text.delta") {
1526
- let t = e.delta;
1527
- typeof t == "string" && t.length > 0 && (yield {
1528
- type: "text-delta",
1529
- delta: t
1530
- });
1531
- continue;
1532
- }
1533
- if (t === "response.output_item.added") {
1534
- let t = e.item;
1535
- if (t?.type === "function_call") {
1536
- let e = typeof t.call_id == "string" ? t.call_id : `call_${r}`, i = typeof t.name == "string" ? t.name : "", a = r++;
1537
- n.set(e, {
1538
- index: a,
1539
- name: i,
1540
- argsJson: "",
1541
- started: !0
1542
- }), yield {
1543
- type: "tool-call-start",
1544
- index: a,
1545
- toolCallId: e,
1546
- toolName: i
1547
- };
1548
- }
1549
- continue;
1550
- }
1551
- if (t === "response.function_call_arguments.delta") {
1552
- let t = typeof e.call_id == "string" ? e.call_id : "", r = typeof e.delta == "string" ? e.delta : "", i = n.get(t);
1553
- i && r.length > 0 && (i.argsJson += r, yield {
1554
- type: "tool-call-args-delta",
1555
- index: i.index,
1556
- toolCallId: t,
1557
- toolName: i.name,
1558
- argsDelta: r
1559
- });
1560
- continue;
1561
- }
1562
- if (t === "response.function_call_arguments.done") {
1563
- let t = typeof e.call_id == "string" ? e.call_id : "", r = typeof e.arguments == "string" ? e.arguments : "", i = n.get(t);
1564
- i && (r && (i.argsJson = r), yield {
1565
- type: "tool-call-ready",
1566
- index: i.index,
1567
- toolCallId: t,
1568
- toolName: i.name,
1569
- args: q(i.argsJson || r)
1570
- });
1571
- continue;
1572
- }
1573
- if (t === "response.completed") {
1574
- let t = e.response;
1575
- t && Array.isArray(t.output) && (i = t.output);
1576
- let n = y(t?.usage);
1577
- n && (yield {
1578
- type: "usage",
1579
- usage: n
1580
- });
1581
- continue;
1582
- }
1583
- if (t === "error") return yield {
1584
- type: "error",
1585
- message: typeof e.message == "string" ? e.message : "OpenAI Responses stream error"
1586
- }, [];
1587
- }
1588
- return yield { type: "done" }, i;
1589
- }
1590
- async function Y(e) {
1591
- let t = await fetch(B(e.config, "/responses"), {
1592
- method: "POST",
1593
- headers: V(e.config),
1594
- body: JSON.stringify(G(e, !1)),
1595
- signal: e.signal
1596
- });
1597
- if (!t.ok) throw Error(await H(t));
1598
- let n = await t.json(), r = n.status;
1599
- if (r !== "completed" && r !== void 0) throw Error(`OpenAI response ended with status ${String(r)}`);
1600
- let i = Array.isArray(n.output) ? n.output : [], a = K(i);
1601
- return {
1602
- text: typeof n.output_text == "string" ? n.output_text : Fe(i),
1603
- output: i,
1604
- toolCalls: a.map((e) => ({
1605
- id: e.call_id,
1606
- name: e.name,
1607
- args: q(e.arguments)
1608
- }))
1609
- };
1610
- }
1611
- var Ie = class {
1612
- constructor(e) {
1613
- this.config = e;
1614
- }
1615
- managesToolLoop = !0;
1616
- stream(e) {
1617
- return this.streamSingleTurn(e);
1618
- }
1619
- async complete(e) {
1620
- let { instructions: t, input: n } = U(e.messages), r = await Y({
1621
- config: this.config,
1622
- instructions: t,
1623
- input: n,
1624
- tools: e.tools,
1625
- signal: e.signal
1626
- });
1627
- return {
1628
- text: r.text,
1629
- toolCalls: r.toolCalls
1630
- };
1631
- }
1632
- async *streamToolLoop(e) {
1633
- let { instructions: t, input: n } = U(e.messages), r = [...n], i = e.maxSteps ?? 10;
1634
- for (let n = 0; n < i; n++) {
1635
- if (e.signal?.aborted) return;
1636
- let n = J({
1637
- config: this.config,
1638
- instructions: t,
1639
- input: r,
1640
- tools: e.tools,
1641
- signal: e.signal
1642
- }), i = [];
1643
- for (;;) {
1644
- let e = await n.next();
1645
- if (e.done) {
1646
- i = e.value ?? [];
1647
- break;
1648
- }
1649
- if (yield e.value, e.value.type === "error") return;
1650
- }
1651
- r.push(...i);
1652
- let a = K(i);
1653
- if (a.length === 0) return;
1654
- for (let t of a) {
1655
- if (e.signal?.aborted) return;
1656
- let n = {};
1657
- try {
1658
- n = JSON.parse(t.arguments);
1659
- } catch {
1660
- n = {};
1661
- }
1662
- let i, a = !1;
1663
- try {
1664
- i = await e.callTool(t.name, n), a = c(i);
1665
- } catch (e) {
1666
- a = !0, i = {
1667
- isError: !0,
1668
- error: e instanceof Error ? e.message : String(e)
1669
- };
1670
- }
1671
- W(r, t.call_id, t.name, i), yield {
1672
- type: "tool-result",
1673
- toolCallId: t.call_id,
1674
- toolName: t.name,
1675
- result: i,
1676
- isError: a
1677
- };
1678
- }
1679
- }
1680
- }
1681
- async runToolLoopNonStreaming(e) {
1682
- let { instructions: t, input: n } = U(e.messages), r = [...n], i = e.maxSteps ?? 10, a = [], o = "";
1683
- for (let n = 0; n < i && !e.signal?.aborted; n++) {
1684
- let n = await Y({
1685
- config: this.config,
1686
- instructions: t,
1687
- input: r,
1688
- tools: e.tools,
1689
- signal: e.signal
1690
- });
1691
- if (r.push(...n.output), n.toolCalls.length === 0) {
1692
- o = n.text;
1693
- break;
1694
- }
1695
- for (let t of n.toolCalls) {
1696
- let n;
1697
- try {
1698
- n = await e.callTool(t.name, t.args), c(n);
1699
- } catch (e) {
1700
- n = {
1701
- isError: !0,
1702
- error: e instanceof Error ? e.message : String(e)
1703
- };
1704
- }
1705
- a.push({
1706
- toolName: t.name,
1707
- args: t.args,
1708
- result: n
1709
- }), W(r, t.id, t.name, n);
1710
- }
1711
- }
1712
- return {
1713
- content: o,
1714
- toolCalls: a
1715
- };
1716
- }
1717
- async *streamSingleTurn(e) {
1718
- let { instructions: t, input: n } = U(e.messages), r = J({
1719
- config: this.config,
1720
- instructions: t,
1721
- input: n,
1722
- tools: e.tools,
1723
- signal: e.signal
1724
- });
1725
- for (;;) {
1726
- let e = await r.next();
1727
- if (e.done || (yield e.value, e.value.type === "error")) return;
1728
- }
1729
- }
1730
- };
1731
- function X(e) {
1732
- return e.provider === "openai" ? new Ie(e) : new Le(e);
1733
- }
1734
- var Le = class {
1735
- constructor(e) {
1736
- this.config = e;
1737
- }
1738
- stream(e) {
1739
- return Ae({
1740
- config: this.config,
1741
- messages: e.messages,
1742
- tools: e.tools,
1743
- signal: e.signal
1744
- });
1745
- }
1746
- async complete(e) {
1747
- let t = await je({
1748
- config: this.config,
1749
- messages: e.messages,
1750
- tools: e.tools,
1751
- signal: e.signal
1752
- });
1753
- return {
1754
- text: t.text,
1755
- toolCalls: t.toolCalls
1756
- };
1757
- }
1758
- };
1759
- async function* Re(e) {
1760
- if (e.driver.managesToolLoop && e.driver.streamToolLoop) {
1761
- yield* e.driver.streamToolLoop(e);
1762
- return;
1763
- }
1764
- let { driver: t, tools: n, callTool: r, signal: i } = e, a = e.maxSteps ?? 10, o = [...e.messages];
1765
- for (let e = 0; e < a; e++) {
1766
- if (i?.aborted) return;
1767
- let e = [], a = "";
1768
- try {
1769
- for await (let r of t.stream({
1770
- messages: o,
1771
- tools: n,
1772
- signal: i
1773
- })) r.type === "text-delta" ? a += r.delta : r.type === "tool-call-ready" && e.push({
1774
- id: r.toolCallId,
1775
- name: r.toolName,
1776
- args: r.args
1777
- }), yield r;
1778
- } catch (e) {
1779
- if (e instanceof M) throw e;
1780
- yield {
1781
- type: "error",
1782
- message: e instanceof Error ? e.message : String(e)
1783
- };
1784
- return;
1785
- }
1786
- if (e.length === 0) return;
1787
- o.push({
1788
- role: "assistant",
1789
- content: a,
1790
- toolCalls: e
1791
- });
1792
- for (let t of e) {
1793
- if (i?.aborted) return;
1794
- let e, n = !1;
1795
- try {
1796
- e = await r(t.name, t.args), n = c(e);
1797
- } catch (t) {
1798
- n = !0, e = {
1799
- isError: !0,
1800
- error: t instanceof Error ? t.message : String(t)
1801
- };
1802
- }
1803
- o.push({
1804
- role: "tool",
1805
- content: d(e),
1806
- toolCallId: t.id,
1807
- toolName: t.name,
1808
- toolResult: e,
1809
- toolIsError: n
1810
- }), yield {
1811
- type: "tool-result",
1812
- toolCallId: t.id,
1813
- toolName: t.name,
1814
- result: e,
1815
- isError: n
1816
- };
1817
- }
1818
- }
1819
- }
1820
- async function ze(e) {
1821
- if (e.driver.managesToolLoop && e.driver.runToolLoopNonStreaming) return e.driver.runToolLoopNonStreaming(e);
1822
- let { driver: t, tools: n, callTool: r, signal: i } = e, a = e.maxSteps ?? 10, o = [...e.messages], s = [], l = "";
1823
- for (let e = 0; e < a && !i?.aborted; e++) {
1824
- let { text: e, toolCalls: a } = await t.complete({
1825
- messages: o,
1826
- tools: n,
1827
- signal: i
1828
- });
1829
- if (a.length === 0) {
1830
- l = e;
1831
- break;
1832
- }
1833
- o.push({
1834
- role: "assistant",
1835
- content: e,
1836
- toolCalls: a
1837
- });
1838
- for (let e of a) {
1839
- let t, n = !1;
1840
- try {
1841
- t = await r(e.name, e.args), n = c(t);
1842
- } catch (e) {
1843
- n = !0, t = {
1844
- isError: !0,
1845
- error: e instanceof Error ? e.message : String(e)
1846
- };
1847
- }
1848
- s.push({
1849
- toolName: e.name,
1850
- args: e.args,
1851
- result: t
1852
- }), o.push({
1853
- role: "tool",
1854
- content: d(t),
1855
- toolCallId: e.id,
1856
- toolName: e.name,
1857
- toolResult: t,
1858
- toolIsError: n
1859
- });
1860
- }
1861
- }
1862
- return {
1863
- content: l,
1864
- toolCalls: s
1865
- };
1866
- }
1867
- async function* Z(e, t) {
1868
- yield* Re({
1869
- driver: e,
1870
- messages: t.messages,
1871
- tools: t.tools,
1872
- callTool: t.callTool,
1873
- maxSteps: t.maxSteps,
1874
- signal: t.signal
1875
- });
1876
- }
1877
- async function* Be(e, t) {
1878
- let n = "", r = null;
1879
- for await (let i of Z(e, t)) if (i.type === "text-delta") n += i.delta;
1880
- else if (i.type === "tool-call-ready") r = {
1881
- action: {
1882
- tool: i.toolName,
1883
- toolInput: i.args,
1884
- log: `Calling tool ${i.toolName}`
1885
- },
1886
- observation: ""
1887
- }, yield r;
1888
- else if (i.type === "tool-result" && r) {
1889
- let e = typeof i.result == "string" ? i.result : JSON.stringify(i.result ?? "");
1890
- yield {
1891
- action: r.action,
1892
- observation: e
1893
- }, r = null;
1894
- } else if (i.type === "error") throw Error(i.message);
1895
- return n;
1896
- }
1897
- async function Ve(e, t) {
1898
- return (await ze({
1899
- driver: e,
1900
- messages: t.messages,
1901
- tools: t.tools,
1902
- callTool: t.callTool,
1903
- maxSteps: t.maxSteps,
1904
- signal: t.signal
1905
- })).content;
1906
- }
1907
- var He = {
1908
- openai: ["OPENAI_API_KEY"],
1909
- anthropic: ["ANTHROPIC_API_KEY"],
1910
- google: ["GOOGLE_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY"],
1911
- openrouter: ["OPENROUTER_API_KEY"],
1912
- ollama: [],
1913
- "openai-compatible": ["OPENAI_API_KEY"]
1914
- };
1915
- function Ue(e, n) {
1916
- if (n?.apiKey) return n.apiKey;
1917
- let r = He[e] ?? [];
1918
- if (typeof process < "u") for (let n of r) {
1919
- let r = {}[n];
1920
- if (r) return t.debug(`Using API key from ${n} for ${e}`), r;
1921
- }
1922
- if (e === "ollama") return "";
1923
- let i = r.length > 0 ? r.join(" or ") : "apiKey in llmConfig";
1924
- throw Error(`API key not found for provider '${e}'. Set ${i}.`);
1925
- }
1926
- function Q(e, t) {
1927
- let n = e.split("/");
1928
- if (n.length < 2) throw Error(`Invalid LLM string '${e}'. Expected 'provider/model'.`);
1929
- let r = n[0].toLowerCase(), i = n.slice(1).join("/"), a = [
1930
- "openai",
1931
- "anthropic",
1932
- "google",
1933
- "openrouter",
1934
- "ollama",
1935
- "openai-compatible"
1936
- ];
1937
- if (!a.includes(r)) throw Error(`Unsupported provider '${r}'. Supported: ${a.join(", ")}`);
1938
- return {
1939
- provider: r,
1940
- model: i,
1941
- apiKey: Ue(r, t),
1942
- temperature: t?.temperature,
1943
- maxTokens: t?.maxTokens,
1944
- baseUrl: t?.baseUrl,
1945
- extraHeaders: t?.extraHeaders,
1946
- credentials: t?.credentials
1947
- };
1948
- }
1949
- function We(e, t, n) {
1950
- return {
1951
- provider: e,
1952
- model: t,
1953
- apiKey: Ue(e, n),
1954
- temperature: n?.temperature,
1955
- maxTokens: n?.maxTokens,
1956
- baseUrl: n?.baseUrl,
1957
- extraHeaders: n?.extraHeaders,
1958
- credentials: n?.credentials
1959
- };
1960
- }
1961
- var Ge = "2.0.0-beta.10";
1962
- function Ke() {
1963
- return Ge;
1964
- }
1965
- function $(e, t, n, r, i, a) {
1966
- return typeof e == "object" && e ? {
1967
- prompt: e.prompt,
1968
- maxSteps: e.maxSteps,
1969
- manageConnector: e.manageConnector,
1970
- messages: e.messages,
1971
- schema: e.schema,
1972
- signal: e.signal
1973
- } : {
1974
- prompt: e,
1975
- maxSteps: t,
1976
- manageConnector: n,
1977
- schema: i,
1978
- signal: a
1979
- };
1980
- }
1981
- var qe = "/api/v1/chats", Je = "/api/v1/chats/{chat_id}/execute";
1982
- function Ye(e, t, n, r, i) {
1983
- if (typeof e == "object" && e) {
1984
- let t = e;
1985
- return {
1986
- query: t.prompt ?? "",
1987
- maxSteps: t.maxSteps,
1988
- manageConnector: t.manageConnector,
1989
- externalHistory: t.externalHistory,
1990
- outputSchema: t.schema
1991
- };
1992
- }
1993
- return {
1994
- query: e,
1995
- maxSteps: t,
1996
- manageConnector: n,
1997
- externalHistory: r,
1998
- outputSchema: i
1999
- };
2000
- }
2001
- var Xe = class {
2002
- agentId;
2003
- apiKey;
2004
- baseUrl;
2005
- chatId = null;
2006
- constructor(e) {
2007
- this.agentId = e.agentId, this.baseUrl = e.baseUrl ?? "https://cloud.manufact.com";
2008
- let t = e.apiKey ?? (typeof process < "u" && {}.MCP_USE_API_KEY);
2009
- if (!t) throw Error("API key is required for remote execution. Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. You can get an API key from https://cloud.manufact.com");
2010
- this.apiKey = t;
2011
- }
2012
- pydanticToJsonSchema(t) {
2013
- return e(t);
2014
- }
2015
- parseStructuredResponse(e, n) {
2016
- let r;
2017
- if (typeof e == "object" && e) if ("result" in e) {
2018
- let t = e.result;
2019
- r = typeof t == "object" && t && "result" in t ? t.result : t;
2020
- } else r = e;
2021
- else if (typeof e == "string") try {
2022
- r = JSON.parse(e);
2023
- } catch {
2024
- r = { content: e };
2025
- }
2026
- else r = e;
2027
- try {
2028
- return n.parse(r);
2029
- } catch (e) {
2030
- t.warn(`Failed to parse structured output: ${e}`);
2031
- let i = n._def?.shape();
2032
- if (i && "content" in i) return n.parse({ content: String(r) });
2033
- throw e;
2034
- }
2035
- }
2036
- async createChatSession() {
2037
- let e = {
2038
- title: `Remote Agent Session - ${this.agentId}`,
2039
- agent_id: this.agentId,
2040
- type: "agent_execution"
2041
- }, n = {
2042
- "Content-Type": "application/json",
2043
- "x-api-key": this.apiKey
2044
- }, r = `${this.baseUrl}${qe}`;
2045
- t.debug(`\u{1F4DD} Creating chat session for agent ${this.agentId}`);
2046
- try {
2047
- let i = await fetch(r, {
2048
- method: "POST",
2049
- headers: n,
2050
- body: JSON.stringify(e)
2051
- });
2052
- if (!i.ok) {
2053
- let e = await i.text(), t = i.status;
2054
- throw Error(t === 404 ? `Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.` : `Failed to create chat session: ${t} - ${e}`);
2055
- }
2056
- let a = (await i.json()).id;
2057
- return t.debug(`\u2705 Chat session created: ${a}`), a;
2058
- } catch (e) {
2059
- throw e instanceof Error ? TypeError(`Failed to create chat session: ${e.message}`) : Error(`Failed to create chat session: ${String(e)}`);
2060
- }
2061
- }
2062
- async run(e, n, r, i, a) {
2063
- let { query: o, maxSteps: s, externalHistory: c, outputSchema: l } = Ye(e, n, r, i, a);
2064
- c !== void 0 && t.warn("External history is not yet supported for remote execution");
2065
- try {
2066
- t.debug(`\u{1F310} Executing query on remote agent ${this.agentId}`), this.chatId === null && (this.chatId = await this.createChatSession());
2067
- let e = this.chatId, n = {
2068
- query: o,
2069
- max_steps: s ?? 10
2070
- };
2071
- l && (n.output_schema = this.pydanticToJsonSchema(l), t.debug("🔧 Using structured output with schema"));
2072
- let r = {
2073
- "Content-Type": "application/json",
2074
- "x-api-key": this.apiKey
2075
- }, i = `${this.baseUrl}${Je.replace("{chat_id}", e)}`;
2076
- t.debug(`\u{1F680} Executing agent in chat ${e}`);
2077
- let a = await fetch(i, {
2078
- method: "POST",
2079
- headers: r,
2080
- body: JSON.stringify(n),
2081
- signal: AbortSignal.timeout(3e5)
2082
- });
2083
- if (!a.ok) {
2084
- let e = await a.text(), n = a.status;
2085
- throw n === 401 ? (t.error(`\u274C Authentication failed: ${e}`), Error("Authentication failed: Invalid or missing API key. Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.")) : n === 403 ? (t.error(`\u274C Access forbidden: ${e}`), Error(`Access denied: You don't have permission to execute agent '${this.agentId}'. Check if the agent exists and you have the necessary permissions.`)) : n === 404 ? (t.error(`\u274C Agent not found: ${e}`), Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`)) : n === 422 ? (t.error(`\u274C Validation error: ${e}`), Error(`Request validation failed: ${e}. Please check your query parameters and output schema format.`)) : n === 500 ? (t.error(`\u274C Server error: ${e}`), Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")) : (t.error(`\u274C Remote execution failed with status ${n}: ${e}`), Error(`Remote agent execution failed: ${n} - ${e}`));
2086
- }
2087
- let c = await a.json();
2088
- if (t.debug(`\u{1F527} Response: ${JSON.stringify(c)}`), t.debug("✅ Remote execution completed successfully"), typeof c == "object" && c) {
2089
- if (c.status === "error" || c.error !== null) {
2090
- let e = c.error ?? String(c);
2091
- throw t.error(`\u274C Remote agent execution failed: ${e}`), Error(`Remote agent execution failed: ${e}`);
2092
- }
2093
- if (String(c).includes("failed to initialize")) throw t.error(`\u274C Agent initialization failed: ${c}`), Error(`Agent initialization failed on remote server. This usually indicates:
2094
- \u2022 Invalid agent configuration (LLM model, system prompt)
2095
- \u2022 Missing or invalid MCP server configurations
2096
- \u2022 Network connectivity issues with MCP servers
2097
- \u2022 Missing environment variables or credentials
2098
- Raw error: ${c}`);
2099
- }
2100
- return l ? this.parseStructuredResponse(c, l) : typeof c == "object" && c && "result" in c ? c.result : typeof c == "string" ? c : String(c);
2101
- } catch (e) {
2102
- throw e instanceof Error ? e.name === "AbortError" ? (t.error(`\u274C Remote execution timed out: ${e}`), Error("Remote agent execution timed out. The server may be overloaded or the query is taking too long to process. Try again or use a simpler query.")) : (t.error(`\u274C Remote execution error: ${e}`), Error(`Remote agent execution failed: ${e.message}`)) : (t.error(`\u274C Remote execution error: ${e}`), Error(`Remote agent execution failed: ${String(e)}`));
2103
- }
2104
- }
2105
- async *stream(e, t, n, r, i) {
2106
- return await this.run(e, t, n, r, i);
2107
- }
2108
- async close() {
2109
- t.debug("🔌 Remote agent client closed");
2110
- }
2111
- }, Ze = class {
2112
- static getPackageVersion() {
2113
- return Ke();
2114
- }
2115
- driver;
2116
- client;
2117
- connectors = [];
2118
- clientOwnedByAgent = !1;
2119
- nativeAdapter;
2120
- providerTools = [];
2121
- callTool;
2122
- maxSteps;
2123
- autoInitialize;
2124
- systemPrompt;
2125
- disallowedTools;
2126
- exposeResourcesAsTools;
2127
- exposePromptsAsTools;
2128
- initialized = !1;
2129
- isRemote = !1;
2130
- remoteAgent = null;
2131
- isSimplifiedMode = !1;
2132
- llmString;
2133
- llmConfig;
2134
- mcpServersConfig;
2135
- explicitProviderConfig;
2136
- conversationMessages = [];
2137
- memoryEnabled;
2138
- boundConnections;
2139
- constructor(e) {
2140
- if (e.agentId) {
2141
- this.isRemote = !0, this.remoteAgent = new Xe({
2142
- agentId: e.agentId,
2143
- apiKey: e.apiKey,
2144
- baseUrl: e.baseUrl
2145
- }), this.maxSteps = e.maxSteps ?? 10, this.autoInitialize = e.autoInitialize ?? !1, this.nativeAdapter = new i(), this.systemPrompt = e.systemPrompt ?? "You are a helpful assistant with access to MCP tools.", this.disallowedTools = [], this.exposeResourcesAsTools = !0, this.exposePromptsAsTools = !0, this.memoryEnabled = e.memoryEnabled ?? !0;
2146
- return;
2147
- }
2148
- if (this.maxSteps = e.maxSteps ?? 10, this.autoInitialize = e.autoInitialize ?? !1, this.systemPrompt = e.systemPrompt ?? "You are a helpful assistant with access to MCP tools.", this.disallowedTools = e.disallowedTools ?? [], this.exposeResourcesAsTools = e.exposeResourcesAsTools ?? !0, this.exposePromptsAsTools = e.exposePromptsAsTools ?? !0, this.memoryEnabled = e.memoryEnabled ?? !0, this.nativeAdapter = new i(this.disallowedTools), this.llmConfig = e.llmConfig, this.resolveMcpServers(e.mcpServers), typeof e.llm == "string") {
2149
- if (this.isSimplifiedMode = !0, this.llmString = e.llm, !this.hasLiveConnections() && (!this.mcpServersConfig || Object.keys(this.mcpServersConfig).length === 0) && !e.client && !e.connectors?.length) throw Error("Simplified mode requires mcpServers, or an existing client/connectors.");
2150
- } else if (this.explicitProviderConfig = e.llm, this.client = e.client, this.connectors = e.connectors ?? [], !this.hasLiveConnections() && !this.client && this.connectors.length === 0 && (!this.mcpServersConfig || Object.keys(this.mcpServersConfig).length === 0)) throw Error("Explicit mode requires mcpServers, client, or connectors.");
2151
- e.client && (this.client = e.client), e.connectors?.length && (this.connectors = e.connectors), this.hasLiveConnections() && this.explicitProviderConfig ? this.bindConnections(this.boundConnections, this.explicitProviderConfig) : this.hasLiveConnections() && this.llmString && (this.driver = X(Q(this.llmString, this.llmConfig)), this.bindConnections(this.boundConnections, Q(this.llmString, this.llmConfig)));
2152
- }
2153
- resolveMcpServers(e) {
2154
- if (e) {
2155
- if (Array.isArray(e)) {
2156
- this.boundConnections = e;
2157
- return;
2158
- }
2159
- this.mcpServersConfig = e;
2160
- }
2161
- }
2162
- hasLiveConnections() {
2163
- return (this.boundConnections?.length ?? 0) > 0;
2164
- }
2165
- async initialize() {
2166
- if (this.isRemote) {
2167
- this.initialized = !0;
2168
- return;
2169
- }
2170
- if (!this.initialized) {
2171
- if (this.isSimplifiedMode) {
2172
- if (!this.client && this.mcpServersConfig) {
2173
- let { MCPClient: e } = await import("./index-browser-DO-sd0TA.js").then((e) => e.n);
2174
- this.client = new e({ mcpServers: this.mcpServersConfig }), this.clientOwnedByAgent = !0;
2175
- }
2176
- this.llmString && (this.driver = X(Q(this.llmString, this.llmConfig)));
2177
- } else this.explicitProviderConfig && (this.driver = X(this.explicitProviderConfig));
2178
- if (!this.driver) throw Error("LLM driver not configured.");
2179
- this.hasLiveConnections() || await this.loadTools(), this.initialized = !0, t.debug("MCPAgent initialized");
2180
- }
2181
- }
2182
- async loadTools() {
2183
- let e = [];
2184
- if (this.client) {
2185
- (!this.client.activeSessions || Object.keys(this.client.activeSessions).length === 0) && await this.client.createAllSessions();
2186
- let t = this.client.getAllActiveSessions(), n = Object.values(t).map((e) => e.connector);
2187
- e.push(...await this.nativeAdapter.createToolsFromConnectors(n)), this.exposeResourcesAsTools && e.push(...await this.nativeAdapter.createResourcesFromConnectors(n)), this.exposePromptsAsTools && e.push(...await this.nativeAdapter.createPromptsFromConnectors(n));
2188
- } else {
2189
- for (let e of this.connectors) e.isClientConnected || await e.connect();
2190
- e.push(...await this.nativeAdapter.createToolsFromConnectors(this.connectors)), this.exposeResourcesAsTools && e.push(...await this.nativeAdapter.createResourcesFromConnectors(this.connectors)), this.exposePromptsAsTools && e.push(...await this.nativeAdapter.createPromptsFromConnectors(this.connectors));
2191
- }
2192
- this.providerTools = this.nativeAdapter.toProviderTools(e), this.callTool = this.nativeAdapter.createCallTool();
2193
- }
2194
- bindConnections(e, t) {
2195
- let n = new Set(this.disallowedTools), r = /* @__PURE__ */ new Set(), i = /* @__PURE__ */ new Map(), a = (e) => {
2196
- if (!r.has(e)) return r.add(e), e;
2197
- let t = 2;
2198
- for (; r.has(`${e}_${t}`);) t++;
2199
- let n = `${e}_${t}`;
2200
- return r.add(n), n;
2201
- }, o = [];
2202
- for (let t of e) for (let e of t.tools ?? []) {
2203
- if (n.has(e.name)) continue;
2204
- let r = a(e.name);
2205
- i.set(r, {
2206
- connection: t,
2207
- mcpName: e.name
2208
- }), o.push({
2209
- name: r,
2210
- description: e.description,
2211
- inputSchema: e.inputSchema ?? {
2212
- type: "object",
2213
- properties: {}
2214
- }
2215
- });
2216
- }
2217
- this.providerTools = o, this.callTool = async (e, t) => {
2218
- let n = i.get(e);
2219
- if (!n) throw Error(`Unknown tool: ${e}`);
2220
- return n.connection.callTool(n.mcpName, t);
2221
- }, this.driver = X(t), this.initialized = !0;
2222
- }
2223
- buildMessages(e) {
2224
- let t = [{
2225
- role: "system",
2226
- content: this.systemPrompt
2227
- }];
2228
- return this.memoryEnabled && this.conversationMessages.length > 0 && t.push(...this.conversationMessages), e.messages?.length && t.push(...e.messages), e.prompt && t.push({
2229
- role: "user",
2230
- content: e.prompt
2231
- }), t;
2232
- }
2233
- getConversationHistory() {
2234
- return [...this.conversationMessages];
2235
- }
2236
- clearConversationHistory() {
2237
- this.conversationMessages = [];
2238
- }
2239
- setSystemMessage(e) {
2240
- this.systemPrompt = e;
2241
- }
2242
- async ensureReady(e = !0) {
2243
- if (e && !this.initialized) if (this.autoInitialize) await this.initialize();
2244
- else throw Error("MCPAgent not initialized. Call initialize() first.");
2245
- if (!this.driver || !this.callTool) throw Error("MCPAgent driver or tools not ready.");
2246
- }
2247
- nativeRunParams(e) {
2248
- return {
2249
- messages: this.buildMessages(e),
2250
- tools: this.providerTools,
2251
- callTool: this.callTool,
2252
- maxSteps: e.maxSteps ?? this.maxSteps,
2253
- signal: e.signal
2254
- };
2255
- }
2256
- async run(e, t, n, r, i, a) {
2257
- let o = $(e, t, n, r, i, a);
2258
- if (o.schema) throw Error("Structured output requires @mcp-use/agent/langchain or pass a JSON schema via prompt.");
2259
- if (this.isRemote && this.remoteAgent) return this.remoteAgent.run(o.prompt ?? "", o.maxSteps, o.manageConnector);
2260
- await this.ensureReady(o.manageConnector ?? !0);
2261
- let s = await Ve(this.driver, this.nativeRunParams(o));
2262
- return this.memoryEnabled && o.prompt && (this.conversationMessages.push({
2263
- role: "user",
2264
- content: o.prompt
2265
- }), this.conversationMessages.push({
2266
- role: "assistant",
2267
- content: s
2268
- })), s;
2269
- }
2270
- async *stream(e, t, n, r, i, a) {
2271
- let o = $(e, t, n, r, i, a);
2272
- if (this.isRemote && this.remoteAgent) return await this.remoteAgent.run(o.prompt ?? "", o.maxSteps, o.manageConnector);
2273
- await this.ensureReady(o.manageConnector ?? !0);
2274
- let s = yield* Be(this.driver, this.nativeRunParams(o));
2275
- return this.memoryEnabled && o.prompt && (this.conversationMessages.push({
2276
- role: "user",
2277
- content: o.prompt
2278
- }), this.conversationMessages.push({
2279
- role: "assistant",
2280
- content: s
2281
- })), s;
2282
- }
2283
- async *streamEvents(e, t, n, r, i, a) {
2284
- let o = $(e, t, n, r, i, a);
2285
- if (this.isRemote && this.remoteAgent) throw Error("streamEvents is not supported for remote agents.");
2286
- await this.ensureReady(o.manageConnector ?? !0), yield* Z(this.driver, this.nativeRunParams(o));
2287
- }
2288
- async chat(e) {
2289
- return await this.ensureReady(), (await this.driver.complete({
2290
- messages: e.messages,
2291
- tools: [],
2292
- signal: e.signal
2293
- })).text;
2294
- }
2295
- async close() {
2296
- this.clientOwnedByAgent && this.client && await this.client.closeAllSessions?.(), this.initialized = !1;
2297
- }
2298
- };
2299
- async function Qe(e) {
2300
- return (await X(e.config).complete({
2301
- messages: e.messages,
2302
- tools: [],
2303
- signal: e.signal
2304
- })).text;
2305
- }
2306
- //#endregion
2307
- export { Qe as a, We as c, D as i, Ze as n, ne as o, Ce as r, E as s, Se as t };