@trilogy-data/trilogy-studio-components 0.1.28 → 0.1.30

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 (110) hide show
  1. package/README.md +1 -0
  2. package/dist/AssetAutoImporter-BA8C4p09.js +403 -0
  3. package/dist/{ChatCreatorModal-Cd40SvdM.js → ChatCreatorModal-94gZ9D-y.js} +1 -1
  4. package/dist/{CodeBlock-Dj-GfTbW.js → CodeBlock-C9o09ipr.js} +1 -1
  5. package/dist/{CommunityModels-lX2RhHCG.js → CommunityModels-D48H9Bqt.js} +6 -6
  6. package/dist/{ConnectionView-CZ06qjjE.js → ConnectionView-sEXGE8Vs.js} +5 -5
  7. package/dist/{CreateEditorFromDatasourcePopup-DwA938kf.js → CreateEditorFromDatasourcePopup-BUoegyem.js} +2 -2
  8. package/dist/{Dashboard-CQsIqWZC.js → Dashboard-C6adKZ7q.js} +202 -203
  9. package/dist/{DashboardImportSelector-CkqH52FX.js → DashboardImportSelector-CQqXshDj.js} +1 -1
  10. package/dist/{DashboardMobile-DWFlel5p.js → DashboardMobile-BU1nDLQv.js} +42 -42
  11. package/dist/{Editor-DQ66Vp6v.js → Editor-DO4VRvek.js} +9 -10
  12. package/dist/{ErrorMessage-D5JeF3Iz.js → ErrorMessage-Cz7q7vJI.js} +1 -1
  13. package/dist/{GlobalChatPanel-B_s3COHE.js → GlobalChatPanel-Ct6oSj_A.js} +20 -20
  14. package/dist/{IDE-4-Jg6gsM.js → IDE-kdaEhA4g.js} +19 -20
  15. package/dist/{JobsView-B5NWDUgP.js → JobsView-BcyWrDRf.js} +11 -11
  16. package/dist/{LLMChat-eKgEc-I3.js → LLMChat-Dg8VvTIP.js} +19 -19
  17. package/dist/{LLMView-CdTwMLVV.js → LLMView-CZNNYXC1.js} +61 -61
  18. package/dist/{LoadingView-Bu3wLJ7J.js → LoadingView-k2CIKiN7.js} +1 -1
  19. package/dist/{MarkdownRenderer-B6lqdkgc.js → MarkdownRenderer-Dlb_KGmk.js} +1 -1
  20. package/dist/{MobileIDE-CZlg20oa.js → MobileIDE-BQcdjWUT.js} +26 -27
  21. package/dist/{ModelCard-Bs_d7Jis.js → ModelCard-Dn2b5WLs.js} +5 -5
  22. package/dist/{ModelView-BP5yyecx.js → ModelView-BEi83zrX.js} +6 -6
  23. package/dist/{PageLoading-DKFeqkmK.js → PageLoading-C7H6q6U6.js} +248 -248
  24. package/dist/{ResultComponent-BaDheojB.js → ResultComponent-DW9Q9tp9.js} +5 -5
  25. package/dist/{Results-CrpHB101.js → Results-N2OttUlb.js} +19 -19
  26. package/dist/{StatusIcon-Clfyy-Yn.js → StatusIcon-B21tjIXx.js} +1 -1
  27. package/dist/{StoreTokenModal-CO5hXMs3.js → StoreTokenModal-CHgvjLGl.js} +1 -1
  28. package/dist/{SymbolsPane-XFVErDFb.js → SymbolsPane-DUrLpSSw.js} +11 -11
  29. package/dist/{TutorialPage-CMcTYDOV.js → TutorialPage-DHgPuFN0.js} +11 -11
  30. package/dist/{VegaLiteChart-DX_LbF3g.js → VegaLiteChart-BqHLSptG.js} +11116 -11067
  31. package/dist/{WelcomePage-B6E35FUa.js → WelcomePage-CN6ptsoF.js} +3 -3
  32. package/dist/agent.js +1349 -0
  33. package/dist/components/VegaLiteChart.vue.d.ts.map +1 -1
  34. package/dist/components/chartControlsManager.d.ts +0 -1
  35. package/dist/components/chartControlsManager.d.ts.map +1 -1
  36. package/dist/{cssMode-zpO2ap2B.js → cssMode-DW4OByy3.js} +2 -2
  37. package/dist/dashboard.js +63 -63
  38. package/dist/dashboards/chartTheme.d.ts +68 -0
  39. package/dist/dashboards/chartTheme.d.ts.map +1 -0
  40. package/dist/dashboards/donutSpec.d.ts +2 -1
  41. package/dist/dashboards/donutSpec.d.ts.map +1 -1
  42. package/dist/dashboards/headlineSpec.d.ts +2 -1
  43. package/dist/dashboards/headlineSpec.d.ts.map +1 -1
  44. package/dist/dashboards/helpers.d.ts +23 -0
  45. package/dist/dashboards/helpers.d.ts.map +1 -1
  46. package/dist/dashboards/index.d.ts +2 -0
  47. package/dist/dashboards/index.d.ts.map +1 -1
  48. package/dist/dashboards/layerSpec.d.ts +4 -1
  49. package/dist/dashboards/layerSpec.d.ts.map +1 -1
  50. package/dist/dashboards/pointSpec.d.ts +2 -1
  51. package/dist/dashboards/pointSpec.d.ts.map +1 -1
  52. package/dist/dashboards/spec.d.ts +8 -1
  53. package/dist/dashboards/spec.d.ts.map +1 -1
  54. package/dist/{editor.main-BQh6DxDB.js → editor.main-TuTbSVcN.js} +22 -22
  55. package/dist/{editorStore-CiWH_nGN.js → editorStore-Czhpct1j.js} +1751 -1181
  56. package/dist/entry.agent.d.ts +12 -0
  57. package/dist/entry.agent.d.ts.map +1 -0
  58. package/dist/entry.llm.d.ts +1 -1
  59. package/dist/entry.llm.d.ts.map +1 -1
  60. package/dist/{freemarker2-DQBqlEXc.js → freemarker2-ZGcKAI8o.js} +1 -1
  61. package/dist/{globalChatRuntime-DAERmOdu.js → globalChatRuntime-BnMYNYqe.js} +35 -35
  62. package/dist/{handlebars-tgYxaM70.js → handlebars-B3s0Qrrb.js} +1 -1
  63. package/dist/{helpers-C2pARJoZ.js → helpers-B3tq3RZK.js} +17 -17
  64. package/dist/{html-jJahD3Mi.js → html-DM1koKCG.js} +1 -1
  65. package/dist/{htmlMode-BA1-8l2e.js → htmlMode-CpPImbDh.js} +2 -2
  66. package/dist/{javascript-Cypfo7va.js → javascript-jClqu73w.js} +1 -1
  67. package/dist/{jsonMode-xJye8PWS.js → jsonMode-CwFYTPO9.js} +2 -2
  68. package/dist/{liquid-BGDrv5da.js → liquid-C6l-UINC.js} +1 -1
  69. package/dist/llm/chatAgentPrompt.d.ts +4 -16
  70. package/dist/llm/chatAgentPrompt.d.ts.map +1 -1
  71. package/dist/llm/dashboardAgentRuntime.d.ts +10 -10
  72. package/dist/llm/dashboardAgentTools.d.ts +10 -10
  73. package/dist/llm/data/prompts.d.ts +1 -1
  74. package/dist/llm/data/prompts.d.ts.map +1 -1
  75. package/dist/llm/data/trilogySyntax.generated.d.ts +3 -3
  76. package/dist/llm/data/trilogySyntax.generated.d.ts.map +1 -1
  77. package/dist/llm/returnToUserTool.d.ts +20 -0
  78. package/dist/llm/returnToUserTool.d.ts.map +1 -0
  79. package/dist/llm/toolLoopCore.d.ts +7 -0
  80. package/dist/llm/toolLoopCore.d.ts.map +1 -1
  81. package/dist/llm/utils.d.ts.map +1 -1
  82. package/dist/{llm-Wf4Etiu9.js → llm-Bc1CfjOE.js} +2203 -2722
  83. package/dist/llm.js +3 -3
  84. package/dist/{localStorage-C3xms-ab.js → localStorage-Cy0sHlT0.js} +19 -19
  85. package/dist/{lspLanguageFeatures-V3e_p9oN.js → lspLanguageFeatures-GDtuGOTD.js} +1 -1
  86. package/dist/{mdx-BUR1aImW.js → mdx-BQEQ0k1f.js} +1 -1
  87. package/dist/monaco.js +3 -3
  88. package/dist/{python-YLkl0pc6.js → python-USoVCfWY.js} +1 -1
  89. package/dist/{razor-BP8TRMDY.js → razor-BxmgiR-q.js} +1 -1
  90. package/dist/{reconcile-BH_ReGDR.js → reconcile-DtPcgEjQ.js} +1 -1
  91. package/dist/{remoteStoreSync-B0K8QScO.js → remoteStoreSync-CscErZ-I.js} +2 -2
  92. package/dist/{stores-DTGQZ4_B.js → stores-DgdADCiH.js} +323 -323
  93. package/dist/stores.js +3 -4
  94. package/dist/trilogy-studio-components.css +1 -1
  95. package/dist/{tsMode-BH9HS_sH.js → tsMode-BEQ7aXX4.js} +1 -1
  96. package/dist/{typescript-BM-ynfk9.js → typescript-CzBSjjfY.js} +1 -1
  97. package/dist/{useChatWithTools-BSrzJtYI.js → useChatWithTools-CMhGxdyr.js} +14 -14
  98. package/dist/{useDashboard-CGeIdDuX.js → useDashboard-CjZgjmgb.js} +553 -553
  99. package/dist/{useGlobalChatPanel-D9kMZLeF.js → useGlobalChatPanel-Doeilj18.js} +69 -70
  100. package/dist/views/LLMView.vue.d.ts +23 -23
  101. package/dist/views/TutorialPage.vue.d.ts +10 -10
  102. package/dist/views.js +147 -148
  103. package/dist/vite.agent.config.d.ts +3 -0
  104. package/dist/vite.agent.config.d.ts.map +1 -0
  105. package/dist/{workers-B9Eybl-M.js → workers-CHvkad0r.js} +2 -2
  106. package/dist/{xml-M5WFPSpA.js → xml-ODdyS0gX.js} +1 -1
  107. package/dist/{yaml-CEeFwjz9.js → yaml-PCBTA2qD.js} +1 -1
  108. package/package.json +7 -2
  109. package/dist/AssetAutoImporter-C_7Ms9xe.js +0 -403
  110. package/dist/rolldown-runtime-B0aSnxlc.js +0 -20
