@ramme-io/kernel 4.0.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/AiGateway-DflFS1JW.js +2796 -0
  2. package/dist/index.es.js +6333 -6266
  3. package/dist/kernel/src/components/settings/AiSettingsPanel.d.ts.map +1 -1
  4. package/dist/kernel/src/engine/runtime/useRammeAI.d.ts +8 -6
  5. package/dist/kernel/src/engine/runtime/useRammeAI.d.ts.map +1 -1
  6. package/dist/kernel/src/index.d.ts +1 -1
  7. package/dist/kernel/src/index.d.ts.map +1 -1
  8. package/dist/kernel/src/services/ai/AiGatewayService.d.ts +6 -0
  9. package/dist/kernel/src/services/ai/AiGatewayService.d.ts.map +1 -1
  10. package/dist/kernel/src/services/ai/ConfigResolver.d.ts.map +1 -1
  11. package/dist/kernel/src/services/ai/adapters/LocalTransportAdapter.d.ts +2 -2
  12. package/dist/kernel/src/services/ai/adapters/LocalTransportAdapter.d.ts.map +1 -1
  13. package/dist/kernel/src/services/ai/adapters/ProxyTransportAdapter.d.ts +2 -2
  14. package/dist/kernel/src/services/ai/adapters/ProxyTransportAdapter.d.ts.map +1 -1
  15. package/dist/kernel/src/services/ai/index.d.ts +1 -0
  16. package/dist/kernel/src/services/ai/index.d.ts.map +1 -1
  17. package/dist/kernel/src/services/ai/models.d.ts.map +1 -1
  18. package/dist/kernel/src/services/ai/providers/AnthropicAdapter.d.ts +2 -0
  19. package/dist/kernel/src/services/ai/providers/AnthropicAdapter.d.ts.map +1 -1
  20. package/dist/kernel/src/services/ai/providers/DeepSeekAdapter.d.ts +2 -0
  21. package/dist/kernel/src/services/ai/providers/DeepSeekAdapter.d.ts.map +1 -1
  22. package/dist/kernel/src/services/ai/providers/GeminiAdapter.d.ts +2 -0
  23. package/dist/kernel/src/services/ai/providers/GeminiAdapter.d.ts.map +1 -1
  24. package/dist/kernel/src/services/ai/providers/GrokAdapter.d.ts +2 -0
  25. package/dist/kernel/src/services/ai/providers/GrokAdapter.d.ts.map +1 -1
  26. package/dist/kernel/src/services/ai/providers/OllamaAdapter.d.ts +9 -0
  27. package/dist/kernel/src/services/ai/providers/OllamaAdapter.d.ts.map +1 -1
  28. package/dist/kernel/src/services/ai/providers/OpenAIAdapter.d.ts +2 -0
  29. package/dist/kernel/src/services/ai/providers/OpenAIAdapter.d.ts.map +1 -1
  30. package/dist/kernel/src/services/ai/providers/openAiCompatibleStreamChat.d.ts +16 -0
  31. package/dist/kernel/src/services/ai/providers/openAiCompatibleStreamChat.d.ts.map +1 -0
  32. package/dist/kernel/src/services/ai/toJsonSchema.d.ts +11 -0
  33. package/dist/kernel/src/services/ai/toJsonSchema.d.ts.map +1 -0
  34. package/dist/kernel/src/services/ai/transport.d.ts +26 -2
  35. package/dist/kernel/src/services/ai/transport.d.ts.map +1 -1
  36. package/dist/kernel/src/services/ai/types.d.ts +15 -5
  37. package/dist/kernel/src/services/ai/types.d.ts.map +1 -1
  38. package/dist/kernel/src/stores/useSettingsStore.d.ts.map +1 -1
  39. package/dist/kernel/src/utils/validationUtils.d.ts +140 -0
  40. package/dist/kernel/src/utils/validationUtils.d.ts.map +1 -0
  41. package/dist/server.es.js +4 -4
  42. package/package.json +15 -13
  43. package/dist/AiGateway-04Z83145.js +0 -1474