package/dist/agent.js ADDED
@@ -0,0 +1,1349 @@
1
+ Object.fromEntries([
2
+ {
3
+ value: "demo",
4
+ label: "Demo (limited messages)"
5
+ },
6
+ {
7
+ value: "anthropic",
8
+ label: "Anthropic"
9
+ },
10
+ {
11
+ value: "google",
12
+ label: "Google"
13
+ },
14
+ {
15
+ value: "openai",
16
+ label: "OpenAI"
17
+ },
18
+ {
19
+ value: "openrouter",
20
+ label: "OpenRouter"
21
+ },
22
+ {
23
+ value: "deepseek",
24
+ label: "DeepSeek"
25
+ }
26
+ ].map((e) => [e.value, e.label]));
27
+ //#endregion
28
+ //#region llm/base.ts
29
+ function e(e) {
30
+ return typeof e == "number" && Number.isFinite(e) ? Math.max(0, Math.floor(e)) : null;
31
+ }
32
+ var t = class {
33
+ apiKey;
34
+ models;
35
+ name;
36
+ model;
37
+ fastModel = null;
38
+ compactionThresholdTokens = null;
39
+ storage;
40
+ type = "generic";
41
+ connected;
42
+ error = null;
43
+ saveCredential;
44
+ isDefault = !1;
45
+ changed = !1;
46
+ deleted = !1;
47
+ running = !1;
48
+ constructor(e, t, n, r = !1) {
49
+ this.apiKey = t, this.models = [], this.name = e, this.model = n, this.fastModel = null, this.compactionThresholdTokens = null, this.storage = "local", this.connected = !1, this.error = null, this.saveCredential = r, this.isDefault = !1, this.changed = !1, this.deleted = !1, this.running = !1;
50
+ }
51
+ setApiKey(e) {
52
+ this.apiKey !== e && (this.changed = !0, this.apiKey = e);
53
+ }
54
+ setModel(e) {
55
+ this.model !== e && (this.changed = !0, this.model = e);
56
+ }
57
+ setFastModel(e) {
58
+ this.fastModel !== e && (this.changed = !0, this.fastModel = e);
59
+ }
60
+ setCompactionThresholdTokens(e) {
61
+ let t = e == null || !Number.isFinite(e) ? null : Math.max(0, Math.floor(e));
62
+ this.compactionThresholdTokens !== t && (this.changed = !0, this.compactionThresholdTokens = t);
63
+ }
64
+ getCompactionThresholdTokens() {
65
+ return this.compactionThresholdTokens ?? 2e5;
66
+ }
67
+ setSaveCredential(e) {
68
+ this.saveCredential !== e && (this.changed = !0, this.saveCredential = e);
69
+ }
70
+ getFastModel() {
71
+ return this.fastModel || this.model;
72
+ }
73
+ getApiKey() {
74
+ return this.apiKey;
75
+ }
76
+ delete() {
77
+ this.deleted = !0, this.changed = !0;
78
+ }
79
+ validateRequestOptions(e) {}
80
+ toJSON() {
81
+ return {
82
+ name: this.name,
83
+ model: this.model,
84
+ fastModel: this.fastModel,
85
+ compactionThresholdTokens: this.compactionThresholdTokens,
86
+ type: this.type,
87
+ apiKey: this.saveCredential ? "saved" : null,
88
+ saveCredential: this.saveCredential,
89
+ isDefault: this.isDefault
90
+ };
91
+ }
92
+ getCredentialName() {
93
+ return `trilogy-llm-${this.type}`;
94
+ }
95
+ static filterModels(e) {
96
+ return e;
97
+ }
98
+ static getDefaultModel(e) {
99
+ return e[0] || "";
100
+ }
101
+ static async fromJSON(t) {
102
+ let n = typeof t == "string" ? JSON.parse(t) : t, r = new this(n.name, n.apiKey, n.model, n.saveCredential);
103
+ return r.isDefault = n.isDefault || !1, r.fastModel = n.fastModel || null, r.compactionThresholdTokens = e(n.compactionThresholdTokens), r;
104
+ }
105
+ }, n = {
106
+ maxRetries: 5,
107
+ initialDelayMs: 1e3,
108
+ backoffMultiplier: 2,
109
+ maxDelayMs: 6e4,
110
+ retryStatusCodes: [
111
+ 429,
112
+ 503,
113
+ 504
114
+ ],
115
+ onRetry: () => {},
116
+ signal: void 0,
117
+ errorBodyExtractor: void 0
118
+ };
119
+ async function r(e, t = {}) {
120
+ let r = {
121
+ ...n,
122
+ ...t
123
+ }, i = 0;
124
+ for (; i <= r.maxRetries;) {
125
+ if (r.signal?.aborted) throw new DOMException("Aborted", "AbortError");
126
+ try {
127
+ return await e();
128
+ } catch (e) {
129
+ if (e instanceof DOMException && e.name === "AbortError" || !(e instanceof Error)) throw e;
130
+ let t = e, n = t.status || t.statusCode;
131
+ if (n === void 0 || !r.retryStatusCodes.includes(n) || i >= r.maxRetries) throw e;
132
+ let a = Math.min(r.initialDelayMs * r.backoffMultiplier ** +i, r.maxDelayMs);
133
+ r.onRetry(i + 1, a, e), await new Promise((e, t) => {
134
+ let n = setTimeout(e, a);
135
+ r.signal && r.signal.addEventListener("abort", () => {
136
+ clearTimeout(n), t(new DOMException("Aborted", "AbortError"));
137
+ }, { once: !0 });
138
+ }), i++;
139
+ }
140
+ }
141
+ throw Error("Maximum retries exceeded");
142
+ }
143
+ async function i(e, t = {}) {
144
+ return r(async () => {
145
+ let n = await e();
146
+ if (!n.ok) {
147
+ let e = `HTTP error ${n.status}: ${n.statusText}`;
148
+ if (t.errorBodyExtractor) try {
149
+ e = await t.errorBodyExtractor(n.clone());
150
+ } catch {}
151
+ let r = Error(e);
152
+ throw r.response = n.clone(), r.status = n.status, r;
153
+ }
154
+ return n;
155
+ }, t);
156
+ }
157
+ //#endregion
158
+ //#region llm/anthropic.ts
159
+ var a = "fable|mythos|opus|sonnet|haiku";
160
+ function o(e) {
161
+ let t = e.match(RegExp(`^claude-(${a})-(\\d+(?:-\\d+)?)-(\\d{8})$`));
162
+ if (t) return {
163
+ version: t[2],
164
+ tier: t[1],
165
+ date: t[3]
166
+ };
167
+ let n = e.match(RegExp(`^claude-(\\d+(?:-\\d+)?)-(${a})-(\\d{8})$`));
168
+ if (n) return {
169
+ version: n[1],
170
+ tier: n[2],
171
+ date: n[3]
172
+ };
173
+ let r = e.match(RegExp(`^claude-(${a})-(\\d+(?:-\\d+)?)$`));
174
+ if (r) return {
175
+ version: r[2],
176
+ tier: r[1],
177
+ date: ""
178
+ };
179
+ let i = e.match(RegExp(`^claude-(\\d+(?:-\\d+)?)-(${a})$`));
180
+ return i ? {
181
+ version: i[1],
182
+ tier: i[2],
183
+ date: ""
184
+ } : null;
185
+ }
186
+ function s(e) {
187
+ let t = o(e);
188
+ if (!t) return !1;
189
+ let n = c(t.version);
190
+ switch (t.tier) {
191
+ case "fable":
192
+ case "mythos": return !0;
193
+ case "opus": return n >= 4.7;
194
+ case "sonnet": return n >= 5;
195
+ default: return !1;
196
+ }
197
+ }
198
+ function c(e) {
199
+ let t = e.split("-").map((e) => parseInt(e, 10));
200
+ return t[0] + (t[1] ?? 0) / 10;
201
+ }
202
+ function l(e, t) {
203
+ let n = o(e), r = o(t);
204
+ if (!n && !r) return e.localeCompare(t);
205
+ if (!n) return 1;
206
+ if (!r) return -1;
207
+ let i = c(n.version), a = c(r.version);
208
+ if (i !== a) return a - i;
209
+ let s = {
210
+ fable: 0,
211
+ mythos: 0,
212
+ opus: 1,
213
+ sonnet: 2,
214
+ haiku: 3
215
+ }, l = s[n.tier] ?? 99, u = s[r.tier] ?? 99;
216
+ if (l !== u) return l - u;
217
+ let d = n.date === "";
218
+ return d === (r.date === "") ? r.date.localeCompare(n.date) : d ? -1 : 1;
219
+ }
220
+ var u = class e extends t {
221
+ baseUrl = "https://api.anthropic.com/v1/messages";
222
+ baseModelUrl = "https://api.anthropic.com/v1/models";
223
+ models = [];
224
+ type = "anthropic";
225
+ retryOptions;
226
+ constructor(t, n, r, i = !1, a) {
227
+ super(t, n, r, i), this.retryOptions = a || {
228
+ maxRetries: 5,
229
+ initialDelayMs: 5e3,
230
+ retryStatusCodes: [
231
+ 429,
232
+ 500,
233
+ 502,
234
+ 503,
235
+ 504
236
+ ],
237
+ errorBodyExtractor: e.extractErrorMessage,
238
+ onRetry: (e, t, n) => {
239
+ console.warn(`Anthropic API retry attempt ${e} after ${t}ms delay due to error: ${n.message}`);
240
+ }
241
+ };
242
+ }
243
+ static async extractErrorMessage(e) {
244
+ let t = `Anthropic API error: HTTP ${e.status}: ${e.statusText}`, n;
245
+ try {
246
+ n = await e.text();
247
+ } catch {
248
+ return t;
249
+ }
250
+ let r;
251
+ try {
252
+ r = JSON.parse(n);
253
+ } catch {
254
+ let e = n.trim().slice(0, 200);
255
+ return e ? `${t} - ${e}` : t;
256
+ }
257
+ return r?.error?.message ? `Anthropic API error${r.error.type ? ` (${r.error.type})` : ""}: ${r.error.message}` : r?.error ? `Anthropic API error: ${JSON.stringify(r.error)}` : t;
258
+ }
259
+ async reset() {
260
+ this.error = null;
261
+ try {
262
+ let t = (await (await i(() => fetch(this.baseModelUrl, {
263
+ headers: {
264
+ "x-api-key": `${this.apiKey}`,
265
+ "anthropic-version": "2023-06-01",
266
+ "anthropic-dangerous-direct-browser-access": "true"
267
+ },
268
+ method: "GET"
269
+ }), this.retryOptions)).json()).data.map((e) => e.id);
270
+ this.models = e.filterModels(t), this.connected = !0;
271
+ } catch (e) {
272
+ throw this.error = e instanceof Error ? e.message : "Unknown error", this.connected = !1, e;
273
+ }
274
+ }
275
+ async generateCompletion(e, t = null) {
276
+ this.validateRequestOptions(e), t ||= [];
277
+ try {
278
+ let n = t.find(({ role: e }) => e === "system"), r = e.systemPrompt ? void 0 : n, a = [];
279
+ for (let e of t) {
280
+ if (e.role === "system") {
281
+ if (e === r) continue;
282
+ e.content && a.push({
283
+ role: "user",
284
+ content: [{
285
+ type: "text",
286
+ text: `<system-reminder>${e.content}</system-reminder>`
287
+ }]
288
+ });
289
+ continue;
290
+ }
291
+ if (e.role === "assistant" && e.toolCalls && e.toolCalls.length > 0) {
292
+ let t = [];
293
+ e.content && t.push({
294
+ type: "text",
295
+ text: e.content
296
+ });
297
+ for (let n of e.toolCalls) t.push({
298
+ type: "tool_use",
299
+ id: n.id,
300
+ name: n.name,
301
+ input: n.input
302
+ });
303
+ a.push({
304
+ role: "assistant",
305
+ content: t
306
+ });
307
+ } else if (e.role === "user" && e.toolResults && e.toolResults.length > 0) {
308
+ let t = e.toolResults.map((e) => {
309
+ if (e.imageData) {
310
+ let t = [];
311
+ return e.result && t.push({
312
+ type: "text",
313
+ text: e.result
314
+ }), t.push({
315
+ type: "image",
316
+ source: {
317
+ type: "base64",
318
+ media_type: e.imageData.mediaType,
319
+ data: e.imageData.data
320
+ }
321
+ }), {
322
+ type: "tool_result",
323
+ tool_use_id: e.toolCallId,
324
+ content: t
325
+ };
326
+ }
327
+ return {
328
+ type: "tool_result",
329
+ tool_use_id: e.toolCallId,
330
+ content: e.result
331
+ };
332
+ });
333
+ a.push({
334
+ role: "user",
335
+ content: t
336
+ });
337
+ } else a.push({
338
+ role: e.role,
339
+ content: e.content
340
+ });
341
+ }
342
+ let o = e.prompt ? a.concat([{
343
+ role: "user",
344
+ content: e.prompt
345
+ }]) : a, c = {
346
+ model: this.model,
347
+ messages: o,
348
+ max_tokens: e.maxTokens ?? 1e4
349
+ };
350
+ s(this.model) || (c.temperature = e.temperature ?? .5, e.topP !== void 0 && (c.top_p = e.topP));
351
+ let l = e.systemPrompt || r?.content;
352
+ l && (c.system = [{
353
+ type: "text",
354
+ text: l,
355
+ cache_control: { type: "ephemeral" }
356
+ }]), e.tools && e.tools.length > 0 && (c.tools = e.tools);
357
+ let u = o[o.length - 1];
358
+ if (u) {
359
+ let e = Array.isArray(u.content) ? u.content : u.content ? [{
360
+ type: "text",
361
+ text: u.content
362
+ }] : [], t = e[e.length - 1];
363
+ t && (e[e.length - 1] = {
364
+ ...t,
365
+ cache_control: { type: "ephemeral" }
366
+ }, o[o.length - 1] = {
367
+ ...u,
368
+ content: e
369
+ });
370
+ }
371
+ let d = await (await i(() => fetch(this.baseUrl, {
372
+ method: "POST",
373
+ headers: {
374
+ "Content-Type": "application/json",
375
+ "x-api-key": `${this.apiKey}`,
376
+ "anthropic-version": "2023-06-01",
377
+ "anthropic-dangerous-direct-browser-access": "true"
378
+ },
379
+ body: JSON.stringify(c),
380
+ signal: e.signal
381
+ }), {
382
+ ...this.retryOptions,
383
+ signal: e.signal,
384
+ onRetry: (t, n, r) => {
385
+ this.retryOptions.onRetry?.(t, n, r), e.onRateLimitBackoff?.(t, n, r);
386
+ }
387
+ })).json();
388
+ if (d.type === "error" || d.error) {
389
+ let e = d.error?.message || d.error?.type || "Unknown API error";
390
+ throw Error(e);
391
+ }
392
+ let f = "", p = [];
393
+ for (let e of Array.isArray(d.content) ? d.content : []) e.type === "text" ? f += e.text : e.type === "tool_use" && p.push({
394
+ id: e.id,
395
+ name: e.name,
396
+ input: e.input
397
+ });
398
+ let m = d.stop_reason ?? void 0;
399
+ if (m === "refusal" && !f && p.length === 0) {
400
+ let e = d.stop_details?.category;
401
+ throw Error(`request was refused for safety reasons${e ? ` (${e})` : ""}`);
402
+ }
403
+ m === "max_tokens" && console.warn(`Anthropic response hit the max_tokens limit (${c.max_tokens}) and is truncated.`);
404
+ let h = d.usage ?? {}, g = h.input_tokens ?? 0, _ = h.output_tokens ?? 0, v = h.cache_creation_input_tokens ?? 0, y = h.cache_read_input_tokens ?? 0;
405
+ return {
406
+ text: f,
407
+ toolCalls: p.length > 0 ? p : void 0,
408
+ stopReason: m,
409
+ usage: {
410
+ promptTokens: g,
411
+ completionTokens: _,
412
+ cacheCreationTokens: v,
413
+ cacheReadTokens: y,
414
+ totalTokens: g + v + y + _
415
+ }
416
+ };
417
+ } catch (e) {
418
+ throw e instanceof Error ? Error(`Anthropic API error: ${e.message}`) : e;
419
+ }
420
+ }
421
+ static filterModels(e) {
422
+ return e.filter((e) => o(e) !== null).sort(l);
423
+ }
424
+ static getDefaultModel(e) {
425
+ let t = [...e].sort(l);
426
+ return t.find((e) => {
427
+ let t = o(e);
428
+ return t !== null && t.tier === "opus";
429
+ }) || t[0] || "";
430
+ }
431
+ };
432
+ //#endregion
433
+ //#region llm/openai.ts
434
+ function d(e) {
435
+ let t = e.match(/^gpt-(\d+)(?:\.(\d+))?(?:-(.+))?$/);
436
+ if (!t) {
437
+ let t = e.match(/^gpt-(\d+)([a-z])(?:-(.+))?$/);
438
+ return t ? {
439
+ major: parseInt(t[1], 10),
440
+ minor: null,
441
+ variant: t[2] + (t[3] ? `-${t[3]}` : "")
442
+ } : null;
443
+ }
444
+ return {
445
+ major: parseInt(t[1], 10),
446
+ minor: t[2] ? parseInt(t[2], 10) : null,
447
+ variant: t[3] || null
448
+ };
449
+ }
450
+ function f(e, t) {
451
+ let n = d(e), r = d(t);
452
+ if (!n && !r) return e.localeCompare(t);
453
+ if (!n) return 1;
454
+ if (!r) return -1;
455
+ if (n.major !== r.major) return r.major - n.major;
456
+ let i = n.minor ?? 0, a = r.minor ?? 0;
457
+ if (i !== a) return a - i;
458
+ let o = n.variant !== null;
459
+ return o === (r.variant !== null) ? 0 : o ? 1 : -1;
460
+ }
461
+ var p = class e extends t {
462
+ static DEFAULT_MODEL = "gpt-6-luna";
463
+ baseCompletionUrl = "https://api.openai.com/v1/responses";
464
+ baseModelUrl = "https://api.openai.com/v1/models";
465
+ models;
466
+ type = "openai";
467
+ retryOptions;
468
+ constructor(t, n, r, i = !1, a) {
469
+ super(t, n, r, i), this.models = [], this.retryOptions = a || {
470
+ maxRetries: 3,
471
+ initialDelayMs: 1e3,
472
+ retryStatusCodes: [
473
+ 429,
474
+ 500,
475
+ 502,
476
+ 503,
477
+ 504
478
+ ],
479
+ errorBodyExtractor: e.extractErrorMessage,
480
+ onRetry: (e, t, n) => {
481
+ console.warn(`Retry attempt ${e} after ${t}ms delay due to error: ${n.message}`);
482
+ }
483
+ };
484
+ }
485
+ static async extractErrorMessage(e) {
486
+ let t = await e.json();
487
+ return t?.error?.message ? `OpenAI API error${t.error.code ? ` (${t.error.code})` : ""}: ${t.error.message}` : t?.error ? `OpenAI API error: ${JSON.stringify(t.error)}` : `OpenAI API error: HTTP ${e.status}: ${e.statusText}`;
488
+ }
489
+ async reset() {
490
+ this.error = null;
491
+ try {
492
+ let t = (await (await i(() => fetch(this.baseModelUrl, {
493
+ headers: { Authorization: `Bearer ${this.apiKey}` },
494
+ method: "GET"
495
+ }), this.retryOptions)).json()).data.map((e) => e.id);
496
+ this.models = e.filterModels(t), this.connected = !0;
497
+ } catch (e) {
498
+ throw this.error = e instanceof Error ? e.message : "Unknown error", this.connected = !1, e;
499
+ }
500
+ }
501
+ async generateCompletion(e, t = null) {
502
+ this.validateRequestOptions(e);
503
+ let n = [];
504
+ for (let e of t || []) if (e.role === "assistant" && e.toolCalls && e.toolCalls.length > 0) {
505
+ e.content && n.push({
506
+ role: "assistant",
507
+ content: e.content
508
+ });
509
+ for (let t of e.toolCalls) n.push({
510
+ type: "function_call",
511
+ call_id: t.id,
512
+ name: t.name,
513
+ arguments: JSON.stringify(t.input)
514
+ });
515
+ } else if (e.role === "user" && e.toolResults && e.toolResults.length > 0) {
516
+ let t = !1;
517
+ for (let r of e.toolResults) n.push({
518
+ type: "function_call_output",
519
+ call_id: r.toolCallId,
520
+ output: r.result
521
+ }), r.imageData && (t = !0);
522
+ if (t) {
523
+ let t = [];
524
+ for (let n of e.toolResults) n.imageData && t.push({
525
+ type: "input_image",
526
+ image_url: `data:${n.imageData.mediaType};base64,${n.imageData.data}`
527
+ });
528
+ t.push({
529
+ type: "input_text",
530
+ text: "Above is the rendered screenshot referenced by the preceding tool result. Review it visually."
531
+ }), n.push({
532
+ role: "user",
533
+ content: t
534
+ });
535
+ }
536
+ } else n.push({
537
+ role: e.role,
538
+ content: e.content
539
+ });
540
+ e.prompt && n.push({
541
+ role: "user",
542
+ content: e.prompt
543
+ });
544
+ let r = {
545
+ model: this.model,
546
+ input: n,
547
+ store: !1
548
+ };
549
+ e.systemPrompt && (r.instructions = e.systemPrompt), e.tools && e.tools.length > 0 && (r.tools = e.tools.map((e) => ({
550
+ type: "function",
551
+ name: e.name,
552
+ description: e.description,
553
+ parameters: e.input_schema,
554
+ strict: !1
555
+ })));
556
+ try {
557
+ let t = await (await i(() => fetch(this.baseCompletionUrl, {
558
+ method: "POST",
559
+ headers: {
560
+ "Content-Type": "application/json",
561
+ Authorization: `Bearer ${this.apiKey}`
562
+ },
563
+ body: JSON.stringify(r),
564
+ signal: e.signal
565
+ }), {
566
+ ...this.retryOptions,
567
+ signal: e.signal,
568
+ onRetry: (t, n, r) => {
569
+ this.retryOptions.onRetry?.(t, n, r), e.onRateLimitBackoff?.(t, n, r);
570
+ }
571
+ })).json(), n = "", a = [];
572
+ for (let e of t.output || []) if (e.type === "message") for (let t of e.content || []) t.type === "output_text" && (n += t.text);
573
+ else e.type === "function_call" && a.push({
574
+ id: e.call_id,
575
+ name: e.name,
576
+ input: JSON.parse(e.arguments)
577
+ });
578
+ return {
579
+ text: n,
580
+ toolCalls: a.length > 0 ? a : void 0,
581
+ usage: {
582
+ promptTokens: t.usage.input_tokens,
583
+ completionTokens: t.usage.output_tokens,
584
+ totalTokens: t.usage.total_tokens
585
+ }
586
+ };
587
+ } catch (e) {
588
+ throw e instanceof Error ? Error(`OpenAI API error: ${e.message}`) : e;
589
+ }
590
+ }
591
+ static filterModels(e) {
592
+ return e.filter((e) => {
593
+ let t = d(e);
594
+ return t !== null && t.major >= 5;
595
+ }).sort(f);
596
+ }
597
+ static getDefaultModel(t) {
598
+ if (t.includes(e.DEFAULT_MODEL)) return e.DEFAULT_MODEL;
599
+ let n = [...t].sort(f);
600
+ return n.find((e) => {
601
+ let t = d(e);
602
+ return t !== null && t.variant === null;
603
+ }) || n[0] || "";
604
+ }
605
+ }, m = [
606
+ /^anthropic\/claude-/,
607
+ /^openai\/gpt-[4-9]/,
608
+ /^openai\/o[1-9]/,
609
+ /^google\/gemini-/,
610
+ /^meta-llama\/llama-[3-9]/,
611
+ /^meta-llama\/llama-guard/,
612
+ /^mistral(?:ai)?\/mistral-(?:large|medium|small)/,
613
+ /^mistral(?:ai)?\/mixtral/,
614
+ /^mistral(?:ai)?\/codestral/,
615
+ /^mistral(?:ai)?\/ministral/,
616
+ /^mistral(?:ai)?\/pixtral/,
617
+ /^deepseek\//,
618
+ /^qwen\/qwen-[2-9]/,
619
+ /^qwen\/qwq/,
620
+ /^cohere\/command-(?:r|a)/,
621
+ /^x-ai\/grok/,
622
+ /^perplexity\//,
623
+ /^nousresearch\/hermes-[3-9]/,
624
+ /^microsoft\/phi-[3-9]/,
625
+ /^microsoft\/wizardlm/
626
+ ];
627
+ function h(e) {
628
+ let t = e.split("/");
629
+ return t.length >= 2 ? {
630
+ provider: t[0],
631
+ modelName: t.slice(1).join("/")
632
+ } : {
633
+ provider: "",
634
+ modelName: e
635
+ };
636
+ }
637
+ function g(e) {
638
+ let t = e.toLowerCase();
639
+ return t.includes("opus") || t.includes("ultra") || t.includes("-large") || /gpt-[5-9]/.test(t) || t.includes("o1-pro") || /\/o[3-9]/.test(t) ? "flagship" : /-mini\b/.test(t) || /\/mini\b/.test(t) || t.includes("haiku") || t.includes("flash") || t.includes("-small") || t.includes("instant") ? "mini" : t.includes("sonnet") || t.includes("medium") || /-pro\b/.test(t) || t.endsWith("-pro") || t.endsWith("pro") || t.includes("gpt-4") ? "standard" : "other";
640
+ }
641
+ function _(e) {
642
+ let t = e.match(/[/-](\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[a-z])?(?:[/-]|$)/i);
643
+ return t ? {
644
+ major: parseInt(t[1], 10),
645
+ minor: t[2] ? parseInt(t[2], 10) : 0,
646
+ patch: t[3] ? parseInt(t[3], 10) : 0
647
+ } : null;
648
+ }
649
+ function v(e, t) {
650
+ let n = h(e), r = h(t), i = {
651
+ anthropic: 0,
652
+ openai: 1,
653
+ google: 2,
654
+ "x-ai": 6,
655
+ "meta-llama": 9,
656
+ mistralai: 5,
657
+ mistral: 5,
658
+ deepseek: 3,
659
+ qwen: 7,
660
+ cohere: 8,
661
+ perplexity: 9
662
+ }, a = i[n.provider] ?? 99, o = i[r.provider] ?? 99;
663
+ if (a !== o) return a - o;
664
+ let s = {
665
+ flagship: 0,
666
+ standard: 1,
667
+ mini: 2,
668
+ other: 3
669
+ }, c = g(e), l = g(t);
670
+ if (c !== l) return s[c] - s[l];
671
+ let u = _(e), d = _(t);
672
+ return u && d ? u.major === d.major ? u.minor === d.minor ? d.patch - u.patch : d.minor - u.minor : d.major - u.major : u ? -1 : d ? 1 : e.localeCompare(t);
673
+ }
674
+ var y = class e extends t {
675
+ baseCompletionUrl = "https://openrouter.ai/api/v1/chat/completions";
676
+ baseModelUrl = "https://openrouter.ai/api/v1/models";
677
+ models = [];
678
+ modelMetadata = /* @__PURE__ */ new Map();
679
+ type = "openrouter";
680
+ retryOptions;
681
+ httpReferer;
682
+ appTitle;
683
+ constructor(t, n, r, i = !1, a, o) {
684
+ super(t, n, r, i), this.httpReferer = o?.httpReferer, this.appTitle = o?.appTitle, this.retryOptions = a || {
685
+ maxRetries: 3,
686
+ initialDelayMs: 1e3,
687
+ retryStatusCodes: [
688
+ 429,
689
+ 500,
690
+ 502,
691
+ 503,
692
+ 504
693
+ ],
694
+ errorBodyExtractor: e.extractErrorMessage,
695
+ onRetry: (e, t, n) => {
696
+ console.warn(`OpenRouter API retry attempt ${e} after ${t}ms delay due to error: ${n.message}`);
697
+ }
698
+ };
699
+ }
700
+ static async extractErrorMessage(e) {
701
+ let t = await e.json();
702
+ return t.error ? `OpenRouter API error${t.error.code ? ` (${t.error.code})` : ""}: ${t.error.message || JSON.stringify(t.error)}` : `OpenRouter API error: HTTP ${e.status}: ${e.statusText}`;
703
+ }
704
+ getHeaders() {
705
+ let e = {
706
+ "Content-Type": "application/json",
707
+ Authorization: `Bearer ${this.apiKey}`
708
+ };
709
+ return this.httpReferer && (e["HTTP-Referer"] = this.httpReferer), this.appTitle && (e["X-Title"] = this.appTitle), e;
710
+ }
711
+ async reset() {
712
+ this.error = null;
713
+ try {
714
+ let t = (await (await i(() => fetch(this.baseModelUrl, {
715
+ headers: this.getHeaders(),
716
+ method: "GET"
717
+ }), this.retryOptions)).json()).data || [];
718
+ this.modelMetadata.clear();
719
+ for (let e of t) this.modelMetadata.set(e.id, e);
720
+ let n = t.map((e) => e.id);
721
+ this.models = e.filterModels(n), this.connected = !0;
722
+ } catch (e) {
723
+ throw this.error = e instanceof Error ? e.message : "Unknown error", this.connected = !1, e;
724
+ }
725
+ }
726
+ async generateCompletion(e, t = null) {
727
+ this.validateRequestOptions(e);
728
+ let n = [];
729
+ for (let e of t || []) if (e.role === "assistant" && e.toolCalls && e.toolCalls.length > 0) n.push({
730
+ role: "assistant",
731
+ content: e.content || null,
732
+ tool_calls: e.toolCalls.map((e) => ({
733
+ id: e.id,
734
+ type: "function",
735
+ function: {
736
+ name: e.name,
737
+ arguments: JSON.stringify(e.input)
738
+ }
739
+ }))
740
+ });
741
+ else if (e.role === "user" && e.toolResults && e.toolResults.length > 0) {
742
+ let t = !1;
743
+ for (let r of e.toolResults) n.push({
744
+ role: "tool",
745
+ tool_call_id: r.toolCallId,
746
+ content: r.result
747
+ }), r.imageData && (t = !0);
748
+ if (t) {
749
+ let t = [];
750
+ for (let n of e.toolResults) n.imageData && t.push({
751
+ type: "image_url",
752
+ image_url: { url: `data:${n.imageData.mediaType};base64,${n.imageData.data}` }
753
+ });
754
+ t.push({
755
+ type: "text",
756
+ text: "Above is the rendered screenshot referenced by the preceding tool result. Review it visually."
757
+ }), n.push({
758
+ role: "user",
759
+ content: t
760
+ });
761
+ }
762
+ } else n.push({
763
+ role: e.role,
764
+ content: e.content
765
+ });
766
+ let r = [];
767
+ e.systemPrompt && r.push({
768
+ role: "system",
769
+ content: e.systemPrompt
770
+ }), r = [...r, ...n], e.prompt && r.push({
771
+ role: "user",
772
+ content: e.prompt
773
+ });
774
+ let a = {
775
+ model: this.model,
776
+ messages: r
777
+ };
778
+ e.maxTokens && (a.max_tokens = e.maxTokens), e.temperature !== void 0 && (a.temperature = e.temperature), e.topP !== void 0 && (a.top_p = e.topP), e.tools && e.tools.length > 0 && (a.tools = e.tools.map((e) => ({
779
+ type: "function",
780
+ function: {
781
+ name: e.name,
782
+ description: e.description,
783
+ parameters: e.input_schema
784
+ }
785
+ })));
786
+ try {
787
+ let t = await (await i(() => fetch(this.baseCompletionUrl, {
788
+ method: "POST",
789
+ headers: this.getHeaders(),
790
+ body: JSON.stringify(a),
791
+ signal: e.signal
792
+ }), {
793
+ ...this.retryOptions,
794
+ signal: e.signal,
795
+ onRetry: (t, n, r) => {
796
+ this.retryOptions.onRetry?.(t, n, r), e.onRateLimitBackoff?.(t, n, r);
797
+ }
798
+ })).json();
799
+ if (t.error) {
800
+ let e = t.error.code ? ` (${t.error.code})` : "";
801
+ throw Error(`OpenRouter API error${e}: ${t.error.message || JSON.stringify(t.error)}`);
802
+ }
803
+ let n = t.choices?.[0]?.message?.content || "", r = t.choices?.[0]?.message?.tool_calls, o = [];
804
+ if (r && r.length > 0) {
805
+ for (let e of r) if (e.type === "function") {
806
+ let t = e.function.arguments ? JSON.parse(e.function.arguments) : {};
807
+ o.push({
808
+ id: e.id,
809
+ name: e.function.name,
810
+ input: t
811
+ });
812
+ }
813
+ }
814
+ let s = t.usage || {};
815
+ return {
816
+ text: n,
817
+ toolCalls: o.length > 0 ? o : void 0,
818
+ usage: {
819
+ promptTokens: s.prompt_tokens || 0,
820
+ completionTokens: s.completion_tokens || 0,
821
+ totalTokens: s.total_tokens || 0
822
+ }
823
+ };
824
+ } catch (e) {
825
+ throw e instanceof Error ? Error(`OpenRouter API error: ${e.message}`) : e;
826
+ }
827
+ }
828
+ getModelMetadata(e) {
829
+ return this.modelMetadata.get(e);
830
+ }
831
+ static filterModels(e) {
832
+ return e.filter((e) => m.some((t) => t.test(e))).sort(v);
833
+ }
834
+ static getDefaultModel(e) {
835
+ for (let t of [
836
+ "google/gemini-3.1-pro-preview",
837
+ "openai/gpt-5.2",
838
+ "anthropic/claude-sonnet-4.6"
839
+ ]) {
840
+ let n = e.find((e) => e === t || e.startsWith(t));
841
+ if (n) return n;
842
+ }
843
+ return e[0] || "";
844
+ }
845
+ static getOAuthAuthorizationUrl(e) {
846
+ let t = new URLSearchParams({ callback_url: e.callbackUrl });
847
+ return e.codeChallenge && t.set("code_challenge", e.codeChallenge), e.codeChallengeMethod && t.set("code_challenge_method", e.codeChallengeMethod), `https://openrouter.ai/auth?${t.toString()}`;
848
+ }
849
+ static async exchangeCodeForApiKey(e, t) {
850
+ let n = { code: e };
851
+ t && (n.code_verifier = t);
852
+ let r = await fetch("https://openrouter.ai/api/v1/auth/keys", {
853
+ method: "POST",
854
+ headers: { "Content-Type": "application/json" },
855
+ body: JSON.stringify(n)
856
+ });
857
+ if (!r.ok) {
858
+ let e = await r.json().catch(() => ({ message: "Unknown error" }));
859
+ throw Error(`Failed to exchange code for API key: ${e.message || r.statusText}`);
860
+ }
861
+ return (await r.json()).key;
862
+ }
863
+ static generateCodeVerifier() {
864
+ let e = /* @__PURE__ */ new Uint8Array(32);
865
+ return crypto.getRandomValues(e), btoa(String.fromCharCode(...e)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
866
+ }
867
+ static async generateCodeChallenge(e) {
868
+ let t = new TextEncoder().encode(e), n = await crypto.subtle.digest("SHA-256", t), r = new Uint8Array(n);
869
+ return btoa(String.fromCharCode(...r)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
870
+ }
871
+ };
872
+ //#endregion
873
+ //#region llm/deepseek.ts
874
+ function b(e) {
875
+ let t = e.match(/^deepseek-v(\d+)(?:\.(\d+))?-([a-z]+)$/);
876
+ if (t) return {
877
+ version: parseInt(t[1], 10) + (t[2] ? parseInt(t[2], 10) : 0) / 10,
878
+ tier: t[3]
879
+ };
880
+ let n = e.match(/^deepseek-(chat|reasoner)$/);
881
+ return n ? {
882
+ version: 0,
883
+ tier: n[1]
884
+ } : null;
885
+ }
886
+ function x(e, t) {
887
+ let n = b(e), r = b(t);
888
+ if (!n && !r) return e.localeCompare(t);
889
+ if (!n) return 1;
890
+ if (!r) return -1;
891
+ if (n.version !== r.version) return r.version - n.version;
892
+ let i = {
893
+ flash: 0,
894
+ pro: 1,
895
+ reasoner: 2,
896
+ chat: 3
897
+ }, a = i[n.tier] ?? 99, o = i[r.tier] ?? 99;
898
+ return a === o ? e.localeCompare(t) : a - o;
899
+ }
900
+ var S = class e extends t {
901
+ baseCompletionUrl = "https://api.deepseek.com/chat/completions";
902
+ baseModelUrl = "https://api.deepseek.com/models";
903
+ models = [];
904
+ type = "deepseek";
905
+ retryOptions;
906
+ constructor(t, n, r, i = !1, a) {
907
+ super(t, n, r, i), this.retryOptions = a || {
908
+ maxRetries: 3,
909
+ initialDelayMs: 1e3,
910
+ retryStatusCodes: [
911
+ 429,
912
+ 500,
913
+ 502,
914
+ 503,
915
+ 504
916
+ ],
917
+ errorBodyExtractor: e.extractErrorMessage,
918
+ onRetry: (e, t, n) => {
919
+ console.warn(`DeepSeek API retry attempt ${e} after ${t}ms delay due to error: ${n.message}`);
920
+ }
921
+ };
922
+ }
923
+ static async extractErrorMessage(e) {
924
+ let t = `DeepSeek API error: HTTP ${e.status}: ${e.statusText}`, n;
925
+ try {
926
+ n = await e.text();
927
+ } catch {
928
+ return t;
929
+ }
930
+ let r;
931
+ try {
932
+ r = JSON.parse(n);
933
+ } catch {
934
+ let e = n.trim().slice(0, 200);
935
+ return e ? `${t} - ${e}` : t;
936
+ }
937
+ if (r?.error?.message) {
938
+ let t = r.error.code || r.error.type, n = e.status === 402 ? " (check your DeepSeek account balance)" : "";
939
+ return `DeepSeek API error${t ? ` (${t})` : ""}: ${r.error.message}${n}`;
940
+ }
941
+ return r?.error ? `DeepSeek API error: ${JSON.stringify(r.error)}` : t;
942
+ }
943
+ getHeaders() {
944
+ return {
945
+ "Content-Type": "application/json",
946
+ Authorization: `Bearer ${this.apiKey}`
947
+ };
948
+ }
949
+ async reset() {
950
+ this.error = null;
951
+ try {
952
+ let t = ((await (await i(() => fetch(this.baseModelUrl, {
953
+ headers: this.getHeaders(),
954
+ method: "GET"
955
+ }), this.retryOptions)).json()).data || []).map((e) => e.id);
956
+ this.models = e.filterModels(t), this.connected = !0;
957
+ } catch (e) {
958
+ throw this.error = e instanceof Error ? e.message : "Unknown error", this.connected = !1, e;
959
+ }
960
+ }
961
+ async generateCompletion(e, t = null) {
962
+ this.validateRequestOptions(e);
963
+ let n = [];
964
+ for (let e of t || []) if (e.role === "assistant" && e.toolCalls && e.toolCalls.length > 0) n.push({
965
+ role: "assistant",
966
+ content: e.content || null,
967
+ tool_calls: e.toolCalls.map((e) => ({
968
+ id: e.id,
969
+ type: "function",
970
+ function: {
971
+ name: e.name,
972
+ arguments: JSON.stringify(e.input)
973
+ }
974
+ }))
975
+ });
976
+ else if (e.role === "user" && e.toolResults && e.toolResults.length > 0) {
977
+ for (let t of e.toolResults) n.push({
978
+ role: "tool",
979
+ tool_call_id: t.toolCallId,
980
+ content: t.result
981
+ });
982
+ let t = e.toolResults.filter((e) => e.imageData).length;
983
+ t > 0 && n.push({
984
+ role: "user",
985
+ content: `[${t} image${t === 1 ? "" : "s"} produced by the preceding tool call could not be included: this model does not accept image input. Rely on the textual tool output instead.]`
986
+ });
987
+ } else n.push({
988
+ role: e.role,
989
+ content: e.content
990
+ });
991
+ let r = [];
992
+ e.systemPrompt && r.push({
993
+ role: "system",
994
+ content: e.systemPrompt
995
+ }), r = [...r, ...n], e.prompt && r.push({
996
+ role: "user",
997
+ content: e.prompt
998
+ });
999
+ let a = {
1000
+ model: this.model,
1001
+ messages: r
1002
+ };
1003
+ e.maxTokens && (a.max_tokens = e.maxTokens), e.temperature !== void 0 && (a.temperature = e.temperature), e.topP !== void 0 && (a.top_p = e.topP), e.tools && e.tools.length > 0 && (a.tools = e.tools.map((e) => ({
1004
+ type: "function",
1005
+ function: {
1006
+ name: e.name,
1007
+ description: e.description,
1008
+ parameters: e.input_schema
1009
+ }
1010
+ })));
1011
+ try {
1012
+ let t = await (await i(() => fetch(this.baseCompletionUrl, {
1013
+ method: "POST",
1014
+ headers: this.getHeaders(),
1015
+ body: JSON.stringify(a),
1016
+ signal: e.signal
1017
+ }), {
1018
+ ...this.retryOptions,
1019
+ signal: e.signal,
1020
+ onRetry: (t, n, r) => {
1021
+ this.retryOptions.onRetry?.(t, n, r), e.onRateLimitBackoff?.(t, n, r);
1022
+ }
1023
+ })).json();
1024
+ if (t.error) {
1025
+ let e = t.error.code || t.error.type;
1026
+ throw Error(`DeepSeek API error${e ? ` (${e})` : ""}: ${t.error.message || JSON.stringify(t.error)}`);
1027
+ }
1028
+ let n = t.choices?.[0], r = n?.message?.content || "", o = n?.message?.tool_calls, s = [];
1029
+ if (o && o.length > 0) {
1030
+ for (let e of o) if (e.type === "function") {
1031
+ let t = e.function.arguments ? JSON.parse(e.function.arguments) : {};
1032
+ s.push({
1033
+ id: e.id,
1034
+ name: e.function.name,
1035
+ input: t
1036
+ });
1037
+ }
1038
+ }
1039
+ let c = n?.finish_reason ?? void 0;
1040
+ c === "length" && console.warn("DeepSeek response hit the output token limit and is truncated.");
1041
+ let l = t.usage || {}, u = l.prompt_cache_hit_tokens ?? 0, d = l.prompt_cache_miss_tokens ?? l.prompt_tokens ?? 0, f = l.completion_tokens ?? 0;
1042
+ return {
1043
+ text: r,
1044
+ toolCalls: s.length > 0 ? s : void 0,
1045
+ stopReason: c,
1046
+ usage: {
1047
+ promptTokens: d,
1048
+ completionTokens: f,
1049
+ cacheReadTokens: u,
1050
+ totalTokens: l.total_tokens ?? d + u + f
1051
+ }
1052
+ };
1053
+ } catch (e) {
1054
+ throw e instanceof Error ? Error(`DeepSeek API error: ${e.message}`) : e;
1055
+ }
1056
+ }
1057
+ static filterModels(e) {
1058
+ return e.filter((e) => b(e) !== null).sort(x);
1059
+ }
1060
+ static getDefaultModel(e) {
1061
+ let t = [...e].sort(x);
1062
+ return t.find((e) => b(e)?.tier === "flash") || t[0] || "";
1063
+ }
1064
+ }, C = "<user_input>", w = "</user_input>", T = "<system_input>", E = "</system_input>";
1065
+ function D(e) {
1066
+ return e.replace(/<\/?(?:user_input|system_input)>/gi, "");
1067
+ }
1068
+ function O(e) {
1069
+ return { generateCompletion: (t, n, r) => e.generateCompletion(n, r) };
1070
+ }
1071
+ function k(e) {
1072
+ let t = e?.data;
1073
+ return !Array.isArray(t) || t.length <= 100 ? {
1074
+ head: t ?? [],
1075
+ tail: [],
1076
+ totalRows: t?.length ?? 0,
1077
+ cutCount: 0
1078
+ } : {
1079
+ head: t.slice(0, 50),
1080
+ tail: t.slice(t.length - 50),
1081
+ totalRows: t.length,
1082
+ cutCount: t.length - 100
1083
+ };
1084
+ }
1085
+ function A(e) {
1086
+ if (e.success) {
1087
+ if (e.artifact) {
1088
+ let t = e.artifact.config, n = e.artifact.data, r = e.artifact.id, i = "";
1089
+ if (n) {
1090
+ let e = typeof n.toJSON == "function" ? n.toJSON() : n, a = t?.resultSize ?? (Array.isArray(e?.data) ? e.data.length : 0), { head: o, tail: s, cutCount: c } = k(e);
1091
+ if (c > 0) {
1092
+ let t = JSON.stringify({
1093
+ ...e,
1094
+ data: o
1095
+ }, null, 2), n = JSON.stringify({
1096
+ headers: e.headers,
1097
+ data: s
1098
+ }, null, 2);
1099
+ i = `\n\nQuery results (${a} rows total — showing first ${o.length} and last ${s.length}, use get_artifact_rows to fetch any range):\n${t}\n...(${c} of ${a} rows cut off — use get_artifact_rows with artifact ID: ${r})...\n${n}`;
1100
+ } else i = `\n\nQuery results (${a} rows):\n${JSON.stringify(e, null, 2)}`;
1101
+ }
1102
+ let a = t && typeof t.executionTime == "number" ? ` in ${t.executionTime}ms` : "", o = t ? `Results: ${t.resultSize || 0} rows, ${t.columnCount || 0} columns${a}.` : "";
1103
+ return `Success. ${r ? `Artifact ID: ${r}. ` : ""}${e.message || o}${i}`;
1104
+ }
1105
+ return e.message ? e.message : "Success.";
1106
+ }
1107
+ return `Error: ${e.error}`;
1108
+ }
1109
+ function j(e) {
1110
+ if (e instanceof Error) return e.message;
1111
+ if (typeof e == "string") return e;
1112
+ try {
1113
+ return JSON.stringify(e);
1114
+ } catch {
1115
+ return String(e);
1116
+ }
1117
+ }
1118
+ async function M(e, t, n, r, i, a, o) {
1119
+ let s = o.maxIterations ?? 20, c = r.getMessages().slice(0, -1).map((e) => e.role === "user" && !e.hidden && e.content ? {
1120
+ ...e,
1121
+ content: `${C}${D(e.content)}${w}`
1122
+ } : e), l = `${C}${D(e)}${w}`, u = l, d = !1, f = 0;
1123
+ for (let e = 0; e < s; e++) {
1124
+ if (a.checkAborted()) return e === 0 && r.addMessage({
1125
+ role: "assistant",
1126
+ content: "(Response in progress when stopped)"
1127
+ }), r.addMessage({
1128
+ role: "user",
1129
+ content: `${T}[User requested pause - conversation can be continued]${E}`,
1130
+ hidden: !0
1131
+ }), {
1132
+ terminated: !1,
1133
+ stopped: !0,
1134
+ finalMessage: "Stopped by user"
1135
+ };
1136
+ for (; a.isPaused?.() && !a.checkAborted();) await new Promise((e) => setTimeout(e, 200));
1137
+ if (a.checkAborted()) return e === 0 && r.addMessage({
1138
+ role: "assistant",
1139
+ content: "(Response in progress when stopped)"
1140
+ }), r.addMessage({
1141
+ role: "user",
1142
+ content: `${T}[User requested pause - conversation can be continued]${E}`,
1143
+ hidden: !0
1144
+ }), {
1145
+ terminated: !1,
1146
+ stopped: !0,
1147
+ finalMessage: "Stopped by user"
1148
+ };
1149
+ let p = i.getToolExecutor(), m = {
1150
+ prompt: u,
1151
+ systemPrompt: o.buildSystemPrompt(),
1152
+ tools: o.tools
1153
+ }, h = await n.generateCompletion(t, m, c), g = h.text, _ = h.toolCalls ?? [];
1154
+ if (a.checkAborted()) return r.addMessage({
1155
+ role: "assistant",
1156
+ content: g
1157
+ }), r.addMessage({
1158
+ role: "user",
1159
+ content: `${T}[User requested pause - conversation can be continued]${E}`,
1160
+ hidden: !0
1161
+ }), {
1162
+ terminated: !1,
1163
+ stopped: !0,
1164
+ finalMessage: "Stopped by user"
1165
+ };
1166
+ if (_.length === 0) {
1167
+ if (r.addMessage({
1168
+ role: "assistant",
1169
+ content: g
1170
+ }), o.terminateOnNoToolCall) return {
1171
+ terminated: !0,
1172
+ finalMessage: g
1173
+ };
1174
+ if (f++, f >= 3) return console.log("[toolLoopCore] Model ignored repeated tool reminders — ending turn"), {
1175
+ terminated: !0,
1176
+ finalMessage: g
1177
+ };
1178
+ let e = o.noToolCallReminder ?? "You must call a tool to proceed. If you are finished, call the appropriate completion tool to return control to the user. Do not respond with text only.";
1179
+ console.log("[toolLoopCore] No tool call — re-prompting agent to use a tool");
1180
+ let t = `${T}${e}${E}`;
1181
+ r.addMessage({
1182
+ role: "user",
1183
+ content: t,
1184
+ hidden: !0
1185
+ }), c = [
1186
+ ...c,
1187
+ ...d ? [] : [{
1188
+ role: "user",
1189
+ content: l
1190
+ }],
1191
+ {
1192
+ role: "assistant",
1193
+ content: g
1194
+ },
1195
+ {
1196
+ role: "user",
1197
+ content: t,
1198
+ hidden: !0
1199
+ }
1200
+ ], d = !0, u = "";
1201
+ continue;
1202
+ }
1203
+ f = 0;
1204
+ let v = [], y = [];
1205
+ for (let e of _) {
1206
+ if (a.checkAborted()) return r.addMessage({
1207
+ role: "assistant",
1208
+ content: g,
1209
+ toolCalls: _.slice(0, y.length),
1210
+ executedToolCalls: y.length > 0 ? y : void 0
1211
+ }), v.length > 0 && r.addMessage({
1212
+ role: "user",
1213
+ content: "",
1214
+ toolResults: v,
1215
+ hidden: !0
1216
+ }), r.addMessage({
1217
+ role: "user",
1218
+ content: `${T}[User requested pause - conversation can be continued]${E}`,
1219
+ hidden: !0
1220
+ }), {
1221
+ terminated: !1,
1222
+ stopped: !0,
1223
+ finalMessage: "Stopped by user"
1224
+ };
1225
+ a.setActiveToolName(e.name);
1226
+ let t;
1227
+ try {
1228
+ t = await p.executeToolCall(e.name, e.input);
1229
+ } catch (n) {
1230
+ t = {
1231
+ success: !1,
1232
+ error: `Tool "${e.name}" failed: ${j(n)}`
1233
+ };
1234
+ }
1235
+ let n = {
1236
+ id: e.id,
1237
+ name: e.name,
1238
+ input: e.input,
1239
+ result: {
1240
+ success: t.success,
1241
+ message: t.message,
1242
+ error: t.error,
1243
+ subchatId: t.subchatId
1244
+ }
1245
+ };
1246
+ if (y.push(n), o.onToolResult?.(e.name, t), t.artifact && r.addArtifact(t.artifact), t.terminatesLoop) {
1247
+ v.push({
1248
+ toolCallId: e.id,
1249
+ toolName: e.name,
1250
+ result: ""
1251
+ });
1252
+ let n = g?.trim() ? g : t.message ?? "";
1253
+ return r.addMessage({
1254
+ role: "assistant",
1255
+ content: n,
1256
+ toolCalls: _.slice(0, y.length),
1257
+ executedToolCalls: y
1258
+ }), r.addMessage({
1259
+ role: "user",
1260
+ content: "",
1261
+ toolResults: v,
1262
+ hidden: !0
1263
+ }), {
1264
+ terminated: !0,
1265
+ finalMessage: t.message
1266
+ };
1267
+ }
1268
+ if (t.awaitsUserInput) {
1269
+ let n = t.message || "Awaiting user input.";
1270
+ return v.push({
1271
+ toolCallId: e.id,
1272
+ toolName: e.name,
1273
+ result: n
1274
+ }), r.addMessage({
1275
+ role: "assistant",
1276
+ content: t.message || "",
1277
+ toolCalls: _.slice(0, y.length),
1278
+ executedToolCalls: y
1279
+ }), r.addMessage({
1280
+ role: "user",
1281
+ content: "",
1282
+ toolResults: v,
1283
+ hidden: !0
1284
+ }), o.onAwaitsUserInput?.(t, y), {
1285
+ terminated: !1,
1286
+ finalMessage: t.message
1287
+ };
1288
+ }
1289
+ let i = A(t);
1290
+ v.push({
1291
+ toolCallId: e.id,
1292
+ toolName: e.name,
1293
+ result: i,
1294
+ imageData: t.imageData
1295
+ });
1296
+ }
1297
+ if (a.setActiveToolName(""), r.addMessage({
1298
+ role: "assistant",
1299
+ content: g,
1300
+ toolCalls: _,
1301
+ executedToolCalls: y
1302
+ }), r.addMessage({
1303
+ role: "user",
1304
+ content: "",
1305
+ toolResults: v,
1306
+ hidden: !0
1307
+ }), c = [
1308
+ ...c,
1309
+ ...d ? [] : [{
1310
+ role: "user",
1311
+ content: l
1312
+ }],
1313
+ {
1314
+ role: "assistant",
1315
+ content: g,
1316
+ toolCalls: _
1317
+ },
1318
+ {
1319
+ role: "user",
1320
+ content: "",
1321
+ toolResults: v,
1322
+ hidden: !0
1323
+ }
1324
+ ], d = !0, u = "", e === s - 1) return r.addMessage({
1325
+ role: "assistant",
1326
+ content: "(Max tool iterations reached)"
1327
+ }), {
1328
+ terminated: !1,
1329
+ finalMessage: g + "\n\n(Max tool iterations reached)"
1330
+ };
1331
+ }
1332
+ return { terminated: !1 };
1333
+ }
1334
+ //#endregion
1335
+ //#region llm/returnToUserTool.ts
1336
+ var N = {
1337
+ name: "return_to_user",
1338
+ description: "Signal that you are done and return control to the user. You MUST call this tool when you have completed all requested tasks and are ready for the user's next input. Provide a brief summary of what was accomplished. Never end a turn with plain text — always call this tool when finished.",
1339
+ input_schema: {
1340
+ type: "object",
1341
+ properties: { message: {
1342
+ type: "string",
1343
+ description: "A brief summary of what was accomplished or a response to the user."
1344
+ } },
1345
+ required: ["message"]
1346
+ }
1347
+ };
1348
+ //#endregion
1349
+ export { u as AnthropicProvider, S as DeepSeekProvider, t as LLMProvider, p as OpenAIProvider, y as OpenRouterProvider, N as RETURN_TO_USER_TOOL, E as SYSTEM_INPUT_END, T as SYSTEM_INPUT_START, l as compareAnthropicModels, x as compareDeepSeekModels, A as formatToolResultText, o as parseAnthropicModelVersion, b as parseDeepSeekModel, O as providerAdapter, M as runToolLoop, D as stripPromptWrapperTags };