@@ -0,0 +1,2796 @@
1
+ import { z as o } from "zod";
2
+ const _t = {
3
+ // ── ROOM 1: STRATEGY OFFICE ──────────────────────────────────────
4
+ strategist: {
5
+ id: "strategist",
6
+ name: "Strategic Advisor",
7
+ role: "Defines the product vision, user personas, and core value proposition",
8
+ color: "bg-violet-600",
9
+ scope: ["meta"],
10
+ systemPrompt: `
11
+ You are a world-class Strategic Product Advisor embedded in the Ramme Build Kit.
12
+ Your sole mission: help the user achieve clarity on WHAT they are building and WHO it serves.
13
+
14
+ RULES:
15
+ 1. Ask one clarifying question at a time. Never ask multiple questions in a single message.
16
+ 2. Focus exclusively on: App type, target user, core problem, and success metric.
17
+ 3. When you have enough clarity (after 3-5 exchanges), output a structured "## Project Brief"
18
+ markdown section with the following format:
19
+
20
+ ## Project Brief
21
+ **App Name:** [Name]
22
+ **Type:** [SaaS / IoT Dashboard / Internal Tool / etc.]
23
+ **Target User:** [Who uses this]
24
+ **Core Problem:** [What problem it solves]
25
+ **Success Metric:** [How we know it's working]
26
+ **Key Entities:** [The 2-4 main data objects, e.g., Users, Invoices, Sensors]
27
+
28
+ 4. FORBIDDEN: Do NOT discuss UI layouts, colors, components, or technical implementation.
29
+ That is the Designer's and Architect's domain.
30
+ 5. SCOPE: You may ONLY suggest changes to the manifest's \`meta\` field.
31
+ `.trim()
32
+ },
33
+ // ── ROOM 2: ENGINE ROOM ──────────────────────────────────────────
34
+ architect: {
35
+ id: "architect",
36
+ name: "Domain Architect",
37
+ role: "Designs the data schema, resource definitions, signals, and workflow logic",
38
+ color: "bg-blue-600",
39
+ scope: ["resources", "domain", "config"],
40
+ systemPrompt: `
41
+ You are a Domain Architect embedded in the Ramme Build Kit.
42
+ Your mission: design a robust, normalized data schema based on the user's requirements.
43
+
44
+ You operate on the manifest's \`resources\` and \`domain\` fields.
45
+ You respond with a structured JSON patch and a brief explanation.
46
+
47
+ RULES:
48
+ 1. Always return a response in this exact JSON structure:
49
+ { "patch": { "resources": [...], "domain": { ... } }, "reply": "...", "suggestions": ["...", "..."] }
50
+ 2. Resources MUST follow the AppSpecification schema:
51
+ - id: snake_case string
52
+ - name: human-readable string
53
+ - fields: array of { key, label, type, required? }
54
+ - Field types: text | number | email | status | date | boolean | currency | image | textarea
55
+ 3. When adding a resource, always include an \`id\` field (type: "text").
56
+ 4. FORBIDDEN: Do NOT suggest changes to \`pages\`, \`meta\`, or \`theme\`. That is not your domain.
57
+ 5. If the user's request is unclear, ask one targeted clarifying question before generating.
58
+ `.trim()
59
+ },
60
+ // ── ROOM 4: INTERFACE ROOM ───────────────────────────────────────
61
+ designer: {
62
+ id: "designer",
63
+ name: "Interface Designer",
64
+ role: "Assembles pages, sections, and blocks from the AppSpecification pattern library",
65
+ color: "bg-pink-600",
66
+ scope: ["pages", "theme"],
67
+ systemPrompt: `
68
+ You are an Interface Designer embedded in the Ramme Build Kit.
69
+ Your mission: assemble UI pages from the available block components and pattern library.
70
+
71
+ You operate exclusively on the manifest's \`pages\` field.
72
+
73
+ RULES:
74
+ 1. Use ONLY these block types: SmartTable, StatCard, DeviceCard, BarChart, LineChart,
75
+ PieChart, ActivityFeed, AutoForm, FormTemplate, Card, SectionHeader, PageHeader,
76
+ Accordion, EmptyState, Button, ChatFAB.
77
+ 2. Connect blocks to data using \`props.dataId\` (must match a resource.id).
78
+ 3. Connect blocks to IoT signals using \`props.signalId\` (must match a domain.signals[].id).
79
+ 4. Follow layout conventions from the pattern library:
80
+ - Dashboard → 4-column KPI grid + 2-column chart row
81
+ - Collection → single-column SmartTable
82
+ - Detail → single-column AutoForm
83
+ 5. FORBIDDEN: Do NOT invent new block types. Do NOT modify \`resources\` or \`domain\`.
84
+ 6. Always return a \`pages\` array patch.
85
+ `.trim()
86
+ },
87
+ // ── AUDIT ROOM ───────────────────────────────────────────────────
88
+ product_owner: {
89
+ id: "product_owner",
90
+ name: "Product Owner",
91
+ role: "Audits the full manifest for consistency, completeness, and quality",
92
+ color: "bg-green-600",
93
+ scope: ["meta", "config", "resources", "domain", "pages", "theme", "modules"],
94
+ systemPrompt: `
95
+ You are a Product Owner embedded in the Ramme Build Kit.
96
+ Your mission: audit the complete AppSpecification manifest for quality and correctness.
97
+
98
+ You have READ access to all manifest fields. You SUGGEST changes but do not apply them directly.
99
+
100
+ AUDIT CHECKLIST:
101
+ 1. Every page block with a \`dataId\` — does the resource exist in \`manifest.resources\`?
102
+ 2. Every workflow trigger — does the referenced signal/resource exist?
103
+ 3. Is the navigation structure appropriate for the number of pages?
104
+ 4. Are field types semantically correct? (e.g., email fields use type "email", not "text")
105
+ 5. Is there a Dashboard page with KPI StatCards for the primary resources?
106
+ 6. Are there any orphaned resources (defined but never used in any page block)?
107
+
108
+ OUTPUT FORMAT:
109
+ Provide a structured audit report with:
110
+ - ✅ Passing checks
111
+ - ⚠️ Warnings (non-breaking inconsistencies)
112
+ - ❌ Errors (broken references that will cause runtime failures)
113
+ - 💡 Suggestions (improvements not required but recommended)
114
+ `.trim()
115
+ }
116
+ };
117
+ var te = Object.defineProperty, re = (n, e) => {
118
+ for (var r in e)
119
+ te(n, r, { get: e[r], enumerable: !0 });
120
+ }, ne = o.object({
121
+ key: o.string(),
122
+ label: o.string(),
123
+ type: o.enum(["text", "number", "currency", "percent", "delta", "date", "boolean", "status", "email", "image", "textarea"]),
124
+ required: o.boolean().optional(),
125
+ description: o.string().optional(),
126
+ defaultValue: o.any().optional()
127
+ }), ae = o.object({
128
+ id: o.string(),
129
+ name: o.string(),
130
+ fields: o.array(ne),
131
+ defaultView: o.enum(["table", "grid", "list"]).optional(),
132
+ features: o.object({
133
+ searchable: o.boolean().optional(),
134
+ creatable: o.boolean().optional(),
135
+ editable: o.boolean().optional(),
136
+ deletable: o.boolean().optional(),
137
+ exportable: o.boolean().optional()
138
+ }).optional()
139
+ }), oe = o.object({
140
+ id: o.string().min(1, "Signal ID is required"),
141
+ label: o.string(),
142
+ description: o.string().optional(),
143
+ kind: o.enum(["sensor", "actuator", "setpoint", "metric", "status", "kpi"]),
144
+ source: o.enum(["mock", "mqtt", "http", "derived", "local"]),
145
+ // Connectivity
146
+ topic: o.string().optional(),
147
+ endpoint: o.string().optional(),
148
+ jsonPath: o.string().optional(),
149
+ refreshRate: o.number().optional().default(1e3),
150
+ // Values
151
+ defaultValue: o.any().optional(),
152
+ unit: o.string().optional(),
153
+ min: o.number().optional(),
154
+ max: o.number().optional()
155
+ }), ie = o.object({
156
+ id: o.string(),
157
+ name: o.string(),
158
+ description: o.string().optional(),
159
+ type: o.string(),
160
+ category: o.string().default("logical"),
161
+ signals: o.array(o.string()),
162
+ ui: o.object({
163
+ icon: o.string().optional(),
164
+ color: o.string().optional(),
165
+ dashboardComponent: o.string().optional()
166
+ }).optional()
167
+ }), se = o.object({
168
+ id: o.string(),
169
+ type: o.enum(["signal_change", "manual_action", "schedule", "webhook"]),
170
+ config: o.record(o.string(), o.any())
171
+ }), ce = o.object({
172
+ id: o.string(),
173
+ type: o.enum([
174
+ "update_resource",
175
+ "send_notification",
176
+ "mqtt_publish",
177
+ "api_call",
178
+ "navigate",
179
+ "agent_task"
180
+ ]),
181
+ config: o.record(o.string(), o.any())
182
+ }), le = o.object({
183
+ id: o.string(),
184
+ name: o.string(),
185
+ active: o.boolean().default(!0),
186
+ trigger: se,
187
+ actions: o.array(ce)
188
+ }), de = o.object({
189
+ id: o.string(),
190
+ type: o.string(),
191
+ props: o.record(o.string(), o.any()),
192
+ layout: o.object({
193
+ colSpan: o.number().optional(),
194
+ rowSpan: o.number().optional()
195
+ }).optional()
196
+ }), ue = o.object({
197
+ id: o.string(),
198
+ title: o.string().optional(),
199
+ description: o.string().optional(),
200
+ layout: o.object({
201
+ columns: o.number().optional(),
202
+ variant: o.enum(["grid", "stack", "split"]).optional()
203
+ }).optional(),
204
+ blocks: o.array(de)
205
+ }), me = o.object({
206
+ id: o.string(),
207
+ slug: o.string(),
208
+ title: o.string(),
209
+ description: o.string().optional(),
210
+ icon: o.string().optional(),
211
+ sections: o.array(ue)
212
+ }), pe = o.enum(["ENVIRONMENT", "SESSION_BYOK", "VAULT"]), ge = o.object({
213
+ strategy: pe,
214
+ status: o.enum(["VALID", "KEY_EXPIRED", "BYOK_REQUIRED", "DEGRADED", "UNKNOWN"]).default("UNKNOWN")
215
+ }), Tt = o.object({
216
+ meta: o.object({
217
+ name: o.string(),
218
+ version: o.string(),
219
+ description: o.string().optional(),
220
+ author: o.string().optional(),
221
+ createdAt: o.string().optional()
222
+ }),
223
+ config: o.object({
224
+ theme: o.enum(["light", "dark", "system", "corporate", "midnight", "blueprint"]).default("system"),
225
+ layout: o.enum(["dashboard", "explorer", "studio", "focus"]).default("dashboard"),
226
+ mockMode: o.boolean().default(!0),
227
+ brokerUrl: o.string().optional(),
228
+ aiKeyManifest: ge.optional()
229
+ }),
230
+ modules: o.array(o.string()).optional(),
231
+ resources: o.array(ae).optional(),
232
+ domain: o.object({
233
+ signals: o.array(oe),
234
+ entities: o.array(ie),
235
+ workflows: o.array(le).optional()
236
+ }),
237
+ pages: o.array(me).optional()
238
+ }), St = o.object({
239
+ timestamp: o.number(),
240
+ soilMoisture: o.number().min(0).max(100),
241
+ ambientLight: o.number().min(0).max(1e5),
242
+ temperature: o.number().min(-40).max(125)
243
+ }), he = o.object({
244
+ id: o.string(),
245
+ source: o.enum(["mqtt", "http", "ws", "mock"]),
246
+ domain: o.string(),
247
+ key: o.string(),
248
+ value: o.union([o.number(), o.string(), o.boolean()]),
249
+ unit: o.string().optional(),
250
+ timestamp: o.number(),
251
+ meta: o.record(o.unknown()).optional()
252
+ });
253
+ o.array(he);
254
+ var fe = o.enum(["telemetry", "market", "system", "logic"]), ye = o.enum(["mqtt", "http", "ws", "mock"]);
255
+ o.object({
256
+ /**
257
+ * Globally unique signal identifier.
258
+ * Convention: '<device-or-entity-id>:<key>'
259
+ * Examples: 'sensor-01:soil_vwc', 'AAPL:price', 'server-01:cpu_pct'
260
+ */
261
+ id: o.string(),
262
+ /**
263
+ * The semantic category of this signal.
264
+ * Determines which Methodology Engine processes it.
265
+ */
266
+ kind: fe,
267
+ /**
268
+ * The specific measurement or metric key within its kind.
269
+ * RULE: Keys MUST be abstract and domain-agnostic where possible.
270
+ * Use 'price' not 'stock_price'. Use 'moisture' not 'soil_vwc'.
271
+ * Hardware-specific keys (soil_vwc) MUST be mapped to abstract keys
272
+ * at the adapter layer BEFORE the SignalPacket is created.
273
+ */
274
+ key: o.string(),
275
+ /**
276
+ * The scalar value. Accepts number, string, or boolean.
277
+ * Structured data MUST be flattened into multiple SignalPackets,
278
+ * one per measurable dimension.
279
+ */
280
+ value: o.union([o.number(), o.string(), o.boolean()]),
281
+ /**
282
+ * Optional unit of measurement.
283
+ * Examples: 'VWC%', 'USD', 'bpm', 'ms', '°C', 'pct'
284
+ */
285
+ unit: o.string().optional(),
286
+ /**
287
+ * Unix timestamp in milliseconds (Date.now() format).
288
+ * MUST represent when the measurement was taken, not when it was received.
289
+ */
290
+ ts: o.number(),
291
+ /**
292
+ * The transport source that produced this signal.
293
+ */
294
+ source: ye.optional(),
295
+ /**
296
+ * Optional domain namespace for grouping related signals.
297
+ * Examples: 'bodewell', 'finance', 'infrastructure', 'user_behavior'
298
+ */
299
+ domain: o.string().optional(),
300
+ /**
301
+ * Optional pass-through for source-specific metadata that does NOT
302
+ * belong in the core contract (e.g. device firmware version, exchange name).
303
+ * RULE: If you find yourself reading from meta in UI components, that
304
+ * field should be promoted to the core schema or handled in the adapter.
305
+ */
306
+ meta: o.record(o.unknown()).optional()
307
+ });
308
+ var be = {};
309
+ re(be, {
310
+ BodewellCommandSchema: () => Ee,
311
+ BodewellDeviceID: () => z,
312
+ BodewellTelemetrySchema: () => we
313
+ });
314
+ var z = o.enum([
315
+ "STK-V1-001",
316
+ "STK-V1-002",
317
+ "STK-V1-003",
318
+ "STK-PRO-001",
319
+ "STK-VIS-001"
320
+ ]), we = o.object({
321
+ device_id: z,
322
+ stick_id: o.string().optional().describe("Firmware alias for device_id"),
323
+ timestamp: o.number().optional().describe("Epoch timestamp from NTP"),
324
+ air_temp: o.number().optional().describe("Celsius"),
325
+ air_humid: o.number().optional().describe("Relative Humidity %"),
326
+ humidity: o.number().optional().describe("Firmware alias for air_humid"),
327
+ air_pressure: o.number().optional().describe("hPa"),
328
+ pressure: o.number().optional().describe("Firmware alias for air_pressure"),
329
+ light_lux: o.number().optional().describe("Lux level"),
330
+ soil_temp_stemma: o.number().optional().describe("Celsius"),
331
+ soil_vwc: o.number().describe("Volumetric Water Content / Raw Capacitance"),
332
+ soil_moisture: o.number().optional().describe("Firmware alias for raw capacitance"),
333
+ soil_moisture_raw: o.number().optional().describe("Unscaled capacitance (300-1100)")
334
+ }).passthrough(), Ee = o.object({
335
+ stick_id: z,
336
+ // Note: Your API uses stick_id here, not device_id
337
+ type: o.enum(["dry", "wet"]),
338
+ value: o.number()
339
+ });
340
+ o.object({
341
+ deviceId: o.string().min(1, "Device ID is required"),
342
+ timeRange: o.enum(["1h", "24h", "7d"], {
343
+ errorMap: () => ({ message: "Time range must be 1h, 24h, or 7d" })
344
+ }),
345
+ metrics: o.array(
346
+ o.enum(["temperature", "humidity", "vwc", "ec", "ph", "pressure", "co2"])
347
+ ).min(1, "At least one metric is required").max(4, "Maximum 4 metrics per graph")
348
+ });
349
+ o.object({
350
+ ticker: o.string().min(1).describe("The stock ticker symbol explicitly requested by the user. YOU MUST EXTRACT AND PROVIDE THIS (e.g., 'AAPL', 'MSFT')."),
351
+ timeRange: o.enum(["1D", "1W", "1M", "1Y"], {
352
+ errorMap: () => ({ message: "Time range must be 1D, 1W, 1M, or 1Y" })
353
+ }).describe("The time range for the chart. Choose based on user request or default to '1M'."),
354
+ metrics: o.array(o.enum(["price", "volume", "moving_average"])).min(1, "At least one metric is required").describe("Array of metrics to display. Always include 'price' and 'volume' unless user specifies otherwise.")
355
+ });
356
+ var J = o.string().min(1).describe("The stock ticker symbol (e.g., 'AAPL', 'TSLA', 'MSFT').");
357
+ o.object({ ticker: J });
358
+ o.object({ ticker: J });
359
+ o.object({ ticker: J });
360
+ var U = "gemini-2.5-flash", Ae = "gemini-2.5-flash", ke = "gemini-2.5-pro", vt = {
361
+ /** The Strategist: high creativity, exploratory conversation */
362
+ STRATEGIST: {
363
+ model: Ae,
364
+ provider: "google-gemini",
365
+ temperature: 0.7
366
+ },
367
+ /** The Architect: data schema and resource modeling — precision required */
368
+ ARCHITECT: {
369
+ model: U,
370
+ provider: "google-gemini",
371
+ temperature: 0.3
372
+ },
373
+ /** The Designer: UI layout generation — moderate creativity */
374
+ DESIGNER: {
375
+ model: U,
376
+ provider: "google-gemini",
377
+ temperature: 0.5
378
+ },
379
+ /** The Reviewer/Product Owner: structured plan output — strict adherence.
380
+ * Uses the Pro tier for superior reasoning on complex structured tasks.
381
+ */
382
+ REVIEWER: {
383
+ model: ke,
384
+ provider: "google-gemini",
385
+ temperature: 0.2
386
+ },
387
+ /** The Genesis Engine: one-shot app generation — must be schema-strict */
388
+ GENESIS: {
389
+ model: U,
390
+ provider: "google-gemini",
391
+ temperature: 0.2
392
+ }
393
+ }, S = o.string().regex(
394
+ /^\d{1,3}\s+\d{1,3}\s+\d{1,3}$/,
395
+ 'Must be space-separated RGB integers (e.g. "13 110 253")'
396
+ ), _e = o.object({
397
+ // ── Core Brand ───────────────────────────────────────────────────────────
398
+ "--app-primary-color": S.optional(),
399
+ "--app-primary-foreground-color": S.optional(),
400
+ "--app-secondary-color": S.optional(),
401
+ "--app-secondary-foreground-color": S.optional(),
402
+ "--app-accent-color": S.optional(),
403
+ "--app-accent-foreground-color": S.optional(),
404
+ // ── Base Surface ─────────────────────────────────────────────────────────
405
+ "--app-bg-color": S.optional(),
406
+ "--app-card-bg-color": S.optional(),
407
+ "--app-text-color": S.optional(),
408
+ "--app-border-color": S.optional(),
409
+ "--app-muted-bg": S.optional(),
410
+ "--app-muted-text": S.optional(),
411
+ // ── Shape ────────────────────────────────────────────────────────────────
412
+ "--app-border-radius-sm": o.string().optional(),
413
+ "--app-border-radius-md": o.string().optional(),
414
+ "--app-border-radius-lg": o.string().optional(),
415
+ // ── Form Controls ────────────────────────────────────────────────────────
416
+ "--app-input-bg-color": S.optional(),
417
+ "--app-input-text-color": S.optional(),
418
+ "--app-input-border-color": S.optional(),
419
+ "--app-input-focus-ring-color": S.optional(),
420
+ "--app-input-placeholder-color": S.optional(),
421
+ // ── Chart Palette ────────────────────────────────────────────────────────
422
+ "--app-chart-1": S.optional(),
423
+ "--app-chart-2": S.optional(),
424
+ "--app-chart-3": S.optional(),
425
+ "--app-chart-4": S.optional(),
426
+ "--app-chart-5": S.optional()
427
+ }).strict(), Te = o.object({
428
+ /** Google Font name for headings (h1–h4, .font-serif). Example: "Playfair Display" */
429
+ heading: o.string(),
430
+ /** Google Font name for body text. Example: "Inter" */
431
+ body: o.string(),
432
+ /** Optional monospace font. Example: "Roboto Mono" */
433
+ mono: o.string().optional()
434
+ });
435
+ o.object({
436
+ /** Short descriptive theme name. Example: "Midnight Garden" */
437
+ name: o.string(),
438
+ /** One-sentence vibe description. Example: "Dark indigo with golden accents." */
439
+ description: o.string(),
440
+ /** Google Font pairing for heading and body text. */
441
+ fonts: Te.optional(),
442
+ /**
443
+ * CSS variable overrides.
444
+ * Every key must match an --app-* variable name.
445
+ * All color values must be space-separated RGB integers.
446
+ */
447
+ cssVars: _e
448
+ });
449
+ o.object({
450
+ primary: S,
451
+ neutral: S,
452
+ success: S,
453
+ warning: S,
454
+ destructive: S,
455
+ radius: o.enum(["none", "sm", "md", "lg", "full"])
456
+ });
457
+ var Ot = {
458
+ primary: "13 110 253",
459
+ neutral: "24 24 27",
460
+ success: "34 197 94",
461
+ warning: "234 179 8",
462
+ destructive: "239 68 68",
463
+ radius: "md"
464
+ };
465
+ o.object({
466
+ id: o.string().default(""),
467
+ name: o.string(),
468
+ email: o.string().email(),
469
+ password: o.string().optional(),
470
+ role: o.string(),
471
+ status: o.string().optional(),
472
+ joinedAt: o.string().optional(),
473
+ lastActive: o.string().optional(),
474
+ avatarUrl: o.string().optional()
475
+ });
476
+ var Se = o.enum([
477
+ "supplier",
478
+ "customer",
479
+ "partner",
480
+ "competitor",
481
+ "regulator",
482
+ "unknown"
483
+ ]);
484
+ o.object({
485
+ id: o.string(),
486
+ ticker: o.string().nullable(),
487
+ name: o.string(),
488
+ type: Se,
489
+ confidence: o.number().min(0).max(1),
490
+ sourceSignalIds: o.array(o.number()),
491
+ firstSeenAt: o.string().datetime(),
492
+ lastSeenAt: o.string().datetime()
493
+ });
494
+ var ve = o.enum([
495
+ "supplies_to",
496
+ "purchases_from",
497
+ "partners_with",
498
+ "competes_with",
499
+ "regulated_by"
500
+ ]);
501
+ o.object({
502
+ id: o.string(),
503
+ sourceId: o.string(),
504
+ targetId: o.string(),
505
+ edgeType: ve,
506
+ weight: o.number().min(0).max(1),
507
+ evidenceSignalIds: o.array(o.number()),
508
+ updatedAt: o.string().datetime()
509
+ });
510
+ var Oe = o.object({
511
+ signalId: o.number(),
512
+ weight: o.number().min(0).max(1),
513
+ reason: o.string().max(280)
514
+ });
515
+ o.object({
516
+ ticker: o.string(),
517
+ metric: o.enum(["operational", "ux"]),
518
+ score: o.number(),
519
+ baseline: o.number(),
520
+ observed: o.number(),
521
+ computedAt: o.string().datetime(),
522
+ contributingSignals: o.array(Oe)
523
+ });
524
+ o.object({
525
+ lei: o.string().nullable(),
526
+ entityName: o.string(),
527
+ jurisdiction: o.string().nullable(),
528
+ registrationStatus: o.string(),
529
+ parentEntityLei: o.string().nullable(),
530
+ materialMetadata: o.record(o.unknown()),
531
+ discoveredAt: o.string().datetime()
532
+ });
533
+ const Ie = Symbol("Let zodToJsonSchema decide on which parser to use"), V = {
534
+ name: void 0,
535
+ $refStrategy: "root",
536
+ basePath: ["#"],
537
+ effectStrategy: "input",
538
+ pipeStrategy: "all",
539
+ dateStrategy: "format:date-time",
540
+ mapStrategy: "entries",
541
+ removeAdditionalStrategy: "passthrough",
542
+ allowedAdditionalProperties: !0,
543
+ rejectedAdditionalProperties: !1,
544
+ definitionPath: "definitions",
545
+ target: "jsonSchema7",
546
+ strictUnions: !1,
547
+ definitions: {},
548
+ errorMessages: !1,
549
+ markdownDescription: !1,
550
+ patternStrategy: "escape",
551
+ applyRegexFlags: !1,
552
+ emailStrategy: "format:email",
553
+ base64Strategy: "contentEncoding:base64",
554
+ nameStrategy: "ref",
555
+ openAiAnyTypeName: "OpenAiAnyType"
556
+ }, Pe = (n) => typeof n == "string" ? {
557
+ ...V,
558
+ name: n
559
+ } : {
560
+ ...V,
561
+ ...n
562
+ }, xe = (n) => {
563
+ const e = Pe(n), r = e.name !== void 0 ? [...e.basePath, e.definitionPath, e.name] : e.basePath;
564
+ return {
565
+ ...e,
566
+ flags: { hasReferencedOpenAiAnyType: !1 },
567
+ currentPath: r,
568
+ propertyPath: void 0,
569
+ seen: new Map(Object.entries(e.definitions).map(([t, a]) => [
570
+ a._def,
571
+ {
572
+ def: a._def,
573
+ path: [...e.basePath, e.definitionPath, t],
574
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
575
+ jsonSchema: void 0
576
+ }
577
+ ]))
578
+ };
579
+ };
580
+ function G(n, e, r, t) {
581
+ t != null && t.errorMessages && r && (n.errorMessage = {
582
+ ...n.errorMessage,
583
+ [e]: r
584
+ });
585
+ }
586
+ function T(n, e, r, t, a) {
587
+ n[e] = r, G(n, e, t, a);
588
+ }
589
+ const W = (n, e) => {
590
+ let r = 0;
591
+ for (; r < n.length && r < e.length && n[r] === e[r]; r++)
592
+ ;
593
+ return [(n.length - r).toString(), ...e.slice(r)].join("/");
594
+ };
595
+ var y;
596
+ (function(n) {
597
+ n.ZodString = "ZodString", n.ZodNumber = "ZodNumber", n.ZodNaN = "ZodNaN", n.ZodBigInt = "ZodBigInt", n.ZodBoolean = "ZodBoolean", n.ZodDate = "ZodDate", n.ZodSymbol = "ZodSymbol", n.ZodUndefined = "ZodUndefined", n.ZodNull = "ZodNull", n.ZodAny = "ZodAny", n.ZodUnknown = "ZodUnknown", n.ZodNever = "ZodNever", n.ZodVoid = "ZodVoid", n.ZodArray = "ZodArray", n.ZodObject = "ZodObject", n.ZodUnion = "ZodUnion", n.ZodDiscriminatedUnion = "ZodDiscriminatedUnion", n.ZodIntersection = "ZodIntersection", n.ZodTuple = "ZodTuple", n.ZodRecord = "ZodRecord", n.ZodMap = "ZodMap", n.ZodSet = "ZodSet", n.ZodFunction = "ZodFunction", n.ZodLazy = "ZodLazy", n.ZodLiteral = "ZodLiteral", n.ZodEnum = "ZodEnum", n.ZodEffects = "ZodEffects", n.ZodNativeEnum = "ZodNativeEnum", n.ZodOptional = "ZodOptional", n.ZodNullable = "ZodNullable", n.ZodDefault = "ZodDefault", n.ZodCatch = "ZodCatch", n.ZodPromise = "ZodPromise", n.ZodBranded = "ZodBranded", n.ZodPipeline = "ZodPipeline", n.ZodReadonly = "ZodReadonly";
598
+ })(y || (y = {}));
599
+ function I(n) {
600
+ if (n.target !== "openAi")
601
+ return {};
602
+ const e = [
603
+ ...n.basePath,
604
+ n.definitionPath,
605
+ n.openAiAnyTypeName
606
+ ];
607
+ return n.flags.hasReferencedOpenAiAnyType = !0, {
608
+ $ref: n.$refStrategy === "relative" ? W(e, n.currentPath) : e.join("/")
609
+ };
610
+ }
611
+ function Re(n, e) {
612
+ var t, a, i;
613
+ const r = {
614
+ type: "array"
615
+ };
616
+ return (t = n.type) != null && t._def && ((i = (a = n.type) == null ? void 0 : a._def) == null ? void 0 : i.typeName) !== y.ZodAny && (r.items = k(n.type._def, {
617
+ ...e,
618
+ currentPath: [...e.currentPath, "items"]
619
+ })), n.minLength && T(r, "minItems", n.minLength.value, n.minLength.message, e), n.maxLength && T(r, "maxItems", n.maxLength.value, n.maxLength.message, e), n.exactLength && (T(r, "minItems", n.exactLength.value, n.exactLength.message, e), T(r, "maxItems", n.exactLength.value, n.exactLength.message, e)), r;
620
+ }
621
+ function Ne(n, e) {
622
+ const r = {
623
+ type: "integer",
624
+ format: "int64"
625
+ };
626
+ if (!n.checks)
627
+ return r;
628
+ for (const t of n.checks)
629
+ switch (t.kind) {
630
+ case "min":
631
+ e.target === "jsonSchema7" ? t.inclusive ? T(r, "minimum", t.value, t.message, e) : T(r, "exclusiveMinimum", t.value, t.message, e) : (t.inclusive || (r.exclusiveMinimum = !0), T(r, "minimum", t.value, t.message, e));
632
+ break;
633
+ case "max":
634
+ e.target === "jsonSchema7" ? t.inclusive ? T(r, "maximum", t.value, t.message, e) : T(r, "exclusiveMaximum", t.value, t.message, e) : (t.inclusive || (r.exclusiveMaximum = !0), T(r, "maximum", t.value, t.message, e));
635
+ break;
636
+ case "multipleOf":
637
+ T(r, "multipleOf", t.value, t.message, e);
638
+ break;
639
+ }
640
+ return r;
641
+ }
642
+ function je() {
643
+ return {
644
+ type: "boolean"
645
+ };
646
+ }
647
+ function H(n, e) {
648
+ return k(n.type._def, e);
649
+ }
650
+ const De = (n, e) => k(n.innerType._def, e);
651
+ function X(n, e, r) {
652
+ const t = r ?? e.dateStrategy;
653
+ if (Array.isArray(t))
654
+ return {
655
+ anyOf: t.map((a, i) => X(n, e, a))
656
+ };
657
+ switch (t) {
658
+ case "string":
659
+ case "format:date-time":
660
+ return {
661
+ type: "string",
662
+ format: "date-time"
663
+ };
664
+ case "format:date":
665
+ return {
666
+ type: "string",
667
+ format: "date"
668
+ };
669
+ case "integer":
670
+ return Me(n, e);
671
+ }
672
+ }
673
+ const Me = (n, e) => {
674
+ const r = {
675
+ type: "integer",
676
+ format: "unix-time"
677
+ };
678
+ if (e.target === "openApi3")
679
+ return r;
680
+ for (const t of n.checks)
681
+ switch (t.kind) {
682
+ case "min":
683
+ T(
684
+ r,
685
+ "minimum",
686
+ t.value,
687
+ // This is in milliseconds
688
+ t.message,
689
+ e
690
+ );
691
+ break;
692
+ case "max":
693
+ T(
694
+ r,
695
+ "maximum",
696
+ t.value,
697
+ // This is in milliseconds
698
+ t.message,
699
+ e
700
+ );
701
+ break;
702
+ }
703
+ return r;
704
+ };
705
+ function $e(n, e) {
706
+ return {
707
+ ...k(n.innerType._def, e),
708
+ default: n.defaultValue()
709
+ };
710
+ }
711
+ function Le(n, e) {
712
+ return e.effectStrategy === "input" ? k(n.schema._def, e) : I(e);
713
+ }
714
+ function Ce(n) {
715
+ return {
716
+ type: "string",
717
+ enum: Array.from(n.values)
718
+ };
719
+ }
720
+ const Ue = (n) => "type" in n && n.type === "string" ? !1 : "allOf" in n;
721
+ function Ze(n, e) {
722
+ const r = [
723
+ k(n.left._def, {
724
+ ...e,
725
+ currentPath: [...e.currentPath, "allOf", "0"]
726
+ }),
727
+ k(n.right._def, {
728
+ ...e,
729
+ currentPath: [...e.currentPath, "allOf", "1"]
730
+ })
731
+ ].filter((i) => !!i);
732
+ let t = e.target === "jsonSchema2019-09" ? { unevaluatedProperties: !1 } : void 0;
733
+ const a = [];
734
+ return r.forEach((i) => {
735
+ if (Ue(i))
736
+ a.push(...i.allOf), i.unevaluatedProperties === void 0 && (t = void 0);
737
+ else {
738
+ let s = i;
739
+ if ("additionalProperties" in i && i.additionalProperties === !1) {
740
+ const { additionalProperties: l, ...c } = i;
741
+ s = c;
742
+ } else
743
+ t = void 0;
744
+ a.push(s);
745
+ }
746
+ }), a.length ? {
747
+ allOf: a,
748
+ ...t
749
+ } : void 0;
750
+ }
751
+ function qe(n, e) {
752
+ const r = typeof n.value;
753
+ return r !== "bigint" && r !== "number" && r !== "boolean" && r !== "string" ? {
754
+ type: Array.isArray(n.value) ? "array" : "object"
755
+ } : e.target === "openApi3" ? {
756
+ type: r === "bigint" ? "integer" : r,
757
+ enum: [n.value]
758
+ } : {
759
+ type: r === "bigint" ? "integer" : r,
760
+ const: n.value
761
+ };
762
+ }
763
+ let Z;
764
+ const x = {
765
+ /**
766
+ * `c` was changed to `[cC]` to replicate /i flag
767
+ */
768
+ cuid: /^[cC][^\s-]{8,}$/,
769
+ cuid2: /^[0-9a-z]+$/,
770
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
771
+ /**
772
+ * `a-z` was added to replicate /i flag
773
+ */
774
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
775
+ /**
776
+ * Constructed a valid Unicode RegExp
777
+ *
778
+ * Lazily instantiate since this type of regex isn't supported
779
+ * in all envs (e.g. React Native).
780
+ *
781
+ * See:
782
+ * https://github.com/colinhacks/zod/issues/2433
783
+ * Fix in Zod:
784
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
785
+ */
786
+ emoji: () => (Z === void 0 && (Z = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u")), Z),
787
+ /**
788
+ * Unused
789
+ */
790
+ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
791
+ /**
792
+ * Unused
793
+ */
794
+ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
795
+ ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
796
+ /**
797
+ * Unused
798
+ */
799
+ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
800
+ ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
801
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
802
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
803
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
804
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
805
+ };
806
+ function Q(n, e) {
807
+ const r = {
808
+ type: "string"
809
+ };
810
+ if (n.checks)
811
+ for (const t of n.checks)
812
+ switch (t.kind) {
813
+ case "min":
814
+ T(r, "minLength", typeof r.minLength == "number" ? Math.max(r.minLength, t.value) : t.value, t.message, e);
815
+ break;
816
+ case "max":
817
+ T(r, "maxLength", typeof r.maxLength == "number" ? Math.min(r.maxLength, t.value) : t.value, t.message, e);
818
+ break;
819
+ case "email":
820
+ switch (e.emailStrategy) {
821
+ case "format:email":
822
+ R(r, "email", t.message, e);
823
+ break;
824
+ case "format:idn-email":
825
+ R(r, "idn-email", t.message, e);
826
+ break;
827
+ case "pattern:zod":
828
+ O(r, x.email, t.message, e);
829
+ break;
830
+ }
831
+ break;
832
+ case "url":
833
+ R(r, "uri", t.message, e);
834
+ break;
835
+ case "uuid":
836
+ R(r, "uuid", t.message, e);
837
+ break;
838
+ case "regex":
839
+ O(r, t.regex, t.message, e);
840
+ break;
841
+ case "cuid":
842
+ O(r, x.cuid, t.message, e);
843
+ break;
844
+ case "cuid2":
845
+ O(r, x.cuid2, t.message, e);
846
+ break;
847
+ case "startsWith":
848
+ O(r, RegExp(`^${q(t.value, e)}`), t.message, e);
849
+ break;
850
+ case "endsWith":
851
+ O(r, RegExp(`${q(t.value, e)}$`), t.message, e);
852
+ break;
853
+ case "datetime":
854
+ R(r, "date-time", t.message, e);
855
+ break;
856
+ case "date":
857
+ R(r, "date", t.message, e);
858
+ break;
859
+ case "time":
860
+ R(r, "time", t.message, e);
861
+ break;
862
+ case "duration":
863
+ R(r, "duration", t.message, e);
864
+ break;
865
+ case "length":
866
+ T(r, "minLength", typeof r.minLength == "number" ? Math.max(r.minLength, t.value) : t.value, t.message, e), T(r, "maxLength", typeof r.maxLength == "number" ? Math.min(r.maxLength, t.value) : t.value, t.message, e);
867
+ break;
868
+ case "includes": {
869
+ O(r, RegExp(q(t.value, e)), t.message, e);
870
+ break;
871
+ }
872
+ case "ip": {
873
+ t.version !== "v6" && R(r, "ipv4", t.message, e), t.version !== "v4" && R(r, "ipv6", t.message, e);
874
+ break;
875
+ }
876
+ case "base64url":
877
+ O(r, x.base64url, t.message, e);
878
+ break;
879
+ case "jwt":
880
+ O(r, x.jwt, t.message, e);
881
+ break;
882
+ case "cidr": {
883
+ t.version !== "v6" && O(r, x.ipv4Cidr, t.message, e), t.version !== "v4" && O(r, x.ipv6Cidr, t.message, e);
884
+ break;
885
+ }
886
+ case "emoji":
887
+ O(r, x.emoji(), t.message, e);
888
+ break;
889
+ case "ulid": {
890
+ O(r, x.ulid, t.message, e);
891
+ break;
892
+ }
893
+ case "base64": {
894
+ switch (e.base64Strategy) {
895
+ case "format:binary": {
896
+ R(r, "binary", t.message, e);
897
+ break;
898
+ }
899
+ case "contentEncoding:base64": {
900
+ T(r, "contentEncoding", "base64", t.message, e);
901
+ break;
902
+ }
903
+ case "pattern:zod": {
904
+ O(r, x.base64, t.message, e);
905
+ break;
906
+ }
907
+ }
908
+ break;
909
+ }
910
+ case "nanoid":
911
+ O(r, x.nanoid, t.message, e);
912
+ }
913
+ return r;
914
+ }
915
+ function q(n, e) {
916
+ return e.patternStrategy === "escape" ? Je(n) : n;
917
+ }
918
+ const ze = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
919
+ function Je(n) {
920
+ let e = "";
921
+ for (let r = 0; r < n.length; r++)
922
+ ze.has(n[r]) || (e += "\\"), e += n[r];
923
+ return e;
924
+ }
925
+ function R(n, e, r, t) {
926
+ var a;
927
+ n.format || (a = n.anyOf) != null && a.some((i) => i.format) ? (n.anyOf || (n.anyOf = []), n.format && (n.anyOf.push({
928
+ format: n.format,
929
+ ...n.errorMessage && t.errorMessages && {
930
+ errorMessage: { format: n.errorMessage.format }
931
+ }
932
+ }), delete n.format, n.errorMessage && (delete n.errorMessage.format, Object.keys(n.errorMessage).length === 0 && delete n.errorMessage)), n.anyOf.push({
933
+ format: e,
934
+ ...r && t.errorMessages && { errorMessage: { format: r } }
935
+ })) : T(n, "format", e, r, t);
936
+ }
937
+ function O(n, e, r, t) {
938
+ var a;
939
+ n.pattern || (a = n.allOf) != null && a.some((i) => i.pattern) ? (n.allOf || (n.allOf = []), n.pattern && (n.allOf.push({
940
+ pattern: n.pattern,
941
+ ...n.errorMessage && t.errorMessages && {
942
+ errorMessage: { pattern: n.errorMessage.pattern }
943
+ }
944
+ }), delete n.pattern, n.errorMessage && (delete n.errorMessage.pattern, Object.keys(n.errorMessage).length === 0 && delete n.errorMessage)), n.allOf.push({
945
+ pattern: F(e, t),
946
+ ...r && t.errorMessages && { errorMessage: { pattern: r } }
947
+ })) : T(n, "pattern", F(e, t), r, t);
948
+ }
949
+ function F(n, e) {
950
+ var c;
951
+ if (!e.applyRegexFlags || !n.flags)
952
+ return n.source;
953
+ const r = {
954
+ i: n.flags.includes("i"),
955
+ m: n.flags.includes("m"),
956
+ s: n.flags.includes("s")
957
+ // `.` matches newlines
958
+ }, t = r.i ? n.source.toLowerCase() : n.source;
959
+ let a = "", i = !1, s = !1, l = !1;
960
+ for (let d = 0; d < t.length; d++) {
961
+ if (i) {
962
+ a += t[d], i = !1;
963
+ continue;
964
+ }
965
+ if (r.i) {
966
+ if (s) {
967
+ if (t[d].match(/[a-z]/)) {
968
+ l ? (a += t[d], a += `${t[d - 2]}-${t[d]}`.toUpperCase(), l = !1) : t[d + 1] === "-" && ((c = t[d + 2]) != null && c.match(/[a-z]/)) ? (a += t[d], l = !0) : a += `${t[d]}${t[d].toUpperCase()}`;
969
+ continue;
970
+ }
971
+ } else if (t[d].match(/[a-z]/)) {
972
+ a += `[${t[d]}${t[d].toUpperCase()}]`;
973
+ continue;
974
+ }
975
+ }
976
+ if (r.m) {
977
+ if (t[d] === "^") {
978
+ a += `(^|(?<=[\r
979
+ ]))`;
980
+ continue;
981
+ } else if (t[d] === "$") {
982
+ a += `($|(?=[\r
983
+ ]))`;
984
+ continue;
985
+ }
986
+ }
987
+ if (r.s && t[d] === ".") {
988
+ a += s ? `${t[d]}\r
989
+ ` : `[${t[d]}\r
990
+ ]`;
991
+ continue;
992
+ }
993
+ a += t[d], t[d] === "\\" ? i = !0 : s && t[d] === "]" ? s = !1 : !s && t[d] === "[" && (s = !0);
994
+ }
995
+ try {
996
+ new RegExp(a);
997
+ } catch {
998
+ return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`), n.source;
999
+ }
1000
+ return a;
1001
+ }
1002
+ function ee(n, e) {
1003
+ var t, a, i, s, l, c;
1004
+ if (e.target === "openAi" && console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."), e.target === "openApi3" && ((t = n.keyType) == null ? void 0 : t._def.typeName) === y.ZodEnum)
1005
+ return {
1006
+ type: "object",
1007
+ required: n.keyType._def.values,
1008
+ properties: n.keyType._def.values.reduce((d, u) => ({
1009
+ ...d,
1010
+ [u]: k(n.valueType._def, {
1011
+ ...e,
1012
+ currentPath: [...e.currentPath, "properties", u]
1013
+ }) ?? I(e)
1014
+ }), {}),
1015
+ additionalProperties: e.rejectedAdditionalProperties
1016
+ };
1017
+ const r = {
1018
+ type: "object",
1019
+ additionalProperties: k(n.valueType._def, {
1020
+ ...e,
1021
+ currentPath: [...e.currentPath, "additionalProperties"]
1022
+ }) ?? e.allowedAdditionalProperties
1023
+ };
1024
+ if (e.target === "openApi3")
1025
+ return r;
1026
+ if (((a = n.keyType) == null ? void 0 : a._def.typeName) === y.ZodString && ((i = n.keyType._def.checks) != null && i.length)) {
1027
+ const { type: d, ...u } = Q(n.keyType._def, e);
1028
+ return {
1029
+ ...r,
1030
+ propertyNames: u
1031
+ };
1032
+ } else {
1033
+ if (((s = n.keyType) == null ? void 0 : s._def.typeName) === y.ZodEnum)
1034
+ return {
1035
+ ...r,
1036
+ propertyNames: {
1037
+ enum: n.keyType._def.values
1038
+ }
1039
+ };
1040
+ if (((l = n.keyType) == null ? void 0 : l._def.typeName) === y.ZodBranded && n.keyType._def.type._def.typeName === y.ZodString && ((c = n.keyType._def.type._def.checks) != null && c.length)) {
1041
+ const { type: d, ...u } = H(n.keyType._def, e);
1042
+ return {
1043
+ ...r,
1044
+ propertyNames: u
1045
+ };
1046
+ }
1047
+ }
1048
+ return r;
1049
+ }
1050
+ function Be(n, e) {
1051
+ if (e.mapStrategy === "record")
1052
+ return ee(n, e);
1053
+ const r = k(n.keyType._def, {
1054
+ ...e,
1055
+ currentPath: [...e.currentPath, "items", "items", "0"]
1056
+ }) || I(e), t = k(n.valueType._def, {
1057
+ ...e,
1058
+ currentPath: [...e.currentPath, "items", "items", "1"]
1059
+ }) || I(e);
1060
+ return {
1061
+ type: "array",
1062
+ maxItems: 125,
1063
+ items: {
1064
+ type: "array",
1065
+ items: [r, t],
1066
+ minItems: 2,
1067
+ maxItems: 2
1068
+ }
1069
+ };
1070
+ }
1071
+ function Ke(n) {
1072
+ const e = n.values, t = Object.keys(n.values).filter((i) => typeof e[e[i]] != "number").map((i) => e[i]), a = Array.from(new Set(t.map((i) => typeof i)));
1073
+ return {
1074
+ type: a.length === 1 ? a[0] === "string" ? "string" : "number" : ["string", "number"],
1075
+ enum: t
1076
+ };
1077
+ }
1078
+ function Ve(n) {
1079
+ return n.target === "openAi" ? void 0 : {
1080
+ not: I({
1081
+ ...n,
1082
+ currentPath: [...n.currentPath, "not"]
1083
+ })
1084
+ };
1085
+ }
1086
+ function Fe(n) {
1087
+ return n.target === "openApi3" ? {
1088
+ enum: ["null"],
1089
+ nullable: !0
1090
+ } : {
1091
+ type: "null"
1092
+ };
1093
+ }
1094
+ const C = {
1095
+ ZodString: "string",
1096
+ ZodNumber: "number",
1097
+ ZodBigInt: "integer",
1098
+ ZodBoolean: "boolean",
1099
+ ZodNull: "null"
1100
+ };
1101
+ function Ye(n, e) {
1102
+ if (e.target === "openApi3")
1103
+ return Y(n, e);
1104
+ const r = n.options instanceof Map ? Array.from(n.options.values()) : n.options;
1105
+ if (r.every((t) => t._def.typeName in C && (!t._def.checks || !t._def.checks.length))) {
1106
+ const t = r.reduce((a, i) => {
1107
+ const s = C[i._def.typeName];
1108
+ return s && !a.includes(s) ? [...a, s] : a;
1109
+ }, []);
1110
+ return {
1111
+ type: t.length > 1 ? t : t[0]
1112
+ };
1113
+ } else if (r.every((t) => t._def.typeName === "ZodLiteral" && !t.description)) {
1114
+ const t = r.reduce((a, i) => {
1115
+ const s = typeof i._def.value;
1116
+ switch (s) {
1117
+ case "string":
1118
+ case "number":
1119
+ case "boolean":
1120
+ return [...a, s];
1121
+ case "bigint":
1122
+ return [...a, "integer"];
1123
+ case "object":
1124
+ if (i._def.value === null)
1125
+ return [...a, "null"];
1126
+ case "symbol":
1127
+ case "undefined":
1128
+ case "function":
1129
+ default:
1130
+ return a;
1131
+ }
1132
+ }, []);
1133
+ if (t.length === r.length) {
1134
+ const a = t.filter((i, s, l) => l.indexOf(i) === s);
1135
+ return {
1136
+ type: a.length > 1 ? a : a[0],
1137
+ enum: r.reduce((i, s) => i.includes(s._def.value) ? i : [...i, s._def.value], [])
1138
+ };
1139
+ }
1140
+ } else if (r.every((t) => t._def.typeName === "ZodEnum"))
1141
+ return {
1142
+ type: "string",
1143
+ enum: r.reduce((t, a) => [
1144
+ ...t,
1145
+ ...a._def.values.filter((i) => !t.includes(i))
1146
+ ], [])
1147
+ };
1148
+ return Y(n, e);
1149
+ }
1150
+ const Y = (n, e) => {
1151
+ const r = (n.options instanceof Map ? Array.from(n.options.values()) : n.options).map((t, a) => k(t._def, {
1152
+ ...e,
1153
+ currentPath: [...e.currentPath, "anyOf", `${a}`]
1154
+ })).filter((t) => !!t && (!e.strictUnions || typeof t == "object" && Object.keys(t).length > 0));
1155
+ return r.length ? { anyOf: r } : void 0;
1156
+ };
1157
+ function Ge(n, e) {
1158
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(n.innerType._def.typeName) && (!n.innerType._def.checks || !n.innerType._def.checks.length))
1159
+ return e.target === "openApi3" ? {
1160
+ type: C[n.innerType._def.typeName],
1161
+ nullable: !0
1162
+ } : {
1163
+ type: [
1164
+ C[n.innerType._def.typeName],
1165
+ "null"
1166
+ ]
1167
+ };
1168
+ if (e.target === "openApi3") {
1169
+ const t = k(n.innerType._def, {
1170
+ ...e,
1171
+ currentPath: [...e.currentPath]
1172
+ });
1173
+ return t && "$ref" in t ? { allOf: [t], nullable: !0 } : t && { ...t, nullable: !0 };
1174
+ }
1175
+ const r = k(n.innerType._def, {
1176
+ ...e,
1177
+ currentPath: [...e.currentPath, "anyOf", "0"]
1178
+ });
1179
+ return r && { anyOf: [r, { type: "null" }] };
1180
+ }
1181
+ function We(n, e) {
1182
+ const r = {
1183
+ type: "number"
1184
+ };
1185
+ if (!n.checks)
1186
+ return r;
1187
+ for (const t of n.checks)
1188
+ switch (t.kind) {
1189
+ case "int":
1190
+ r.type = "integer", G(r, "type", t.message, e);
1191
+ break;
1192
+ case "min":
1193
+ e.target === "jsonSchema7" ? t.inclusive ? T(r, "minimum", t.value, t.message, e) : T(r, "exclusiveMinimum", t.value, t.message, e) : (t.inclusive || (r.exclusiveMinimum = !0), T(r, "minimum", t.value, t.message, e));
1194
+ break;
1195
+ case "max":
1196
+ e.target === "jsonSchema7" ? t.inclusive ? T(r, "maximum", t.value, t.message, e) : T(r, "exclusiveMaximum", t.value, t.message, e) : (t.inclusive || (r.exclusiveMaximum = !0), T(r, "maximum", t.value, t.message, e));
1197
+ break;
1198
+ case "multipleOf":
1199
+ T(r, "multipleOf", t.value, t.message, e);
1200
+ break;
1201
+ }
1202
+ return r;
1203
+ }
1204
+ function He(n, e) {
1205
+ const r = e.target === "openAi", t = {
1206
+ type: "object",
1207
+ properties: {}
1208
+ }, a = [], i = n.shape();
1209
+ for (const l in i) {
1210
+ let c = i[l];
1211
+ if (c === void 0 || c._def === void 0)
1212
+ continue;
1213
+ let d = Qe(c);
1214
+ d && r && (c._def.typeName === "ZodOptional" && (c = c._def.innerType), c.isNullable() || (c = c.nullable()), d = !1);
1215
+ const u = k(c._def, {
1216
+ ...e,
1217
+ currentPath: [...e.currentPath, "properties", l],
1218
+ propertyPath: [...e.currentPath, "properties", l]
1219
+ });
1220
+ u !== void 0 && (t.properties[l] = u, d || a.push(l));
1221
+ }
1222
+ a.length && (t.required = a);
1223
+ const s = Xe(n, e);
1224
+ return s !== void 0 && (t.additionalProperties = s), t;
1225
+ }
1226
+ function Xe(n, e) {
1227
+ if (n.catchall._def.typeName !== "ZodNever")
1228
+ return k(n.catchall._def, {
1229
+ ...e,
1230
+ currentPath: [...e.currentPath, "additionalProperties"]
1231
+ });
1232
+ switch (n.unknownKeys) {
1233
+ case "passthrough":
1234
+ return e.allowedAdditionalProperties;
1235
+ case "strict":
1236
+ return e.rejectedAdditionalProperties;
1237
+ case "strip":
1238
+ return e.removeAdditionalStrategy === "strict" ? e.allowedAdditionalProperties : e.rejectedAdditionalProperties;
1239
+ }
1240
+ }
1241
+ function Qe(n) {
1242
+ try {
1243
+ return n.isOptional();
1244
+ } catch {
1245
+ return !0;
1246
+ }
1247
+ }
1248
+ const et = (n, e) => {
1249
+ var t;
1250
+ if (e.currentPath.toString() === ((t = e.propertyPath) == null ? void 0 : t.toString()))
1251
+ return k(n.innerType._def, e);
1252
+ const r = k(n.innerType._def, {
1253
+ ...e,
1254
+ currentPath: [...e.currentPath, "anyOf", "1"]
1255
+ });
1256
+ return r ? {
1257
+ anyOf: [
1258
+ {
1259
+ not: I(e)
1260
+ },
1261
+ r
1262
+ ]
1263
+ } : I(e);
1264
+ }, tt = (n, e) => {
1265
+ if (e.pipeStrategy === "input")
1266
+ return k(n.in._def, e);
1267
+ if (e.pipeStrategy === "output")
1268
+ return k(n.out._def, e);
1269
+ const r = k(n.in._def, {
1270
+ ...e,
1271
+ currentPath: [...e.currentPath, "allOf", "0"]
1272
+ }), t = k(n.out._def, {
1273
+ ...e,
1274
+ currentPath: [...e.currentPath, "allOf", r ? "1" : "0"]
1275
+ });
1276
+ return {
1277
+ allOf: [r, t].filter((a) => a !== void 0)
1278
+ };
1279
+ };
1280
+ function rt(n, e) {
1281
+ return k(n.type._def, e);
1282
+ }
1283
+ function nt(n, e) {
1284
+ const t = {
1285
+ type: "array",
1286
+ uniqueItems: !0,
1287
+ items: k(n.valueType._def, {
1288
+ ...e,
1289
+ currentPath: [...e.currentPath, "items"]
1290
+ })
1291
+ };
1292
+ return n.minSize && T(t, "minItems", n.minSize.value, n.minSize.message, e), n.maxSize && T(t, "maxItems", n.maxSize.value, n.maxSize.message, e), t;
1293
+ }
1294
+ function at(n, e) {
1295
+ return n.rest ? {
1296
+ type: "array",
1297
+ minItems: n.items.length,
1298
+ items: n.items.map((r, t) => k(r._def, {
1299
+ ...e,
1300
+ currentPath: [...e.currentPath, "items", `${t}`]
1301
+ })).reduce((r, t) => t === void 0 ? r : [...r, t], []),
1302
+ additionalItems: k(n.rest._def, {
1303
+ ...e,
1304
+ currentPath: [...e.currentPath, "additionalItems"]
1305
+ })
1306
+ } : {
1307
+ type: "array",
1308
+ minItems: n.items.length,
1309
+ maxItems: n.items.length,
1310
+ items: n.items.map((r, t) => k(r._def, {
1311
+ ...e,
1312
+ currentPath: [...e.currentPath, "items", `${t}`]
1313
+ })).reduce((r, t) => t === void 0 ? r : [...r, t], [])
1314
+ };
1315
+ }
1316
+ function ot(n) {
1317
+ return {
1318
+ not: I(n)
1319
+ };
1320
+ }
1321
+ function it(n) {
1322
+ return I(n);
1323
+ }
1324
+ const st = (n, e) => k(n.innerType._def, e), ct = (n, e, r) => {
1325
+ switch (e) {
1326
+ case y.ZodString:
1327
+ return Q(n, r);
1328
+ case y.ZodNumber:
1329
+ return We(n, r);
1330
+ case y.ZodObject:
1331
+ return He(n, r);
1332
+ case y.ZodBigInt:
1333
+ return Ne(n, r);
1334
+ case y.ZodBoolean:
1335
+ return je();
1336
+ case y.ZodDate:
1337
+ return X(n, r);
1338
+ case y.ZodUndefined:
1339
+ return ot(r);
1340
+ case y.ZodNull:
1341
+ return Fe(r);
1342
+ case y.ZodArray:
1343
+ return Re(n, r);
1344
+ case y.ZodUnion:
1345
+ case y.ZodDiscriminatedUnion:
1346
+ return Ye(n, r);
1347
+ case y.ZodIntersection:
1348
+ return Ze(n, r);
1349
+ case y.ZodTuple:
1350
+ return at(n, r);
1351
+ case y.ZodRecord:
1352
+ return ee(n, r);
1353
+ case y.ZodLiteral:
1354
+ return qe(n, r);
1355
+ case y.ZodEnum:
1356
+ return Ce(n);
1357
+ case y.ZodNativeEnum:
1358
+ return Ke(n);
1359
+ case y.ZodNullable:
1360
+ return Ge(n, r);
1361
+ case y.ZodOptional:
1362
+ return et(n, r);
1363
+ case y.ZodMap:
1364
+ return Be(n, r);
1365
+ case y.ZodSet:
1366
+ return nt(n, r);
1367
+ case y.ZodLazy:
1368
+ return () => n.getter()._def;
1369
+ case y.ZodPromise:
1370
+ return rt(n, r);
1371
+ case y.ZodNaN:
1372
+ case y.ZodNever:
1373
+ return Ve(r);
1374
+ case y.ZodEffects:
1375
+ return Le(n, r);
1376
+ case y.ZodAny:
1377
+ return I(r);
1378
+ case y.ZodUnknown:
1379
+ return it(r);
1380
+ case y.ZodDefault:
1381
+ return $e(n, r);
1382
+ case y.ZodBranded:
1383
+ return H(n, r);
1384
+ case y.ZodReadonly:
1385
+ return st(n, r);
1386
+ case y.ZodCatch:
1387
+ return De(n, r);
1388
+ case y.ZodPipeline:
1389
+ return tt(n, r);
1390
+ case y.ZodFunction:
1391
+ case y.ZodVoid:
1392
+ case y.ZodSymbol:
1393
+ return;
1394
+ default:
1395
+ return /* @__PURE__ */ ((t) => {
1396
+ })();
1397
+ }
1398
+ };
1399
+ function k(n, e, r = !1) {
1400
+ var l;
1401
+ const t = e.seen.get(n);
1402
+ if (e.override) {
1403
+ const c = (l = e.override) == null ? void 0 : l.call(e, n, e, t, r);
1404
+ if (c !== Ie)
1405
+ return c;
1406
+ }
1407
+ if (t && !r) {
1408
+ const c = lt(t, e);
1409
+ if (c !== void 0)
1410
+ return c;
1411
+ }
1412
+ const a = { def: n, path: e.currentPath, jsonSchema: void 0 };
1413
+ e.seen.set(n, a);
1414
+ const i = ct(n, n.typeName, e), s = typeof i == "function" ? k(i(), e) : i;
1415
+ if (s && dt(n, e, s), e.postProcess) {
1416
+ const c = e.postProcess(s, n, e);
1417
+ return a.jsonSchema = s, c;
1418
+ }
1419
+ return a.jsonSchema = s, s;
1420
+ }
1421
+ const lt = (n, e) => {
1422
+ switch (e.$refStrategy) {
1423
+ case "root":
1424
+ return { $ref: n.path.join("/") };
1425
+ case "relative":
1426
+ return { $ref: W(e.currentPath, n.path) };
1427
+ case "none":
1428
+ case "seen":
1429
+ return n.path.length < e.currentPath.length && n.path.every((r, t) => e.currentPath[t] === r) ? (console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`), I(e)) : e.$refStrategy === "seen" ? I(e) : void 0;
1430
+ }
1431
+ }, dt = (n, e, r) => (n.description && (r.description = n.description, e.markdownDescription && (r.markdownDescription = n.description)), r), ut = (n, e) => {
1432
+ const r = xe(e);
1433
+ let t = typeof e == "object" && e.definitions ? Object.entries(e.definitions).reduce((c, [d, u]) => ({
1434
+ ...c,
1435
+ [d]: k(u._def, {
1436
+ ...r,
1437
+ currentPath: [...r.basePath, r.definitionPath, d]
1438
+ }, !0) ?? I(r)
1439
+ }), {}) : void 0;
1440
+ const a = typeof e == "string" ? e : (e == null ? void 0 : e.nameStrategy) === "title" || e == null ? void 0 : e.name, i = k(n._def, a === void 0 ? r : {
1441
+ ...r,
1442
+ currentPath: [...r.basePath, r.definitionPath, a]
1443
+ }, !1) ?? I(r), s = typeof e == "object" && e.name !== void 0 && e.nameStrategy === "title" ? e.name : void 0;
1444
+ s !== void 0 && (i.title = s), r.flags.hasReferencedOpenAiAnyType && (t || (t = {}), t[r.openAiAnyTypeName] || (t[r.openAiAnyTypeName] = {
1445
+ // Skipping "object" as no properties can be defined and additionalProperties must be "false"
1446
+ type: ["string", "number", "integer", "boolean", "array", "null"],
1447
+ items: {
1448
+ $ref: r.$refStrategy === "relative" ? "1" : [
1449
+ ...r.basePath,
1450
+ r.definitionPath,
1451
+ r.openAiAnyTypeName
1452
+ ].join("/")
1453
+ }
1454
+ }));
1455
+ const l = a === void 0 ? t ? {
1456
+ ...i,
1457
+ [r.definitionPath]: t
1458
+ } : i : {
1459
+ $ref: [
1460
+ ...r.$refStrategy === "relative" ? [] : r.basePath,
1461
+ r.definitionPath,
1462
+ a
1463
+ ].join("/"),
1464
+ [r.definitionPath]: {
1465
+ ...t,
1466
+ [a]: i
1467
+ }
1468
+ };
1469
+ return r.target === "jsonSchema7" ? l.$schema = "http://json-schema.org/draft-07/schema#" : (r.target === "jsonSchema2019-09" || r.target === "openAi") && (l.$schema = "https://json-schema.org/draft/2019-09/schema#"), r.target === "openAi" && ("anyOf" in l || "oneOf" in l || "allOf" in l || "type" in l && Array.isArray(l.type)) && console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."), l;
1470
+ };
1471
+ function It(n) {
1472
+ const e = ut(n.parameters, { target: "jsonSchema7", $refStrategy: "none" });
1473
+ return {
1474
+ name: n.name,
1475
+ description: n.description,
1476
+ parameters: e
1477
+ };
1478
+ }
1479
+ function mt(n) {
1480
+ const e = /* @__PURE__ */ new Set(["$schema", "additionalProperties", "default"]), r = (t) => Array.isArray(t) ? t.map(r) : t && typeof t == "object" ? Object.fromEntries(
1481
+ Object.entries(t).filter(([a]) => !e.has(a)).map(([a, i]) => [a, r(i)])
1482
+ ) : t;
1483
+ return r(n);
1484
+ }
1485
+ class pt {
1486
+ async *streamChat(e, r, t) {
1487
+ var g, h, w, f;
1488
+ const { apiKey: a, model: i = "gemini-1.5-flash" } = r;
1489
+ if (!a) throw new Error("Gemini API key required");
1490
+ const s = e.find((b) => b.role === "system"), l = e.filter((b) => b.role !== "system").map((b) => ({ role: b.role === "assistant" ? "model" : "user", parts: [{ text: b.content }] })), c = t != null && t.length ? [{
1491
+ functionDeclarations: t.map((b) => ({
1492
+ name: b.name,
1493
+ description: b.description,
1494
+ parameters: mt(b.parameters)
1495
+ }))
1496
+ }] : void 0, d = await fetch(
1497
+ `https://generativelanguage.googleapis.com/v1beta/models/${i}:streamGenerateContent?alt=sse`,
1498
+ {
1499
+ method: "POST",
1500
+ headers: { "Content-Type": "application/json", "x-goog-api-key": a },
1501
+ body: JSON.stringify({
1502
+ contents: l,
1503
+ ...s && { systemInstruction: { parts: [{ text: s.content }] } },
1504
+ ...c && { tools: c }
1505
+ })
1506
+ }
1507
+ );
1508
+ if (!d.ok) {
1509
+ const b = await d.text();
1510
+ throw new Error(`Gemini Error ${d.status}: ${b}`);
1511
+ }
1512
+ const u = (g = d.body) == null ? void 0 : g.getReader();
1513
+ if (!u) throw new Error("No response body");
1514
+ const m = new TextDecoder();
1515
+ let p = "";
1516
+ for (; ; ) {
1517
+ const { done: b, value: A } = await u.read();
1518
+ if (b) break;
1519
+ p += m.decode(A, { stream: !0 });
1520
+ const v = p.split(`
1521
+ `);
1522
+ p = v.pop() || "";
1523
+ for (const E of v) {
1524
+ const _ = E.trim();
1525
+ if (!(!_ || !_.startsWith("data: ")))
1526
+ try {
1527
+ const D = ((f = (w = (h = JSON.parse(_.slice(6)).candidates) == null ? void 0 : h[0]) == null ? void 0 : w.content) == null ? void 0 : f.parts) ?? [];
1528
+ for (const j of D)
1529
+ j.text && (yield { type: "text-delta", text: j.text }), j.functionCall && (yield {
1530
+ type: "tool-call",
1531
+ toolCall: { name: j.functionCall.name, arguments: j.functionCall.args ?? {} }
1532
+ });
1533
+ } catch {
1534
+ }
1535
+ }
1536
+ }
1537
+ }
1538
+ async generateText(e, r) {
1539
+ var c, d, u, m, p;
1540
+ const { apiKey: t, model: a = "gemini-1.5-flash", temperature: i = 0.7 } = r;
1541
+ if (!t) throw new Error("Gemini API key required");
1542
+ if (!a) throw new Error("GeminiAdapter: model is required but was undefined");
1543
+ const s = await fetch(
1544
+ `https://generativelanguage.googleapis.com/v1beta/models/${a}:generateContent`,
1545
+ {
1546
+ method: "POST",
1547
+ headers: {
1548
+ "Content-Type": "application/json",
1549
+ "x-goog-api-key": t
1550
+ },
1551
+ body: JSON.stringify({
1552
+ contents: [{ parts: [{ text: e }] }],
1553
+ generationConfig: { temperature: i }
1554
+ })
1555
+ }
1556
+ );
1557
+ if (!s.ok) {
1558
+ const g = await s.text();
1559
+ throw new Error(`Gemini Error ${s.status}: ${g}`);
1560
+ }
1561
+ return ((p = (m = (u = (d = (c = (await s.json()).candidates) == null ? void 0 : c[0]) == null ? void 0 : d.content) == null ? void 0 : u.parts) == null ? void 0 : m[0]) == null ? void 0 : p.text) || "";
1562
+ }
1563
+ async *streamText(e, r) {
1564
+ var d, u, m, p, g, h;
1565
+ const { apiKey: t, model: a = "gemini-1.5-flash" } = r;
1566
+ if (!t) throw new Error("Gemini API key required");
1567
+ if (!a) throw new Error("GeminiAdapter: model is required but was undefined");
1568
+ const i = await fetch(
1569
+ `https://generativelanguage.googleapis.com/v1beta/models/${a}:streamGenerateContent?alt=sse`,
1570
+ {
1571
+ method: "POST",
1572
+ headers: {
1573
+ "Content-Type": "application/json",
1574
+ "x-goog-api-key": t
1575
+ },
1576
+ body: JSON.stringify({
1577
+ contents: [{ parts: [{ text: e }] }]
1578
+ })
1579
+ }
1580
+ );
1581
+ if (!i.ok) {
1582
+ const w = await i.text();
1583
+ throw new Error(`Gemini Error ${i.status}: ${w}`);
1584
+ }
1585
+ const s = (d = i.body) == null ? void 0 : d.getReader();
1586
+ if (!s) throw new Error("No response body");
1587
+ const l = new TextDecoder();
1588
+ let c = "";
1589
+ for (; ; ) {
1590
+ const { done: w, value: f } = await s.read();
1591
+ if (w) break;
1592
+ c += l.decode(f, { stream: !0 });
1593
+ const b = c.split(`
1594
+ `);
1595
+ c = b.pop() || "";
1596
+ for (const A of b) {
1597
+ const v = A.trim();
1598
+ if (!(!v || !v.startsWith("data: ")))
1599
+ try {
1600
+ const _ = (h = (g = (p = (m = (u = JSON.parse(v.slice(6)).candidates) == null ? void 0 : u[0]) == null ? void 0 : m.content) == null ? void 0 : p.parts) == null ? void 0 : g[0]) == null ? void 0 : h.text;
1601
+ _ && (yield _);
1602
+ } catch {
1603
+ continue;
1604
+ }
1605
+ }
1606
+ }
1607
+ }
1608
+ async generateObject(e, r, t) {
1609
+ var d, u, m, p, g;
1610
+ const { apiKey: a, model: i = "gemini-1.5-flash" } = t;
1611
+ if (!a) throw new Error("Gemini API key required");
1612
+ if (!i) throw new Error("GeminiAdapter: model is required but was undefined");
1613
+ const s = await fetch(
1614
+ `https://generativelanguage.googleapis.com/v1beta/models/${i}:generateContent`,
1615
+ {
1616
+ method: "POST",
1617
+ headers: {
1618
+ "Content-Type": "application/json",
1619
+ "x-goog-api-key": a
1620
+ },
1621
+ body: JSON.stringify({
1622
+ contents: [{ parts: [{ text: e }] }],
1623
+ generationConfig: {
1624
+ responseMimeType: "application/json",
1625
+ responseSchema: r
1626
+ }
1627
+ })
1628
+ }
1629
+ );
1630
+ if (!s.ok) {
1631
+ const h = await s.json();
1632
+ throw this.normalizeError(h, s.status);
1633
+ }
1634
+ const c = ((g = (p = (m = (u = (d = (await s.json()).candidates) == null ? void 0 : d[0]) == null ? void 0 : u.content) == null ? void 0 : m.parts) == null ? void 0 : p[0]) == null ? void 0 : g.text) || "{}";
1635
+ return JSON.parse(c);
1636
+ }
1637
+ async listModels(e) {
1638
+ var a;
1639
+ if (!e) throw new Error("API key required to list models");
1640
+ const r = await fetch(
1641
+ "https://generativelanguage.googleapis.com/v1beta/models",
1642
+ {
1643
+ headers: { "x-goog-api-key": e }
1644
+ }
1645
+ );
1646
+ if (!r.ok)
1647
+ throw new Error("Failed to fetch model list");
1648
+ return ((a = (await r.json()).models) == null ? void 0 : a.map((i) => i.name)) || [];
1649
+ }
1650
+ normalizeError(e, r) {
1651
+ var t;
1652
+ if (r === 429) {
1653
+ const a = new Error("Rate limit exceeded. Please wait 30 seconds before retrying.");
1654
+ return a.code = "RATE_LIMIT", a;
1655
+ }
1656
+ if (r === 401 || r === 403) {
1657
+ const a = new Error("Invalid API key.");
1658
+ return a.code = "AUTH_ERROR", a;
1659
+ }
1660
+ return new Error(((t = e.error) == null ? void 0 : t.message) || "Unknown error");
1661
+ }
1662
+ }
1663
+ class gt {
1664
+ /**
1665
+ * Tool calling requires /api/chat, not /api/generate (which has no tool
1666
+ * support at all). Tool support itself is model-dependent (llama3.1+,
1667
+ * qwen2.5, mistral-nemo, etc.) — a non-tool-capable model just replies
1668
+ * with plain text; there's no reliable way to detect that in advance, so
1669
+ * this degrades gracefully rather than special-casing it.
1670
+ */
1671
+ async *streamChat(e, r, t) {
1672
+ var m, p, g, h, w;
1673
+ const { baseUrl: a = "http://localhost:11434", model: i = "llama3.2" } = r, s = t != null && t.length ? t.map((f) => ({ type: "function", function: { name: f.name, description: f.description, parameters: f.parameters } })) : void 0, l = await fetch(`${a}/api/chat`, {
1674
+ method: "POST",
1675
+ headers: { "Content-Type": "application/json" },
1676
+ body: JSON.stringify({
1677
+ model: i,
1678
+ messages: e.map((f) => ({ role: f.role, content: f.content })),
1679
+ stream: !0,
1680
+ ...s && { tools: s }
1681
+ })
1682
+ });
1683
+ if (!l.ok) {
1684
+ const f = await l.text();
1685
+ throw new Error(`Ollama Error ${l.status}: ${f}`);
1686
+ }
1687
+ const c = (m = l.body) == null ? void 0 : m.getReader();
1688
+ if (!c) throw new Error("No response body");
1689
+ const d = new TextDecoder();
1690
+ let u = "";
1691
+ for (; ; ) {
1692
+ const { done: f, value: b } = await c.read();
1693
+ if (f) break;
1694
+ u += d.decode(b, { stream: !0 });
1695
+ const A = u.split(`
1696
+ `);
1697
+ u = A.pop() || "";
1698
+ for (const v of A) {
1699
+ const E = v.trim();
1700
+ if (E)
1701
+ try {
1702
+ const _ = JSON.parse(E);
1703
+ if ((p = _.message) != null && p.content && (yield { type: "text-delta", text: _.message.content }), (g = _.message) != null && g.tool_calls)
1704
+ for (const N of _.message.tool_calls)
1705
+ yield {
1706
+ type: "tool-call",
1707
+ toolCall: { name: (h = N.function) == null ? void 0 : h.name, arguments: ((w = N.function) == null ? void 0 : w.arguments) ?? {} }
1708
+ };
1709
+ } catch {
1710
+ }
1711
+ }
1712
+ }
1713
+ }
1714
+ async generateText(e, r) {
1715
+ const { baseUrl: t = "http://localhost:11434", model: a = "llama3.2" } = r, i = await fetch(`${t}/api/generate`, {
1716
+ method: "POST",
1717
+ headers: { "Content-Type": "application/json" },
1718
+ body: JSON.stringify({
1719
+ model: a,
1720
+ prompt: e,
1721
+ stream: !1
1722
+ })
1723
+ });
1724
+ if (!i.ok) {
1725
+ const l = await i.text();
1726
+ throw new Error(`Ollama Error ${i.status}: ${l}`);
1727
+ }
1728
+ return (await i.json()).response;
1729
+ }
1730
+ async *streamText(e, r) {
1731
+ var d;
1732
+ const { baseUrl: t = "http://localhost:11434", model: a = "llama3.2" } = r, i = await fetch(`${t}/api/generate`, {
1733
+ method: "POST",
1734
+ headers: { "Content-Type": "application/json" },
1735
+ body: JSON.stringify({
1736
+ model: a,
1737
+ prompt: e,
1738
+ stream: !0
1739
+ })
1740
+ });
1741
+ if (!i.ok) {
1742
+ const u = await i.text();
1743
+ throw new Error(`Ollama Error ${i.status}: ${u}`);
1744
+ }
1745
+ const s = (d = i.body) == null ? void 0 : d.getReader();
1746
+ if (!s) throw new Error("No response body");
1747
+ const l = new TextDecoder();
1748
+ let c = "";
1749
+ for (; ; ) {
1750
+ const { done: u, value: m } = await s.read();
1751
+ if (u) break;
1752
+ c += l.decode(m, { stream: !0 });
1753
+ const p = c.split(`
1754
+ `);
1755
+ c = p.pop() || "";
1756
+ for (const g of p) {
1757
+ const h = g.trim();
1758
+ if (h)
1759
+ try {
1760
+ const w = JSON.parse(h);
1761
+ w.response && (yield w.response);
1762
+ } catch {
1763
+ continue;
1764
+ }
1765
+ }
1766
+ }
1767
+ }
1768
+ async generateObject(e, r, t) {
1769
+ const a = `${e}
1770
+
1771
+ IMPORTANT: Return ONLY valid JSON matching this schema:
1772
+ ${JSON.stringify(r, null, 2)}
1773
+
1774
+ Do not include any explanation, only the raw JSON object.`, i = await this.generateText(a, t), s = i.match(/```json\n?([\s\S]*?)\n?```/) || i.match(/\{[\s\S]*\}/), l = s ? s[1] || s[0] : i;
1775
+ return JSON.parse(l.trim());
1776
+ }
1777
+ async listModels(e, r = "http://localhost:11434") {
1778
+ var i;
1779
+ const t = await fetch(`${r}/api/tags`);
1780
+ if (!t.ok)
1781
+ throw new Error(`Failed to fetch Ollama models. Is Ollama running at ${r}?`);
1782
+ return ((i = (await t.json()).models) == null ? void 0 : i.map((s) => s.name)) || [];
1783
+ }
1784
+ }
1785
+ class ht {
1786
+ async *streamChat(e, r, t) {
1787
+ var b, A, v;
1788
+ const {
1789
+ apiKey: a,
1790
+ model: i = "claude-sonnet-4-5-20250929",
1791
+ temperature: s = 0.7,
1792
+ maxTokens: l = 4096,
1793
+ baseUrl: c = "https://api.anthropic.com/v1"
1794
+ } = r;
1795
+ if (!a) throw new Error("Anthropic API key required");
1796
+ const d = e.find((E) => E.role === "system"), u = e.filter((E) => E.role !== "system").map((E) => ({ role: E.role, content: E.content })), m = t != null && t.length ? t.map((E) => ({ name: E.name, description: E.description, input_schema: E.parameters })) : void 0, p = await fetch(`${c}/messages`, {
1797
+ method: "POST",
1798
+ headers: {
1799
+ "Content-Type": "application/json",
1800
+ "x-api-key": a,
1801
+ "anthropic-version": "2023-06-01",
1802
+ "anthropic-dangerous-direct-browser-access": "true"
1803
+ },
1804
+ body: JSON.stringify({
1805
+ model: i,
1806
+ messages: u,
1807
+ ...d && { system: d.content },
1808
+ max_tokens: l,
1809
+ temperature: s,
1810
+ stream: !0,
1811
+ ...m && { tools: m }
1812
+ })
1813
+ });
1814
+ if (!p.ok) {
1815
+ const E = await p.text();
1816
+ throw new Error(`Anthropic ${p.status}: ${E}`);
1817
+ }
1818
+ if (!p.body) throw new Error("No response body for streaming");
1819
+ const g = p.body.getReader(), h = new TextDecoder();
1820
+ let w = "", f = null;
1821
+ try {
1822
+ for (; ; ) {
1823
+ const { done: E, value: _ } = await g.read();
1824
+ if (E) break;
1825
+ w += h.decode(_, { stream: !0 });
1826
+ const N = w.split(`
1827
+ `);
1828
+ w = N.pop() || "";
1829
+ for (const D of N) {
1830
+ const j = D.trim();
1831
+ if (!(!j || !j.startsWith("data: ")))
1832
+ try {
1833
+ const P = JSON.parse(j.slice(6));
1834
+ if (P.type === "content_block_start" && ((b = P.content_block) == null ? void 0 : b.type) === "tool_use")
1835
+ f = { id: P.content_block.id, name: P.content_block.name, argsBuf: "" };
1836
+ else if (P.type === "content_block_delta")
1837
+ ((A = P.delta) == null ? void 0 : A.type) === "text_delta" && P.delta.text ? yield { type: "text-delta", text: P.delta.text } : ((v = P.delta) == null ? void 0 : v.type) === "input_json_delta" && f && (f.argsBuf += P.delta.partial_json ?? "");
1838
+ else if (P.type === "content_block_stop" && f) {
1839
+ try {
1840
+ yield {
1841
+ type: "tool-call",
1842
+ toolCall: {
1843
+ id: f.id,
1844
+ name: f.name,
1845
+ arguments: f.argsBuf ? JSON.parse(f.argsBuf) : {}
1846
+ }
1847
+ };
1848
+ } catch {
1849
+ }
1850
+ f = null;
1851
+ }
1852
+ } catch {
1853
+ }
1854
+ }
1855
+ }
1856
+ } finally {
1857
+ g.releaseLock();
1858
+ }
1859
+ }
1860
+ async generateText(e, r) {
1861
+ var u, m, p;
1862
+ const {
1863
+ apiKey: t,
1864
+ model: a = "claude-sonnet-4-5-20250929",
1865
+ temperature: i = 0.7,
1866
+ maxTokens: s = 4096,
1867
+ baseUrl: l = "https://api.anthropic.com/v1"
1868
+ } = r;
1869
+ if (!t) throw new Error("Anthropic API key required");
1870
+ if (!a) throw new Error("Model is required but was undefined");
1871
+ console.log("🔵 Anthropic Request:", {
1872
+ model: a,
1873
+ maxTokens: s,
1874
+ temperature: i,
1875
+ endpoint: `${l}/messages`,
1876
+ keyPrefix: t.slice(0, 12) + "…",
1877
+ keyLength: t.length
1878
+ });
1879
+ const c = await fetch(`${l}/messages`, {
1880
+ method: "POST",
1881
+ headers: {
1882
+ "Content-Type": "application/json",
1883
+ "x-api-key": t,
1884
+ "anthropic-version": "2023-06-01",
1885
+ "anthropic-dangerous-direct-browser-access": "true"
1886
+ },
1887
+ body: JSON.stringify({
1888
+ model: a,
1889
+ messages: [{ role: "user", content: e }],
1890
+ max_tokens: s,
1891
+ // REQUIRED by Anthropic
1892
+ temperature: i
1893
+ })
1894
+ });
1895
+ if (!c.ok) {
1896
+ const g = await c.text();
1897
+ console.error("🔴 RAW ANTHROPIC ERROR:", c.status, g), console.error("🔴 Request was made to:", `${l}/messages`), console.error("🔴 Model requested:", a);
1898
+ try {
1899
+ const h = JSON.parse(g);
1900
+ throw new Error(`Anthropic ${c.status}: ${((u = h.error) == null ? void 0 : u.message) || JSON.stringify(h)}`);
1901
+ } catch {
1902
+ throw new Error(`Anthropic ${c.status}: ${g}`);
1903
+ }
1904
+ }
1905
+ return ((p = (m = (await c.json()).content) == null ? void 0 : m[0]) == null ? void 0 : p.text) || "";
1906
+ }
1907
+ async *streamText(e, r) {
1908
+ var p, g;
1909
+ const {
1910
+ apiKey: t,
1911
+ model: a = "claude-sonnet-4-5-20250929",
1912
+ temperature: i = 0.7,
1913
+ maxTokens: s = 4096,
1914
+ baseUrl: l = "https://api.anthropic.com/v1"
1915
+ } = r;
1916
+ if (!t) throw new Error("Anthropic API key required");
1917
+ if (!a) throw new Error("Model is required but was undefined");
1918
+ const c = await fetch(`${l}/messages`, {
1919
+ method: "POST",
1920
+ headers: {
1921
+ "Content-Type": "application/json",
1922
+ "x-api-key": t,
1923
+ "anthropic-version": "2023-06-01",
1924
+ "anthropic-dangerous-direct-browser-access": "true"
1925
+ },
1926
+ body: JSON.stringify({
1927
+ model: a,
1928
+ messages: [{ role: "user", content: e }],
1929
+ max_tokens: s,
1930
+ // REQUIRED by Anthropic
1931
+ temperature: i,
1932
+ stream: !0
1933
+ })
1934
+ });
1935
+ if (!c.ok) {
1936
+ const h = await c.text();
1937
+ console.error("🔴 RAW ANTHROPIC STREAM ERROR:", c.status, h), console.error("🔴 Request was made to:", `${l}/messages`), console.error("🔴 Model requested:", a);
1938
+ try {
1939
+ const w = JSON.parse(h);
1940
+ throw new Error(`Anthropic ${c.status}: ${((p = w.error) == null ? void 0 : p.message) || JSON.stringify(w)}`);
1941
+ } catch {
1942
+ throw new Error(`Anthropic ${c.status}: ${h}`);
1943
+ }
1944
+ }
1945
+ if (!c.body) throw new Error("No response body for streaming");
1946
+ const d = c.body.getReader(), u = new TextDecoder();
1947
+ let m = "";
1948
+ try {
1949
+ for (; ; ) {
1950
+ const { done: h, value: w } = await d.read();
1951
+ if (h) break;
1952
+ m += u.decode(w, { stream: !0 });
1953
+ const f = m.split(`
1954
+ `);
1955
+ m = f.pop() || "";
1956
+ for (const b of f) {
1957
+ const A = b.trim();
1958
+ if (!A || !A.startsWith("data: ")) continue;
1959
+ const v = A.slice(6);
1960
+ try {
1961
+ const E = JSON.parse(v);
1962
+ E.type === "content_block_delta" && ((g = E.delta) != null && g.text) && (yield E.delta.text);
1963
+ } catch {
1964
+ continue;
1965
+ }
1966
+ }
1967
+ }
1968
+ } finally {
1969
+ d.releaseLock();
1970
+ }
1971
+ }
1972
+ async generateObject(e, r) {
1973
+ var h, w, f;
1974
+ const {
1975
+ apiKey: t,
1976
+ model: a = "claude-sonnet-4-5-20250929",
1977
+ temperature: i = 0.7,
1978
+ maxTokens: s = 4096,
1979
+ baseUrl: l = "https://api.anthropic.com/v1"
1980
+ } = r;
1981
+ if (!t) throw new Error("Anthropic API key required");
1982
+ if (!a) throw new Error("Model is required but was undefined");
1983
+ const c = `${e}
1984
+
1985
+ IMPORTANT: Respond ONLY with valid JSON. No markdown, no explanation, just the JSON object.`, d = await fetch(`${l}/messages`, {
1986
+ method: "POST",
1987
+ headers: {
1988
+ "Content-Type": "application/json",
1989
+ "x-api-key": t,
1990
+ "anthropic-version": "2023-06-01",
1991
+ "anthropic-dangerous-direct-browser-access": "true"
1992
+ },
1993
+ body: JSON.stringify({
1994
+ model: a,
1995
+ messages: [{ role: "user", content: c }],
1996
+ max_tokens: s,
1997
+ // REQUIRED by Anthropic
1998
+ temperature: i
1999
+ })
2000
+ });
2001
+ if (!d.ok) {
2002
+ const b = await d.text();
2003
+ console.error("🔴 RAW ANTHROPIC OBJECT ERROR:", d.status, b), console.error("🔴 Request was made to:", `${l}/messages`), console.error("🔴 Model requested:", a);
2004
+ try {
2005
+ const A = JSON.parse(b);
2006
+ throw new Error(`Anthropic ${d.status}: ${((h = A.error) == null ? void 0 : h.message) || JSON.stringify(A)}`);
2007
+ } catch {
2008
+ throw new Error(`Anthropic ${d.status}: ${b}`);
2009
+ }
2010
+ }
2011
+ const m = ((f = (w = (await d.json()).content) == null ? void 0 : w[0]) == null ? void 0 : f.text) || "{}", p = m.match(/\{[\s\S]*\}/), g = p ? p[0] : m;
2012
+ return JSON.parse(g);
2013
+ }
2014
+ async listModels(e, r) {
2015
+ return [
2016
+ "claude-sonnet-4-5-20250929",
2017
+ "claude-3-5-sonnet-20241022",
2018
+ "claude-3-5-haiku-20241022",
2019
+ "claude-3-opus-20240229"
2020
+ ];
2021
+ }
2022
+ normalizeError(e, r) {
2023
+ var i;
2024
+ const t = ((i = r.error) == null ? void 0 : i.message) || r.message || "Anthropic request failed";
2025
+ if (e === 429) {
2026
+ const s = new Error(`Rate limit exceeded: ${t}`);
2027
+ return s.code = "RATE_LIMIT_EXCEEDED", s.status = 429, s;
2028
+ }
2029
+ if (e === 401 || e === 403) {
2030
+ const s = new Error(`Authentication failed: ${t}`);
2031
+ return s.code = "AUTH_ERROR", s.status = e, s;
2032
+ }
2033
+ if (e === 400) {
2034
+ const s = new Error(`Bad request: ${t}`);
2035
+ return s.code = "INVALID_REQUEST", s.status = 400, s;
2036
+ }
2037
+ const a = new Error(t);
2038
+ return a.code = "API_ERROR", a.status = e, a;
2039
+ }
2040
+ }
2041
+ function L(n) {
2042
+ if (!(!n || n.length === 0))
2043
+ return n.map((e) => ({
2044
+ type: "function",
2045
+ function: { name: e.name, description: e.description, parameters: e.parameters }
2046
+ }));
2047
+ }
2048
+ async function* B(n, e, r, t) {
2049
+ var d, u, m, p;
2050
+ const a = await fetch(n, {
2051
+ method: "POST",
2052
+ headers: e,
2053
+ body: JSON.stringify(r)
2054
+ });
2055
+ if (!a.ok) {
2056
+ const g = await a.json().catch(() => ({}));
2057
+ throw t(a.status, g);
2058
+ }
2059
+ if (!a.body) throw new Error("No response body for streaming");
2060
+ const i = a.body.getReader(), s = new TextDecoder();
2061
+ let l = "";
2062
+ const c = /* @__PURE__ */ new Map();
2063
+ try {
2064
+ for (; ; ) {
2065
+ const { done: g, value: h } = await i.read();
2066
+ if (g) break;
2067
+ l += s.decode(h, { stream: !0 });
2068
+ const w = l.split(`
2069
+ `);
2070
+ l = w.pop() || "";
2071
+ for (const f of w) {
2072
+ const b = f.trim();
2073
+ if (!b || !b.startsWith("data: ")) continue;
2074
+ const A = b.slice(6);
2075
+ if (A !== "[DONE]")
2076
+ try {
2077
+ const E = (u = (d = JSON.parse(A).choices) == null ? void 0 : d[0]) == null ? void 0 : u.delta;
2078
+ if (!E) continue;
2079
+ if (E.content && (yield { type: "text-delta", text: E.content }), E.tool_calls)
2080
+ for (const _ of E.tool_calls) {
2081
+ const N = _.index ?? 0, D = c.get(N) ?? { name: "", args: "" };
2082
+ _.id && (D.id = _.id), (m = _.function) != null && m.name && (D.name += _.function.name), (p = _.function) != null && p.arguments && (D.args += _.function.arguments), c.set(N, D);
2083
+ }
2084
+ } catch {
2085
+ }
2086
+ }
2087
+ }
2088
+ } finally {
2089
+ i.releaseLock();
2090
+ }
2091
+ for (const g of c.values())
2092
+ if (g.name)
2093
+ try {
2094
+ yield {
2095
+ type: "tool-call",
2096
+ toolCall: {
2097
+ id: g.id,
2098
+ name: g.name,
2099
+ arguments: g.args ? JSON.parse(g.args) : {}
2100
+ }
2101
+ };
2102
+ } catch {
2103
+ }
2104
+ }
2105
+ function K(n) {
2106
+ return n.map((e) => ({ role: e.role, content: e.content }));
2107
+ }
2108
+ class ft {
2109
+ async *streamChat(e, r, t) {
2110
+ const { apiKey: a, model: i = "gpt-4o-mini", temperature: s = 0.7, baseUrl: l = "https://api.openai.com/v1" } = r;
2111
+ if (!a) throw new Error("OpenAI API key required");
2112
+ yield* B(
2113
+ `${l}/chat/completions`,
2114
+ { "Content-Type": "application/json", Authorization: `Bearer ${a}` },
2115
+ {
2116
+ model: i,
2117
+ messages: K(e),
2118
+ temperature: s,
2119
+ stream: !0,
2120
+ ...L(t) && { tools: L(t), tool_choice: "auto" }
2121
+ },
2122
+ this.normalizeError
2123
+ );
2124
+ }
2125
+ async generateText(e, r) {
2126
+ var d, u, m;
2127
+ const { apiKey: t, model: a = "gpt-4o-mini", temperature: i = 0.7, baseUrl: s = "https://api.openai.com/v1" } = r;
2128
+ if (!t) throw new Error("OpenAI API key required");
2129
+ const l = await fetch(`${s}/chat/completions`, {
2130
+ method: "POST",
2131
+ headers: {
2132
+ "Content-Type": "application/json",
2133
+ Authorization: `Bearer ${t}`
2134
+ },
2135
+ body: JSON.stringify({
2136
+ model: a,
2137
+ messages: [{ role: "user", content: e }],
2138
+ temperature: i
2139
+ })
2140
+ });
2141
+ if (!l.ok) {
2142
+ const p = await l.json();
2143
+ throw this.normalizeError(l.status, p);
2144
+ }
2145
+ return ((m = (u = (d = (await l.json()).choices) == null ? void 0 : d[0]) == null ? void 0 : u.message) == null ? void 0 : m.content) || "";
2146
+ }
2147
+ async *streamText(e, r) {
2148
+ var m, p, g;
2149
+ const { apiKey: t, model: a = "gpt-4o-mini", temperature: i = 0.7, baseUrl: s = "https://api.openai.com/v1" } = r;
2150
+ if (!t) throw new Error("OpenAI API key required");
2151
+ const l = await fetch(`${s}/chat/completions`, {
2152
+ method: "POST",
2153
+ headers: {
2154
+ "Content-Type": "application/json",
2155
+ Authorization: `Bearer ${t}`
2156
+ },
2157
+ body: JSON.stringify({
2158
+ model: a,
2159
+ messages: [{ role: "user", content: e }],
2160
+ temperature: i,
2161
+ stream: !0
2162
+ })
2163
+ });
2164
+ if (!l.ok) {
2165
+ const h = await l.json();
2166
+ throw this.normalizeError(l.status, h);
2167
+ }
2168
+ if (!l.body) throw new Error("No response body for streaming");
2169
+ const c = l.body.getReader(), d = new TextDecoder();
2170
+ let u = "";
2171
+ try {
2172
+ for (; ; ) {
2173
+ const { done: h, value: w } = await c.read();
2174
+ if (h) break;
2175
+ u += d.decode(w, { stream: !0 });
2176
+ const f = u.split(`
2177
+ `);
2178
+ u = f.pop() || "";
2179
+ for (const b of f) {
2180
+ const A = b.trim();
2181
+ if (!A || !A.startsWith("data: ")) continue;
2182
+ const v = A.slice(6);
2183
+ if (v !== "[DONE]")
2184
+ try {
2185
+ const _ = (g = (p = (m = JSON.parse(v).choices) == null ? void 0 : m[0]) == null ? void 0 : p.delta) == null ? void 0 : g.content;
2186
+ _ && (yield _);
2187
+ } catch {
2188
+ }
2189
+ }
2190
+ }
2191
+ } finally {
2192
+ c.releaseLock();
2193
+ }
2194
+ }
2195
+ async generateObject(e, r, t) {
2196
+ var m, p, g;
2197
+ const { apiKey: a, model: i = "gpt-4o-mini", temperature: s = 0.7, baseUrl: l = "https://api.openai.com/v1" } = t;
2198
+ if (!a) throw new Error("OpenAI API key required");
2199
+ const c = await fetch(`${l}/chat/completions`, {
2200
+ method: "POST",
2201
+ headers: {
2202
+ "Content-Type": "application/json",
2203
+ Authorization: `Bearer ${a}`
2204
+ },
2205
+ body: JSON.stringify({
2206
+ model: i,
2207
+ messages: [{ role: "user", content: e }],
2208
+ response_format: { type: "json_object" },
2209
+ temperature: s
2210
+ })
2211
+ });
2212
+ if (!c.ok) {
2213
+ const h = await c.json();
2214
+ throw this.normalizeError(c.status, h);
2215
+ }
2216
+ const u = ((g = (p = (m = (await c.json()).choices) == null ? void 0 : m[0]) == null ? void 0 : p.message) == null ? void 0 : g.content) || "{}";
2217
+ return JSON.parse(u);
2218
+ }
2219
+ async listModels(e, r) {
2220
+ var s, l;
2221
+ const t = r || "https://api.openai.com/v1";
2222
+ if (!e) throw new Error("OpenAI API key required");
2223
+ const a = await fetch(`${t}/models`, {
2224
+ headers: {
2225
+ Authorization: `Bearer ${e}`
2226
+ }
2227
+ });
2228
+ if (!a.ok) {
2229
+ const c = await a.json();
2230
+ throw this.normalizeError(a.status, c);
2231
+ }
2232
+ return ((l = (s = (await a.json()).data) == null ? void 0 : s.filter((c) => c.id.startsWith("gpt-"))) == null ? void 0 : l.map((c) => c.id)) || [];
2233
+ }
2234
+ normalizeError(e, r) {
2235
+ var i;
2236
+ const t = ((i = r.error) == null ? void 0 : i.message) || r.message || "OpenAI request failed";
2237
+ if (e === 429) {
2238
+ const s = new Error(`Rate limit exceeded: ${t}`);
2239
+ return s.code = "RATE_LIMIT_EXCEEDED", s.status = 429, s;
2240
+ }
2241
+ if (e === 401 || e === 403) {
2242
+ const s = new Error(`Authentication failed: ${t}`);
2243
+ return s.code = "AUTH_ERROR", s.status = e, s;
2244
+ }
2245
+ const a = new Error(t);
2246
+ return a.code = "API_ERROR", a.status = e, a;
2247
+ }
2248
+ }
2249
+ class yt {
2250
+ async *streamChat(e, r, t) {
2251
+ const { apiKey: a, model: i = "grok-beta", temperature: s = 0.7, baseUrl: l = "https://api.x.ai/v1" } = r;
2252
+ if (!a) throw new Error("Grok API key required");
2253
+ yield* B(
2254
+ `${l}/chat/completions`,
2255
+ { "Content-Type": "application/json", Authorization: `Bearer ${a}` },
2256
+ {
2257
+ model: i,
2258
+ messages: K(e),
2259
+ temperature: s,
2260
+ stream: !0,
2261
+ ...L(t) && { tools: L(t), tool_choice: "auto" }
2262
+ },
2263
+ this.normalizeError
2264
+ );
2265
+ }
2266
+ async generateText(e, r) {
2267
+ var d, u, m;
2268
+ const { apiKey: t, model: a = "grok-beta", temperature: i = 0.7, baseUrl: s = "https://api.x.ai/v1" } = r;
2269
+ if (!t) throw new Error("Grok API key required");
2270
+ const l = await fetch(`${s}/chat/completions`, {
2271
+ method: "POST",
2272
+ headers: {
2273
+ "Content-Type": "application/json",
2274
+ Authorization: `Bearer ${t}`
2275
+ },
2276
+ body: JSON.stringify({
2277
+ model: a,
2278
+ messages: [{ role: "user", content: e }],
2279
+ temperature: i
2280
+ })
2281
+ });
2282
+ if (!l.ok) {
2283
+ const p = await l.json();
2284
+ throw this.normalizeError(l.status, p);
2285
+ }
2286
+ return ((m = (u = (d = (await l.json()).choices) == null ? void 0 : d[0]) == null ? void 0 : u.message) == null ? void 0 : m.content) || "";
2287
+ }
2288
+ async *streamText(e, r) {
2289
+ var m, p, g;
2290
+ const { apiKey: t, model: a = "grok-beta", temperature: i = 0.7, baseUrl: s = "https://api.x.ai/v1" } = r;
2291
+ if (!t) throw new Error("Grok API key required");
2292
+ const l = await fetch(`${s}/chat/completions`, {
2293
+ method: "POST",
2294
+ headers: {
2295
+ "Content-Type": "application/json",
2296
+ Authorization: `Bearer ${t}`
2297
+ },
2298
+ body: JSON.stringify({
2299
+ model: a,
2300
+ messages: [{ role: "user", content: e }],
2301
+ temperature: i,
2302
+ stream: !0
2303
+ })
2304
+ });
2305
+ if (!l.ok) {
2306
+ const h = await l.json();
2307
+ throw this.normalizeError(l.status, h);
2308
+ }
2309
+ if (!l.body) throw new Error("No response body for streaming");
2310
+ const c = l.body.getReader(), d = new TextDecoder();
2311
+ let u = "";
2312
+ try {
2313
+ for (; ; ) {
2314
+ const { done: h, value: w } = await c.read();
2315
+ if (h) break;
2316
+ u += d.decode(w, { stream: !0 });
2317
+ const f = u.split(`
2318
+ `);
2319
+ u = f.pop() || "";
2320
+ for (const b of f) {
2321
+ const A = b.trim();
2322
+ if (!A || !A.startsWith("data: ")) continue;
2323
+ const v = A.slice(6);
2324
+ if (v !== "[DONE]")
2325
+ try {
2326
+ const _ = (g = (p = (m = JSON.parse(v).choices) == null ? void 0 : m[0]) == null ? void 0 : p.delta) == null ? void 0 : g.content;
2327
+ _ && (yield _);
2328
+ } catch {
2329
+ }
2330
+ }
2331
+ }
2332
+ } finally {
2333
+ c.releaseLock();
2334
+ }
2335
+ }
2336
+ async generateObject(e, r, t) {
2337
+ var h, w, f;
2338
+ const { apiKey: a, model: i = "grok-beta", temperature: s = 0.7, baseUrl: l = "https://api.x.ai/v1" } = t;
2339
+ if (!a) throw new Error("Grok API key required");
2340
+ const c = `${e}
2341
+
2342
+ Respond with valid JSON only.`, d = await fetch(`${l}/chat/completions`, {
2343
+ method: "POST",
2344
+ headers: {
2345
+ "Content-Type": "application/json",
2346
+ Authorization: `Bearer ${a}`
2347
+ },
2348
+ body: JSON.stringify({
2349
+ model: i,
2350
+ messages: [{ role: "user", content: c }],
2351
+ temperature: s
2352
+ })
2353
+ });
2354
+ if (!d.ok) {
2355
+ const b = await d.json();
2356
+ throw this.normalizeError(d.status, b);
2357
+ }
2358
+ const m = ((f = (w = (h = (await d.json()).choices) == null ? void 0 : h[0]) == null ? void 0 : w.message) == null ? void 0 : f.content) || "{}", p = m.match(/\{[\s\S]*\}/), g = p ? p[0] : m;
2359
+ return JSON.parse(g);
2360
+ }
2361
+ async listModels(e, r) {
2362
+ return ["grok-beta", "grok-vision-beta"];
2363
+ }
2364
+ normalizeError(e, r) {
2365
+ var i;
2366
+ const t = ((i = r.error) == null ? void 0 : i.message) || r.message || "Grok request failed";
2367
+ if (e === 429) {
2368
+ const s = new Error(`Rate limit exceeded: ${t}`);
2369
+ return s.code = "RATE_LIMIT_EXCEEDED", s.status = 429, s;
2370
+ }
2371
+ if (e === 401 || e === 403) {
2372
+ const s = new Error(`Authentication failed: ${t}`);
2373
+ return s.code = "AUTH_ERROR", s.status = e, s;
2374
+ }
2375
+ const a = new Error(t);
2376
+ return a.code = "API_ERROR", a.status = e, a;
2377
+ }
2378
+ }
2379
+ class bt {
2380
+ async *streamChat(e, r, t) {
2381
+ const { apiKey: a, model: i = "deepseek-chat", temperature: s = 0.7, baseUrl: l = "https://api.deepseek.com/v1" } = r;
2382
+ if (!a) throw new Error("DeepSeek API key required");
2383
+ yield* B(
2384
+ `${l}/chat/completions`,
2385
+ { "Content-Type": "application/json", Authorization: `Bearer ${a}` },
2386
+ {
2387
+ model: i,
2388
+ messages: K(e),
2389
+ temperature: s,
2390
+ stream: !0,
2391
+ ...L(t) && { tools: L(t), tool_choice: "auto" }
2392
+ },
2393
+ this.normalizeError
2394
+ );
2395
+ }
2396
+ async generateText(e, r) {
2397
+ var d, u, m;
2398
+ const { apiKey: t, model: a = "deepseek-chat", temperature: i = 0.7, baseUrl: s = "https://api.deepseek.com/v1" } = r;
2399
+ if (!t) throw new Error("DeepSeek API key required");
2400
+ const l = await fetch(`${s}/chat/completions`, {
2401
+ method: "POST",
2402
+ headers: {
2403
+ "Content-Type": "application/json",
2404
+ Authorization: `Bearer ${t}`
2405
+ },
2406
+ body: JSON.stringify({
2407
+ model: a,
2408
+ messages: [{ role: "user", content: e }],
2409
+ temperature: i
2410
+ })
2411
+ });
2412
+ if (!l.ok) {
2413
+ const p = await l.json();
2414
+ throw this.normalizeError(l.status, p);
2415
+ }
2416
+ return ((m = (u = (d = (await l.json()).choices) == null ? void 0 : d[0]) == null ? void 0 : u.message) == null ? void 0 : m.content) || "";
2417
+ }
2418
+ async *streamText(e, r) {
2419
+ var m, p, g;
2420
+ const { apiKey: t, model: a = "deepseek-chat", temperature: i = 0.7, baseUrl: s = "https://api.deepseek.com/v1" } = r;
2421
+ if (!t) throw new Error("DeepSeek API key required");
2422
+ const l = await fetch(`${s}/chat/completions`, {
2423
+ method: "POST",
2424
+ headers: {
2425
+ "Content-Type": "application/json",
2426
+ Authorization: `Bearer ${t}`
2427
+ },
2428
+ body: JSON.stringify({
2429
+ model: a,
2430
+ messages: [{ role: "user", content: e }],
2431
+ temperature: i,
2432
+ stream: !0
2433
+ })
2434
+ });
2435
+ if (!l.ok) {
2436
+ const h = await l.json();
2437
+ throw this.normalizeError(l.status, h);
2438
+ }
2439
+ if (!l.body) throw new Error("No response body for streaming");
2440
+ const c = l.body.getReader(), d = new TextDecoder();
2441
+ let u = "";
2442
+ try {
2443
+ for (; ; ) {
2444
+ const { done: h, value: w } = await c.read();
2445
+ if (h) break;
2446
+ u += d.decode(w, { stream: !0 });
2447
+ const f = u.split(`
2448
+ `);
2449
+ u = f.pop() || "";
2450
+ for (const b of f) {
2451
+ const A = b.trim();
2452
+ if (!A || !A.startsWith("data: ")) continue;
2453
+ const v = A.slice(6);
2454
+ if (v !== "[DONE]")
2455
+ try {
2456
+ const _ = (g = (p = (m = JSON.parse(v).choices) == null ? void 0 : m[0]) == null ? void 0 : p.delta) == null ? void 0 : g.content;
2457
+ _ && (yield _);
2458
+ } catch {
2459
+ }
2460
+ }
2461
+ }
2462
+ } finally {
2463
+ c.releaseLock();
2464
+ }
2465
+ }
2466
+ async generateObject(e, r, t) {
2467
+ var m, p, g;
2468
+ const { apiKey: a, model: i = "deepseek-chat", temperature: s = 0.7, baseUrl: l = "https://api.deepseek.com/v1" } = t;
2469
+ if (!a) throw new Error("DeepSeek API key required");
2470
+ const c = await fetch(`${l}/chat/completions`, {
2471
+ method: "POST",
2472
+ headers: {
2473
+ "Content-Type": "application/json",
2474
+ Authorization: `Bearer ${a}`
2475
+ },
2476
+ body: JSON.stringify({
2477
+ model: i,
2478
+ messages: [{ role: "user", content: e }],
2479
+ response_format: { type: "json_object" },
2480
+ temperature: s
2481
+ })
2482
+ });
2483
+ if (!c.ok) {
2484
+ const h = await c.json();
2485
+ throw this.normalizeError(c.status, h);
2486
+ }
2487
+ const u = ((g = (p = (m = (await c.json()).choices) == null ? void 0 : m[0]) == null ? void 0 : p.message) == null ? void 0 : g.content) || "{}";
2488
+ return JSON.parse(u);
2489
+ }
2490
+ async listModels(e, r) {
2491
+ return ["deepseek-chat", "deepseek-coder"];
2492
+ }
2493
+ normalizeError(e, r) {
2494
+ var i;
2495
+ const t = ((i = r.error) == null ? void 0 : i.message) || r.message || "DeepSeek request failed";
2496
+ if (e === 429) {
2497
+ const s = new Error(`Rate limit exceeded: ${t}`);
2498
+ return s.code = "RATE_LIMIT_EXCEEDED", s.status = 429, s;
2499
+ }
2500
+ if (e === 401 || e === 403) {
2501
+ const s = new Error(`Authentication failed: ${t}`);
2502
+ return s.code = "AUTH_ERROR", s.status = e, s;
2503
+ }
2504
+ const a = new Error(t);
2505
+ return a.code = "API_ERROR", a.status = e, a;
2506
+ }
2507
+ }
2508
+ let wt = class {
2509
+ constructor(e) {
2510
+ this.requests = [], this.config = e;
2511
+ }
2512
+ checkLimit() {
2513
+ const e = Date.now(), r = e - this.config.windowMs;
2514
+ return this.requests = this.requests.filter((t) => t > r), this.requests.length >= this.config.maxRequests ? !1 : (this.requests.push(e), !0);
2515
+ }
2516
+ getRemainingRequests() {
2517
+ const r = Date.now() - this.config.windowMs;
2518
+ return this.requests = this.requests.filter((t) => t > r), Math.max(0, this.config.maxRequests - this.requests.length);
2519
+ }
2520
+ getResetTime() {
2521
+ return this.requests.length === 0 ? 0 : this.requests[0] + this.config.windowMs;
2522
+ }
2523
+ };
2524
+ class $ {
2525
+ constructor() {
2526
+ this.rateLimiter = new wt({
2527
+ maxRequests: 10,
2528
+ windowMs: 6e4
2529
+ }), this.adapters = /* @__PURE__ */ new Map([
2530
+ ["google-gemini", new pt()],
2531
+ ["ollama", new gt()],
2532
+ ["anthropic", new ht()],
2533
+ ["openai", new ft()],
2534
+ ["grok", new yt()],
2535
+ ["deepseek", new bt()]
2536
+ ]);
2537
+ }
2538
+ static getInstance() {
2539
+ return $.instance || ($.instance = new $()), $.instance;
2540
+ }
2541
+ /**
2542
+ * Generate text with rate limiting and error handling
2543
+ */
2544
+ async generateText(e, r) {
2545
+ if (!this.rateLimiter.checkLimit()) {
2546
+ const a = this.rateLimiter.getResetTime(), i = new Error("Rate limit exceeded. Please wait before making another request.");
2547
+ throw i.code = "RATE_LIMIT_EXCEEDED", i.resetTime = a, i;
2548
+ }
2549
+ const t = this.adapters.get(r.provider);
2550
+ if (!t)
2551
+ throw new Error(`Provider ${r.provider} not supported yet.`);
2552
+ try {
2553
+ return await t.generateText(e, r);
2554
+ } catch (a) {
2555
+ throw console.error("[AiGateway] Error:", a), a;
2556
+ }
2557
+ }
2558
+ /**
2559
+ * Stream text generation
2560
+ */
2561
+ async *streamText(e, r) {
2562
+ if (!this.rateLimiter.checkLimit()) {
2563
+ const a = new Error("Rate limit exceeded");
2564
+ throw a.code = "RATE_LIMIT_EXCEEDED", a;
2565
+ }
2566
+ const t = this.adapters.get(r.provider);
2567
+ if (!t)
2568
+ throw new Error(`Provider ${r.provider} not supported yet.`);
2569
+ yield* t.streamText(e, r);
2570
+ }
2571
+ /**
2572
+ * Multi-turn chat streaming with optional native tool/function-calling.
2573
+ * Additive alongside streamText — does not touch its prompt-flattened path.
2574
+ */
2575
+ async *streamChat(e, r, t) {
2576
+ if (!this.rateLimiter.checkLimit()) {
2577
+ const i = new Error("Rate limit exceeded");
2578
+ throw i.code = "RATE_LIMIT_EXCEEDED", i;
2579
+ }
2580
+ const a = this.adapters.get(r.provider);
2581
+ if (!a)
2582
+ throw new Error(`Provider ${r.provider} not supported yet.`);
2583
+ if (!a.streamChat)
2584
+ throw new Error(`Provider ${r.provider} does not implement native chat streaming yet.`);
2585
+ yield* a.streamChat(e, r, t);
2586
+ }
2587
+ /**
2588
+ * Generate structured object (JSON mode)
2589
+ */
2590
+ async generateObject(e, r, t) {
2591
+ if (!this.rateLimiter.checkLimit()) {
2592
+ const i = new Error("Rate limit exceeded");
2593
+ throw i.code = "RATE_LIMIT_EXCEEDED", i;
2594
+ }
2595
+ const a = this.adapters.get(t.provider);
2596
+ if (!a)
2597
+ throw new Error(`Provider ${t.provider} not supported yet.`);
2598
+ return a.generateObject(e, r, t);
2599
+ }
2600
+ /**
2601
+ * Get remaining requests before rate limit
2602
+ */
2603
+ getRemainingRequests() {
2604
+ return this.rateLimiter.getRemainingRequests();
2605
+ }
2606
+ /**
2607
+ * List available models for a provider
2608
+ */
2609
+ async listModels(e, r, t) {
2610
+ const a = this.adapters.get(e);
2611
+ if (!a)
2612
+ throw new Error(`Provider ${e} not supported yet.`);
2613
+ return a.listModels(r, t);
2614
+ }
2615
+ }
2616
+ const xt = $.getInstance(), M = {};
2617
+ class Rt {
2618
+ /**
2619
+ * Resolve configuration with 3-tier priority:
2620
+ * 1. User's localStorage override (highest priority)
2621
+ * 2. App-level .env defaults
2622
+ * 3. System defaults (fallback)
2623
+ */
2624
+ static resolve(e, r) {
2625
+ const t = (e == null ? void 0 : e.provider) || (r == null ? void 0 : r.provider) || "ollama", a = (e == null ? void 0 : e.model) || (r == null ? void 0 : r.model) || this.getDefaultModel(t), i = (e == null ? void 0 : e.apiKey) || (r == null ? void 0 : r.apiKey), s = (e == null ? void 0 : e.ollamaUrl) || (r == null ? void 0 : r.ollamaUrl) || "/ollama";
2626
+ if (t !== "ollama" && !i)
2627
+ throw new Error(`API key required for provider: ${t}`);
2628
+ return {
2629
+ provider: t,
2630
+ model: a,
2631
+ apiKey: i,
2632
+ baseUrl: t === "ollama" ? s : void 0
2633
+ };
2634
+ }
2635
+ static getDefaultModel(e) {
2636
+ return {
2637
+ "google-gemini": "gemini-2.5-flash",
2638
+ openai: "gpt-4o-mini",
2639
+ anthropic: "claude-haiku-4-5-20251001",
2640
+ grok: "grok-2-1212",
2641
+ deepseek: "deepseek-chat",
2642
+ ollama: "llama3.3"
2643
+ }[e];
2644
+ }
2645
+ /**
2646
+ * Load user preferences from localStorage (client-side)
2647
+ */
2648
+ static loadUserConfig() {
2649
+ if (!(typeof window > "u"))
2650
+ return {
2651
+ provider: localStorage.getItem("app_ai_provider"),
2652
+ model: localStorage.getItem("app_ai_model") || void 0,
2653
+ apiKey: localStorage.getItem("app_ai_api_key") || void 0,
2654
+ ollamaUrl: localStorage.getItem("app_ollama_url") || void 0
2655
+ };
2656
+ }
2657
+ /**
2658
+ * Returns the env key for a specific provider — for REQUEST FLOW ONLY.
2659
+ * Never call this from UI components; use hasEnvKey() for status badges.
2660
+ */
2661
+ static getEnvKeyForProvider(e) {
2662
+ var t, a, i, s, l;
2663
+ if (typeof import.meta < "u" && M) {
2664
+ const c = M, d = (m) => (m == null ? void 0 : m.trim()) || void 0;
2665
+ return {
2666
+ "google-gemini": d(c == null ? void 0 : c.VITE_DEFAULT_GEMINI_KEY),
2667
+ openai: d(c == null ? void 0 : c.VITE_DEFAULT_OPENAI_KEY),
2668
+ anthropic: d(c == null ? void 0 : c.VITE_DEFAULT_ANTHROPIC_KEY),
2669
+ grok: d(c == null ? void 0 : c.VITE_DEFAULT_GROK_KEY),
2670
+ deepseek: d(c == null ? void 0 : c.VITE_DEFAULT_DEEPSEEK_KEY)
2671
+ }[e];
2672
+ }
2673
+ if (typeof process < "u" && process.env)
2674
+ return {
2675
+ "google-gemini": (t = process.env.VITE_DEFAULT_GEMINI_KEY) == null ? void 0 : t.trim(),
2676
+ openai: (a = process.env.VITE_DEFAULT_OPENAI_KEY) == null ? void 0 : a.trim(),
2677
+ anthropic: (i = process.env.VITE_DEFAULT_ANTHROPIC_KEY) == null ? void 0 : i.trim(),
2678
+ grok: (s = process.env.VITE_DEFAULT_GROK_KEY) == null ? void 0 : s.trim(),
2679
+ deepseek: (l = process.env.VITE_DEFAULT_DEEPSEEK_KEY) == null ? void 0 : l.trim()
2680
+ }[e];
2681
+ }
2682
+ /**
2683
+ * Returns true if an env key exists for the given provider — boolean only,
2684
+ * value never exposed. Safe to call from UI components for status badges.
2685
+ */
2686
+ static hasEnvKey(e) {
2687
+ if (typeof import.meta < "u" && M) {
2688
+ const t = M, a = (s) => (s == null ? void 0 : s.trim()) || void 0;
2689
+ return !!{
2690
+ "google-gemini": a(t == null ? void 0 : t.VITE_DEFAULT_GEMINI_KEY),
2691
+ openai: a(t == null ? void 0 : t.VITE_DEFAULT_OPENAI_KEY),
2692
+ anthropic: a(t == null ? void 0 : t.VITE_DEFAULT_ANTHROPIC_KEY),
2693
+ grok: a(t == null ? void 0 : t.VITE_DEFAULT_GROK_KEY),
2694
+ deepseek: a(t == null ? void 0 : t.VITE_DEFAULT_DEEPSEEK_KEY)
2695
+ }[e];
2696
+ }
2697
+ return typeof process < "u" && process.env ? !!{
2698
+ "google-gemini": process.env.VITE_DEFAULT_GEMINI_KEY || process.env.NEXT_PUBLIC_GEMINI_KEY,
2699
+ openai: process.env.VITE_DEFAULT_OPENAI_KEY || process.env.NEXT_PUBLIC_OPENAI_KEY,
2700
+ anthropic: process.env.VITE_DEFAULT_ANTHROPIC_KEY || process.env.NEXT_PUBLIC_ANTHROPIC_KEY
2701
+ }[e] : !1;
2702
+ }
2703
+ /**
2704
+ * Load app defaults from environment variables
2705
+ * Note: This works differently in Vite vs Next.js
2706
+ */
2707
+ static loadAppDefaults() {
2708
+ var r, t;
2709
+ if (typeof import.meta < "u" && M) {
2710
+ const a = M, i = (a == null ? void 0 : a.VITE_DEFAULT_AI_PROVIDER) || "", s = (m) => (m == null ? void 0 : m.trim()) || void 0, l = {
2711
+ "google-gemini": s(a == null ? void 0 : a.VITE_DEFAULT_GEMINI_KEY),
2712
+ openai: s(a == null ? void 0 : a.VITE_DEFAULT_OPENAI_KEY),
2713
+ anthropic: s(a == null ? void 0 : a.VITE_DEFAULT_ANTHROPIC_KEY),
2714
+ grok: s(a == null ? void 0 : a.VITE_DEFAULT_GROK_KEY),
2715
+ deepseek: s(a == null ? void 0 : a.VITE_DEFAULT_DEEPSEEK_KEY)
2716
+ };
2717
+ let c = i || "ollama";
2718
+ const u = ["google-gemini", "anthropic", "openai", "grok", "deepseek"].filter((m) => !!l[m]);
2719
+ return c === "ollama" && u.length > 0 && (c = u[0]), {
2720
+ provider: c,
2721
+ model: a == null ? void 0 : a.VITE_DEFAULT_AI_MODEL,
2722
+ apiKey: l[c],
2723
+ ollamaUrl: a == null ? void 0 : a.VITE_DEFAULT_OLLAMA_URL
2724
+ };
2725
+ }
2726
+ return typeof process < "u" && process.env ? {
2727
+ provider: (r = process.env) == null ? void 0 : r.NEXT_PUBLIC_DEFAULT_AI_PROVIDER,
2728
+ model: (t = process.env) == null ? void 0 : t.NEXT_PUBLIC_DEFAULT_AI_MODEL
2729
+ } : {};
2730
+ }
2731
+ }
2732
+ class Et {
2733
+ constructor(e) {
2734
+ this.requests = [], this.config = e;
2735
+ }
2736
+ checkLimit() {
2737
+ const e = Date.now(), r = e - this.config.windowMs;
2738
+ return this.requests = this.requests.filter((t) => t > r), this.requests.length >= this.config.maxRequests ? !1 : (this.requests.push(e), !0);
2739
+ }
2740
+ getRemainingRequests() {
2741
+ const r = Date.now() - this.config.windowMs;
2742
+ return this.requests = this.requests.filter((t) => t > r), Math.max(0, this.config.maxRequests - this.requests.length);
2743
+ }
2744
+ getResetTime() {
2745
+ return this.requests.length === 0 ? 0 : this.requests[0] + this.config.windowMs;
2746
+ }
2747
+ }
2748
+ class At {
2749
+ constructor(e = { maxRequests: 10, windowMs: 6e4 }) {
2750
+ this.rateLimiter = new Et(e);
2751
+ }
2752
+ async makeRequest(e, r) {
2753
+ if (!this.rateLimiter.checkLimit()) {
2754
+ const t = this.rateLimiter.getResetTime(), a = new Error("Rate limit exceeded. Please wait before making another request.");
2755
+ throw a.code = "RATE_LIMIT_EXCEEDED", a.resetTime = t, r && r(t), a;
2756
+ }
2757
+ return await e();
2758
+ }
2759
+ getRemainingRequests() {
2760
+ return this.rateLimiter.getRemainingRequests();
2761
+ }
2762
+ }
2763
+ const Nt = new At({ maxRequests: 10, windowMs: 6e4 });
2764
+ export {
2765
+ Rt as A,
2766
+ de as B,
2767
+ Ot as D,
2768
+ ie as E,
2769
+ St as F,
2770
+ pt as G,
2771
+ wt as I,
2772
+ gt as O,
2773
+ ue as P,
2774
+ ae as R,
2775
+ he as S,
2776
+ se as T,
2777
+ le as W,
2778
+ Ae as a,
2779
+ xt as b,
2780
+ $ as c,
2781
+ At as d,
2782
+ Nt as e,
2783
+ _t as f,
2784
+ ht as g,
2785
+ ft as h,
2786
+ yt as i,
2787
+ bt as j,
2788
+ ne as k,
2789
+ ce as l,
2790
+ me as m,
2791
+ Tt as n,
2792
+ vt as o,
2793
+ U as p,
2794
+ mt as s,
2795
+ It as t
2796
+ };