@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
@@ -1,1474 +0,0 @@
1
- import { z as e } from "zod";
2
- const ce = {
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 O = Object.defineProperty, x = (A, o) => {
118
- for (var a in o)
119
- O(A, a, { get: o[a], enumerable: !0 });
120
- }, P = e.object({
121
- key: e.string(),
122
- label: e.string(),
123
- type: e.enum(["text", "number", "currency", "percent", "delta", "date", "boolean", "status", "email", "image", "textarea"]),
124
- required: e.boolean().optional(),
125
- description: e.string().optional(),
126
- defaultValue: e.any().optional()
127
- }), N = e.object({
128
- id: e.string(),
129
- name: e.string(),
130
- fields: e.array(P),
131
- defaultView: e.enum(["table", "grid", "list"]).optional(),
132
- features: e.object({
133
- searchable: e.boolean().optional(),
134
- creatable: e.boolean().optional(),
135
- editable: e.boolean().optional(),
136
- deletable: e.boolean().optional(),
137
- exportable: e.boolean().optional()
138
- }).optional()
139
- }), v = e.object({
140
- id: e.string().min(1, "Signal ID is required"),
141
- label: e.string(),
142
- description: e.string().optional(),
143
- kind: e.enum(["sensor", "actuator", "setpoint", "metric", "status", "kpi"]),
144
- source: e.enum(["mock", "mqtt", "http", "derived", "local"]),
145
- // Connectivity
146
- topic: e.string().optional(),
147
- endpoint: e.string().optional(),
148
- jsonPath: e.string().optional(),
149
- refreshRate: e.number().optional().default(1e3),
150
- // Values
151
- defaultValue: e.any().optional(),
152
- unit: e.string().optional(),
153
- min: e.number().optional(),
154
- max: e.number().optional()
155
- }), j = e.object({
156
- id: e.string(),
157
- name: e.string(),
158
- description: e.string().optional(),
159
- type: e.string(),
160
- category: e.string().default("logical"),
161
- signals: e.array(e.string()),
162
- ui: e.object({
163
- icon: e.string().optional(),
164
- color: e.string().optional(),
165
- dashboardComponent: e.string().optional()
166
- }).optional()
167
- }), D = e.object({
168
- id: e.string(),
169
- type: e.enum(["signal_change", "manual_action", "schedule", "webhook"]),
170
- config: e.record(e.string(), e.any())
171
- }), q = e.object({
172
- id: e.string(),
173
- type: e.enum([
174
- "update_resource",
175
- "send_notification",
176
- "mqtt_publish",
177
- "api_call",
178
- "navigate",
179
- "agent_task"
180
- ]),
181
- config: e.record(e.string(), e.any())
182
- }), L = e.object({
183
- id: e.string(),
184
- name: e.string(),
185
- active: e.boolean().default(!0),
186
- trigger: D,
187
- actions: e.array(q)
188
- }), U = e.object({
189
- id: e.string(),
190
- type: e.string(),
191
- props: e.record(e.string(), e.any()),
192
- layout: e.object({
193
- colSpan: e.number().optional(),
194
- rowSpan: e.number().optional()
195
- }).optional()
196
- }), M = e.object({
197
- id: e.string(),
198
- title: e.string().optional(),
199
- description: e.string().optional(),
200
- layout: e.object({
201
- columns: e.number().optional(),
202
- variant: e.enum(["grid", "stack", "split"]).optional()
203
- }).optional(),
204
- blocks: e.array(U)
205
- }), K = e.object({
206
- id: e.string(),
207
- slug: e.string(),
208
- title: e.string(),
209
- description: e.string().optional(),
210
- icon: e.string().optional(),
211
- sections: e.array(M)
212
- }), C = e.enum(["ENVIRONMENT", "SESSION_BYOK", "VAULT"]), $ = e.object({
213
- strategy: C,
214
- status: e.enum(["VALID", "KEY_EXPIRED", "BYOK_REQUIRED", "DEGRADED", "UNKNOWN"]).default("UNKNOWN")
215
- }), le = e.object({
216
- meta: e.object({
217
- name: e.string(),
218
- version: e.string(),
219
- description: e.string().optional(),
220
- author: e.string().optional(),
221
- createdAt: e.string().optional()
222
- }),
223
- config: e.object({
224
- theme: e.enum(["light", "dark", "system", "corporate", "midnight", "blueprint"]).default("system"),
225
- layout: e.enum(["dashboard", "explorer", "studio", "focus"]).default("dashboard"),
226
- mockMode: e.boolean().default(!0),
227
- brokerUrl: e.string().optional(),
228
- aiKeyManifest: $.optional()
229
- }),
230
- modules: e.array(e.string()).optional(),
231
- resources: e.array(N).optional(),
232
- domain: e.object({
233
- signals: e.array(v),
234
- entities: e.array(j),
235
- workflows: e.array(L).optional()
236
- }),
237
- pages: e.array(K).optional()
238
- }), de = e.object({
239
- timestamp: e.number(),
240
- soilMoisture: e.number().min(0).max(100),
241
- ambientLight: e.number().min(0).max(1e5),
242
- temperature: e.number().min(-40).max(125)
243
- }), F = e.object({
244
- id: e.string(),
245
- source: e.enum(["mqtt", "http", "ws", "mock"]),
246
- domain: e.string(),
247
- key: e.string(),
248
- value: e.union([e.number(), e.string(), e.boolean()]),
249
- unit: e.string().optional(),
250
- timestamp: e.number(),
251
- meta: e.record(e.unknown()).optional()
252
- });
253
- e.array(F);
254
- var Y = e.enum(["telemetry", "market", "system", "logic"]), J = e.enum(["mqtt", "http", "ws", "mock"]);
255
- e.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: e.string(),
262
- /**
263
- * The semantic category of this signal.
264
- * Determines which Methodology Engine processes it.
265
- */
266
- kind: Y,
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: e.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: e.union([e.number(), e.string(), e.boolean()]),
281
- /**
282
- * Optional unit of measurement.
283
- * Examples: 'VWC%', 'USD', 'bpm', 'ms', '°C', 'pct'
284
- */
285
- unit: e.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: e.number(),
291
- /**
292
- * The transport source that produced this signal.
293
- */
294
- source: J.optional(),
295
- /**
296
- * Optional domain namespace for grouping related signals.
297
- * Examples: 'bodewell', 'finance', 'infrastructure', 'user_behavior'
298
- */
299
- domain: e.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: e.record(e.unknown()).optional()
307
- });
308
- var V = {};
309
- x(V, {
310
- BodewellCommandSchema: () => G,
311
- BodewellDeviceID: () => R,
312
- BodewellTelemetrySchema: () => B
313
- });
314
- var R = e.enum([
315
- "STK-V1-001",
316
- "STK-V1-002",
317
- "STK-V1-003",
318
- "STK-PRO-001",
319
- "STK-VIS-001"
320
- ]), B = e.object({
321
- device_id: R,
322
- stick_id: e.string().optional().describe("Firmware alias for device_id"),
323
- timestamp: e.number().optional().describe("Epoch timestamp from NTP"),
324
- air_temp: e.number().optional().describe("Celsius"),
325
- air_humid: e.number().optional().describe("Relative Humidity %"),
326
- humidity: e.number().optional().describe("Firmware alias for air_humid"),
327
- air_pressure: e.number().optional().describe("hPa"),
328
- pressure: e.number().optional().describe("Firmware alias for air_pressure"),
329
- light_lux: e.number().optional().describe("Lux level"),
330
- soil_temp_stemma: e.number().optional().describe("Celsius"),
331
- soil_vwc: e.number().describe("Volumetric Water Content / Raw Capacitance"),
332
- soil_moisture: e.number().optional().describe("Firmware alias for raw capacitance"),
333
- soil_moisture_raw: e.number().optional().describe("Unscaled capacitance (300-1100)")
334
- }).passthrough(), G = e.object({
335
- stick_id: R,
336
- // Note: Your API uses stick_id here, not device_id
337
- type: e.enum(["dry", "wet"]),
338
- value: e.number()
339
- });
340
- e.object({
341
- deviceId: e.string().min(1, "Device ID is required"),
342
- timeRange: e.enum(["1h", "24h", "7d"], {
343
- errorMap: () => ({ message: "Time range must be 1h, 24h, or 7d" })
344
- }),
345
- metrics: e.array(
346
- e.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
- e.object({
350
- ticker: e.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: e.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: e.array(e.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 S = "gemini-2.5-flash", z = "gemini-2.5-flash", H = "gemini-2.5-pro", pe = {
357
- /** The Strategist: high creativity, exploratory conversation */
358
- STRATEGIST: {
359
- model: z,
360
- provider: "google-gemini",
361
- temperature: 0.7
362
- },
363
- /** The Architect: data schema and resource modeling — precision required */
364
- ARCHITECT: {
365
- model: S,
366
- provider: "google-gemini",
367
- temperature: 0.3
368
- },
369
- /** The Designer: UI layout generation — moderate creativity */
370
- DESIGNER: {
371
- model: S,
372
- provider: "google-gemini",
373
- temperature: 0.5
374
- },
375
- /** The Reviewer/Product Owner: structured plan output — strict adherence.
376
- * Uses the Pro tier for superior reasoning on complex structured tasks.
377
- */
378
- REVIEWER: {
379
- model: H,
380
- provider: "google-gemini",
381
- temperature: 0.2
382
- },
383
- /** The Genesis Engine: one-shot app generation — must be schema-strict */
384
- GENESIS: {
385
- model: S,
386
- provider: "google-gemini",
387
- temperature: 0.2
388
- }
389
- }, g = e.string().regex(
390
- /^\d{1,3}\s+\d{1,3}\s+\d{1,3}$/,
391
- 'Must be space-separated RGB integers (e.g. "13 110 253")'
392
- ), W = e.object({
393
- // ── Core Brand ───────────────────────────────────────────────────────────
394
- "--app-primary-color": g.optional(),
395
- "--app-primary-foreground-color": g.optional(),
396
- "--app-secondary-color": g.optional(),
397
- "--app-secondary-foreground-color": g.optional(),
398
- "--app-accent-color": g.optional(),
399
- "--app-accent-foreground-color": g.optional(),
400
- // ── Base Surface ─────────────────────────────────────────────────────────
401
- "--app-bg-color": g.optional(),
402
- "--app-card-bg-color": g.optional(),
403
- "--app-text-color": g.optional(),
404
- "--app-border-color": g.optional(),
405
- "--app-muted-bg": g.optional(),
406
- "--app-muted-text": g.optional(),
407
- // ── Shape ────────────────────────────────────────────────────────────────
408
- "--app-border-radius-sm": e.string().optional(),
409
- "--app-border-radius-md": e.string().optional(),
410
- "--app-border-radius-lg": e.string().optional(),
411
- // ── Form Controls ────────────────────────────────────────────────────────
412
- "--app-input-bg-color": g.optional(),
413
- "--app-input-text-color": g.optional(),
414
- "--app-input-border-color": g.optional(),
415
- "--app-input-focus-ring-color": g.optional(),
416
- "--app-input-placeholder-color": g.optional(),
417
- // ── Chart Palette ────────────────────────────────────────────────────────
418
- "--app-chart-1": g.optional(),
419
- "--app-chart-2": g.optional(),
420
- "--app-chart-3": g.optional(),
421
- "--app-chart-4": g.optional(),
422
- "--app-chart-5": g.optional()
423
- }).strict(), X = e.object({
424
- /** Google Font name for headings (h1–h4, .font-serif). Example: "Playfair Display" */
425
- heading: e.string(),
426
- /** Google Font name for body text. Example: "Inter" */
427
- body: e.string(),
428
- /** Optional monospace font. Example: "Roboto Mono" */
429
- mono: e.string().optional()
430
- });
431
- e.object({
432
- /** Short descriptive theme name. Example: "Midnight Garden" */
433
- name: e.string(),
434
- /** One-sentence vibe description. Example: "Dark indigo with golden accents." */
435
- description: e.string(),
436
- /** Google Font pairing for heading and body text. */
437
- fonts: X.optional(),
438
- /**
439
- * CSS variable overrides.
440
- * Every key must match an --app-* variable name.
441
- * All color values must be space-separated RGB integers.
442
- */
443
- cssVars: W
444
- });
445
- e.object({
446
- primary: g,
447
- neutral: g,
448
- success: g,
449
- warning: g,
450
- destructive: g,
451
- radius: e.enum(["none", "sm", "md", "lg", "full"])
452
- });
453
- var me = {
454
- primary: "13 110 253",
455
- neutral: "24 24 27",
456
- success: "34 197 94",
457
- warning: "234 179 8",
458
- destructive: "239 68 68",
459
- radius: "md"
460
- };
461
- e.object({
462
- id: e.string().default(""),
463
- name: e.string(),
464
- email: e.string().email(),
465
- password: e.string().optional(),
466
- role: e.string(),
467
- status: e.string().optional(),
468
- joinedAt: e.string().optional(),
469
- lastActive: e.string().optional(),
470
- avatarUrl: e.string().optional()
471
- });
472
- class Q {
473
- async generateText(o, a) {
474
- var i, d, p, l, m;
475
- const { apiKey: r, model: t = "gemini-1.5-flash", temperature: n = 0.7 } = a;
476
- if (!r) throw new Error("Gemini API key required");
477
- if (!t) throw new Error("GeminiAdapter: model is required but was undefined");
478
- const s = await fetch(
479
- `https://generativelanguage.googleapis.com/v1beta/models/${t}:generateContent`,
480
- {
481
- method: "POST",
482
- headers: {
483
- "Content-Type": "application/json",
484
- "x-goog-api-key": r
485
- },
486
- body: JSON.stringify({
487
- contents: [{ parts: [{ text: o }] }],
488
- generationConfig: { temperature: n }
489
- })
490
- }
491
- );
492
- if (!s.ok) {
493
- const h = await s.text();
494
- throw new Error(`Gemini Error ${s.status}: ${h}`);
495
- }
496
- return ((m = (l = (p = (d = (i = (await s.json()).candidates) == null ? void 0 : i[0]) == null ? void 0 : d.content) == null ? void 0 : p.parts) == null ? void 0 : l[0]) == null ? void 0 : m.text) || "";
497
- }
498
- async *streamText(o, a) {
499
- var d, p, l, m, h, u;
500
- const { apiKey: r, model: t = "gemini-1.5-flash" } = a;
501
- if (!r) throw new Error("Gemini API key required");
502
- if (!t) throw new Error("GeminiAdapter: model is required but was undefined");
503
- const n = await fetch(
504
- `https://generativelanguage.googleapis.com/v1beta/models/${t}:streamGenerateContent?alt=sse`,
505
- {
506
- method: "POST",
507
- headers: {
508
- "Content-Type": "application/json",
509
- "x-goog-api-key": r
510
- },
511
- body: JSON.stringify({
512
- contents: [{ parts: [{ text: o }] }]
513
- })
514
- }
515
- );
516
- if (!n.ok) {
517
- const w = await n.text();
518
- throw new Error(`Gemini Error ${n.status}: ${w}`);
519
- }
520
- const s = (d = n.body) == null ? void 0 : d.getReader();
521
- if (!s) throw new Error("No response body");
522
- const c = new TextDecoder();
523
- let i = "";
524
- for (; ; ) {
525
- const { done: w, value: E } = await s.read();
526
- if (w) break;
527
- i += c.decode(E, { stream: !0 });
528
- const y = i.split(`
529
- `);
530
- i = y.pop() || "";
531
- for (const f of y) {
532
- const b = f.trim();
533
- if (!(!b || !b.startsWith("data: ")))
534
- try {
535
- const _ = (u = (h = (m = (l = (p = JSON.parse(b.slice(6)).candidates) == null ? void 0 : p[0]) == null ? void 0 : l.content) == null ? void 0 : m.parts) == null ? void 0 : h[0]) == null ? void 0 : u.text;
536
- _ && (yield _);
537
- } catch {
538
- continue;
539
- }
540
- }
541
- }
542
- }
543
- async generateObject(o, a, r) {
544
- var d, p, l, m, h;
545
- const { apiKey: t, model: n = "gemini-1.5-flash" } = r;
546
- if (!t) throw new Error("Gemini API key required");
547
- if (!n) throw new Error("GeminiAdapter: model is required but was undefined");
548
- const s = await fetch(
549
- `https://generativelanguage.googleapis.com/v1beta/models/${n}:generateContent`,
550
- {
551
- method: "POST",
552
- headers: {
553
- "Content-Type": "application/json",
554
- "x-goog-api-key": t
555
- },
556
- body: JSON.stringify({
557
- contents: [{ parts: [{ text: o }] }],
558
- generationConfig: {
559
- responseMimeType: "application/json",
560
- responseSchema: a
561
- }
562
- })
563
- }
564
- );
565
- if (!s.ok) {
566
- const u = await s.json();
567
- throw this.normalizeError(u, s.status);
568
- }
569
- const i = ((h = (m = (l = (p = (d = (await s.json()).candidates) == null ? void 0 : d[0]) == null ? void 0 : p.content) == null ? void 0 : l.parts) == null ? void 0 : m[0]) == null ? void 0 : h.text) || "{}";
570
- return JSON.parse(i);
571
- }
572
- async listModels(o) {
573
- var t;
574
- if (!o) throw new Error("API key required to list models");
575
- const a = await fetch(
576
- "https://generativelanguage.googleapis.com/v1beta/models",
577
- {
578
- headers: { "x-goog-api-key": o }
579
- }
580
- );
581
- if (!a.ok)
582
- throw new Error("Failed to fetch model list");
583
- return ((t = (await a.json()).models) == null ? void 0 : t.map((n) => n.name)) || [];
584
- }
585
- normalizeError(o, a) {
586
- var r;
587
- if (a === 429) {
588
- const t = new Error("Rate limit exceeded. Please wait 30 seconds before retrying.");
589
- return t.code = "RATE_LIMIT", t;
590
- }
591
- if (a === 401 || a === 403) {
592
- const t = new Error("Invalid API key.");
593
- return t.code = "AUTH_ERROR", t;
594
- }
595
- return new Error(((r = o.error) == null ? void 0 : r.message) || "Unknown error");
596
- }
597
- }
598
- class Z {
599
- async generateText(o, a) {
600
- const { baseUrl: r = "http://localhost:11434", model: t = "llama3.2" } = a, n = await fetch(`${r}/api/generate`, {
601
- method: "POST",
602
- headers: { "Content-Type": "application/json" },
603
- body: JSON.stringify({
604
- model: t,
605
- prompt: o,
606
- stream: !1
607
- })
608
- });
609
- if (!n.ok) {
610
- const c = await n.text();
611
- throw new Error(`Ollama Error ${n.status}: ${c}`);
612
- }
613
- return (await n.json()).response;
614
- }
615
- async *streamText(o, a) {
616
- var d;
617
- const { baseUrl: r = "http://localhost:11434", model: t = "llama3.2" } = a, n = await fetch(`${r}/api/generate`, {
618
- method: "POST",
619
- headers: { "Content-Type": "application/json" },
620
- body: JSON.stringify({
621
- model: t,
622
- prompt: o,
623
- stream: !0
624
- })
625
- });
626
- if (!n.ok) {
627
- const p = await n.text();
628
- throw new Error(`Ollama Error ${n.status}: ${p}`);
629
- }
630
- const s = (d = n.body) == null ? void 0 : d.getReader();
631
- if (!s) throw new Error("No response body");
632
- const c = new TextDecoder();
633
- let i = "";
634
- for (; ; ) {
635
- const { done: p, value: l } = await s.read();
636
- if (p) break;
637
- i += c.decode(l, { stream: !0 });
638
- const m = i.split(`
639
- `);
640
- i = m.pop() || "";
641
- for (const h of m) {
642
- const u = h.trim();
643
- if (u)
644
- try {
645
- const w = JSON.parse(u);
646
- w.response && (yield w.response);
647
- } catch {
648
- continue;
649
- }
650
- }
651
- }
652
- }
653
- async generateObject(o, a, r) {
654
- const t = `${o}
655
-
656
- IMPORTANT: Return ONLY valid JSON matching this schema:
657
- ${JSON.stringify(a, null, 2)}
658
-
659
- Do not include any explanation, only the raw JSON object.`, n = await this.generateText(t, r), s = n.match(/```json\n?([\s\S]*?)\n?```/) || n.match(/\{[\s\S]*\}/), c = s ? s[1] || s[0] : n;
660
- return JSON.parse(c.trim());
661
- }
662
- async listModels(o, a = "http://localhost:11434") {
663
- var n;
664
- const r = await fetch(`${a}/api/tags`);
665
- if (!r.ok)
666
- throw new Error(`Failed to fetch Ollama models. Is Ollama running at ${a}?`);
667
- return ((n = (await r.json()).models) == null ? void 0 : n.map((s) => s.name)) || [];
668
- }
669
- }
670
- class ee {
671
- async generateText(o, a) {
672
- var p, l, m;
673
- const {
674
- apiKey: r,
675
- model: t = "claude-sonnet-4-5-20250929",
676
- temperature: n = 0.7,
677
- maxTokens: s = 4096,
678
- baseUrl: c = "https://api.anthropic.com/v1"
679
- } = a;
680
- if (!r) throw new Error("Anthropic API key required");
681
- if (!t) throw new Error("Model is required but was undefined");
682
- console.log("🔵 Anthropic Request:", {
683
- model: t,
684
- maxTokens: s,
685
- temperature: n,
686
- endpoint: `${c}/messages`,
687
- keyPrefix: r.slice(0, 12) + "…",
688
- keyLength: r.length
689
- });
690
- const i = await fetch(`${c}/messages`, {
691
- method: "POST",
692
- headers: {
693
- "Content-Type": "application/json",
694
- "x-api-key": r,
695
- "anthropic-version": "2023-06-01",
696
- "anthropic-dangerous-direct-browser-access": "true"
697
- },
698
- body: JSON.stringify({
699
- model: t,
700
- messages: [{ role: "user", content: o }],
701
- max_tokens: s,
702
- // REQUIRED by Anthropic
703
- temperature: n
704
- })
705
- });
706
- if (!i.ok) {
707
- const h = await i.text();
708
- console.error("🔴 RAW ANTHROPIC ERROR:", i.status, h), console.error("🔴 Request was made to:", `${c}/messages`), console.error("🔴 Model requested:", t);
709
- try {
710
- const u = JSON.parse(h);
711
- throw new Error(`Anthropic ${i.status}: ${((p = u.error) == null ? void 0 : p.message) || JSON.stringify(u)}`);
712
- } catch {
713
- throw new Error(`Anthropic ${i.status}: ${h}`);
714
- }
715
- }
716
- return ((m = (l = (await i.json()).content) == null ? void 0 : l[0]) == null ? void 0 : m.text) || "";
717
- }
718
- async *streamText(o, a) {
719
- var m, h;
720
- const {
721
- apiKey: r,
722
- model: t = "claude-sonnet-4-5-20250929",
723
- temperature: n = 0.7,
724
- maxTokens: s = 4096,
725
- baseUrl: c = "https://api.anthropic.com/v1"
726
- } = a;
727
- if (!r) throw new Error("Anthropic API key required");
728
- if (!t) throw new Error("Model is required but was undefined");
729
- const i = await fetch(`${c}/messages`, {
730
- method: "POST",
731
- headers: {
732
- "Content-Type": "application/json",
733
- "x-api-key": r,
734
- "anthropic-version": "2023-06-01",
735
- "anthropic-dangerous-direct-browser-access": "true"
736
- },
737
- body: JSON.stringify({
738
- model: t,
739
- messages: [{ role: "user", content: o }],
740
- max_tokens: s,
741
- // REQUIRED by Anthropic
742
- temperature: n,
743
- stream: !0
744
- })
745
- });
746
- if (!i.ok) {
747
- const u = await i.text();
748
- console.error("🔴 RAW ANTHROPIC STREAM ERROR:", i.status, u), console.error("🔴 Request was made to:", `${c}/messages`), console.error("🔴 Model requested:", t);
749
- try {
750
- const w = JSON.parse(u);
751
- throw new Error(`Anthropic ${i.status}: ${((m = w.error) == null ? void 0 : m.message) || JSON.stringify(w)}`);
752
- } catch {
753
- throw new Error(`Anthropic ${i.status}: ${u}`);
754
- }
755
- }
756
- if (!i.body) throw new Error("No response body for streaming");
757
- const d = i.body.getReader(), p = new TextDecoder();
758
- let l = "";
759
- try {
760
- for (; ; ) {
761
- const { done: u, value: w } = await d.read();
762
- if (u) break;
763
- l += p.decode(w, { stream: !0 });
764
- const E = l.split(`
765
- `);
766
- l = E.pop() || "";
767
- for (const y of E) {
768
- const f = y.trim();
769
- if (!f || !f.startsWith("data: ")) continue;
770
- const b = f.slice(6);
771
- try {
772
- const T = JSON.parse(b);
773
- T.type === "content_block_delta" && ((h = T.delta) != null && h.text) && (yield T.delta.text);
774
- } catch {
775
- continue;
776
- }
777
- }
778
- }
779
- } finally {
780
- d.releaseLock();
781
- }
782
- }
783
- async generateObject(o, a) {
784
- var u, w, E;
785
- const {
786
- apiKey: r,
787
- model: t = "claude-sonnet-4-5-20250929",
788
- temperature: n = 0.7,
789
- maxTokens: s = 4096,
790
- baseUrl: c = "https://api.anthropic.com/v1"
791
- } = a;
792
- if (!r) throw new Error("Anthropic API key required");
793
- if (!t) throw new Error("Model is required but was undefined");
794
- const i = `${o}
795
-
796
- IMPORTANT: Respond ONLY with valid JSON. No markdown, no explanation, just the JSON object.`, d = await fetch(`${c}/messages`, {
797
- method: "POST",
798
- headers: {
799
- "Content-Type": "application/json",
800
- "x-api-key": r,
801
- "anthropic-version": "2023-06-01",
802
- "anthropic-dangerous-direct-browser-access": "true"
803
- },
804
- body: JSON.stringify({
805
- model: t,
806
- messages: [{ role: "user", content: i }],
807
- max_tokens: s,
808
- // REQUIRED by Anthropic
809
- temperature: n
810
- })
811
- });
812
- if (!d.ok) {
813
- const y = await d.text();
814
- console.error("🔴 RAW ANTHROPIC OBJECT ERROR:", d.status, y), console.error("🔴 Request was made to:", `${c}/messages`), console.error("🔴 Model requested:", t);
815
- try {
816
- const f = JSON.parse(y);
817
- throw new Error(`Anthropic ${d.status}: ${((u = f.error) == null ? void 0 : u.message) || JSON.stringify(f)}`);
818
- } catch {
819
- throw new Error(`Anthropic ${d.status}: ${y}`);
820
- }
821
- }
822
- const l = ((E = (w = (await d.json()).content) == null ? void 0 : w[0]) == null ? void 0 : E.text) || "{}", m = l.match(/\{[\s\S]*\}/), h = m ? m[0] : l;
823
- return JSON.parse(h);
824
- }
825
- async listModels(o, a) {
826
- return [
827
- "claude-sonnet-4-5-20250929",
828
- "claude-3-5-sonnet-20241022",
829
- "claude-3-5-haiku-20241022",
830
- "claude-3-opus-20240229"
831
- ];
832
- }
833
- normalizeError(o, a) {
834
- var n;
835
- const r = ((n = a.error) == null ? void 0 : n.message) || a.message || "Anthropic request failed";
836
- if (o === 429) {
837
- const s = new Error(`Rate limit exceeded: ${r}`);
838
- return s.code = "RATE_LIMIT_EXCEEDED", s.status = 429, s;
839
- }
840
- if (o === 401 || o === 403) {
841
- const s = new Error(`Authentication failed: ${r}`);
842
- return s.code = "AUTH_ERROR", s.status = o, s;
843
- }
844
- if (o === 400) {
845
- const s = new Error(`Bad request: ${r}`);
846
- return s.code = "INVALID_REQUEST", s.status = 400, s;
847
- }
848
- const t = new Error(r);
849
- return t.code = "API_ERROR", t.status = o, t;
850
- }
851
- }
852
- class te {
853
- async generateText(o, a) {
854
- var d, p, l;
855
- const { apiKey: r, model: t = "gpt-4o-mini", temperature: n = 0.7, baseUrl: s = "https://api.openai.com/v1" } = a;
856
- if (!r) throw new Error("OpenAI API key required");
857
- const c = await fetch(`${s}/chat/completions`, {
858
- method: "POST",
859
- headers: {
860
- "Content-Type": "application/json",
861
- Authorization: `Bearer ${r}`
862
- },
863
- body: JSON.stringify({
864
- model: t,
865
- messages: [{ role: "user", content: o }],
866
- temperature: n
867
- })
868
- });
869
- if (!c.ok) {
870
- const m = await c.json();
871
- throw this.normalizeError(c.status, m);
872
- }
873
- return ((l = (p = (d = (await c.json()).choices) == null ? void 0 : d[0]) == null ? void 0 : p.message) == null ? void 0 : l.content) || "";
874
- }
875
- async *streamText(o, a) {
876
- var l, m, h;
877
- const { apiKey: r, model: t = "gpt-4o-mini", temperature: n = 0.7, baseUrl: s = "https://api.openai.com/v1" } = a;
878
- if (!r) throw new Error("OpenAI API key required");
879
- const c = await fetch(`${s}/chat/completions`, {
880
- method: "POST",
881
- headers: {
882
- "Content-Type": "application/json",
883
- Authorization: `Bearer ${r}`
884
- },
885
- body: JSON.stringify({
886
- model: t,
887
- messages: [{ role: "user", content: o }],
888
- temperature: n,
889
- stream: !0
890
- })
891
- });
892
- if (!c.ok) {
893
- const u = await c.json();
894
- throw this.normalizeError(c.status, u);
895
- }
896
- if (!c.body) throw new Error("No response body for streaming");
897
- const i = c.body.getReader(), d = new TextDecoder();
898
- let p = "";
899
- try {
900
- for (; ; ) {
901
- const { done: u, value: w } = await i.read();
902
- if (u) break;
903
- p += d.decode(w, { stream: !0 });
904
- const E = p.split(`
905
- `);
906
- p = E.pop() || "";
907
- for (const y of E) {
908
- const f = y.trim();
909
- if (!f || !f.startsWith("data: ")) continue;
910
- const b = f.slice(6);
911
- if (b !== "[DONE]")
912
- try {
913
- const _ = (h = (m = (l = JSON.parse(b).choices) == null ? void 0 : l[0]) == null ? void 0 : m.delta) == null ? void 0 : h.content;
914
- _ && (yield _);
915
- } catch {
916
- }
917
- }
918
- }
919
- } finally {
920
- i.releaseLock();
921
- }
922
- }
923
- async generateObject(o, a, r) {
924
- var l, m, h;
925
- const { apiKey: t, model: n = "gpt-4o-mini", temperature: s = 0.7, baseUrl: c = "https://api.openai.com/v1" } = r;
926
- if (!t) throw new Error("OpenAI API key required");
927
- const i = await fetch(`${c}/chat/completions`, {
928
- method: "POST",
929
- headers: {
930
- "Content-Type": "application/json",
931
- Authorization: `Bearer ${t}`
932
- },
933
- body: JSON.stringify({
934
- model: n,
935
- messages: [{ role: "user", content: o }],
936
- response_format: { type: "json_object" },
937
- temperature: s
938
- })
939
- });
940
- if (!i.ok) {
941
- const u = await i.json();
942
- throw this.normalizeError(i.status, u);
943
- }
944
- const p = ((h = (m = (l = (await i.json()).choices) == null ? void 0 : l[0]) == null ? void 0 : m.message) == null ? void 0 : h.content) || "{}";
945
- return JSON.parse(p);
946
- }
947
- async listModels(o, a) {
948
- var s, c;
949
- const r = a || "https://api.openai.com/v1";
950
- if (!o) throw new Error("OpenAI API key required");
951
- const t = await fetch(`${r}/models`, {
952
- headers: {
953
- Authorization: `Bearer ${o}`
954
- }
955
- });
956
- if (!t.ok) {
957
- const i = await t.json();
958
- throw this.normalizeError(t.status, i);
959
- }
960
- return ((c = (s = (await t.json()).data) == null ? void 0 : s.filter((i) => i.id.startsWith("gpt-"))) == null ? void 0 : c.map((i) => i.id)) || [];
961
- }
962
- normalizeError(o, a) {
963
- var n;
964
- const r = ((n = a.error) == null ? void 0 : n.message) || a.message || "OpenAI request failed";
965
- if (o === 429) {
966
- const s = new Error(`Rate limit exceeded: ${r}`);
967
- return s.code = "RATE_LIMIT_EXCEEDED", s.status = 429, s;
968
- }
969
- if (o === 401 || o === 403) {
970
- const s = new Error(`Authentication failed: ${r}`);
971
- return s.code = "AUTH_ERROR", s.status = o, s;
972
- }
973
- const t = new Error(r);
974
- return t.code = "API_ERROR", t.status = o, t;
975
- }
976
- }
977
- class re {
978
- async generateText(o, a) {
979
- var d, p, l;
980
- const { apiKey: r, model: t = "grok-beta", temperature: n = 0.7, baseUrl: s = "https://api.x.ai/v1" } = a;
981
- if (!r) throw new Error("Grok API key required");
982
- const c = await fetch(`${s}/chat/completions`, {
983
- method: "POST",
984
- headers: {
985
- "Content-Type": "application/json",
986
- Authorization: `Bearer ${r}`
987
- },
988
- body: JSON.stringify({
989
- model: t,
990
- messages: [{ role: "user", content: o }],
991
- temperature: n
992
- })
993
- });
994
- if (!c.ok) {
995
- const m = await c.json();
996
- throw this.normalizeError(c.status, m);
997
- }
998
- return ((l = (p = (d = (await c.json()).choices) == null ? void 0 : d[0]) == null ? void 0 : p.message) == null ? void 0 : l.content) || "";
999
- }
1000
- async *streamText(o, a) {
1001
- var l, m, h;
1002
- const { apiKey: r, model: t = "grok-beta", temperature: n = 0.7, baseUrl: s = "https://api.x.ai/v1" } = a;
1003
- if (!r) throw new Error("Grok API key required");
1004
- const c = await fetch(`${s}/chat/completions`, {
1005
- method: "POST",
1006
- headers: {
1007
- "Content-Type": "application/json",
1008
- Authorization: `Bearer ${r}`
1009
- },
1010
- body: JSON.stringify({
1011
- model: t,
1012
- messages: [{ role: "user", content: o }],
1013
- temperature: n,
1014
- stream: !0
1015
- })
1016
- });
1017
- if (!c.ok) {
1018
- const u = await c.json();
1019
- throw this.normalizeError(c.status, u);
1020
- }
1021
- if (!c.body) throw new Error("No response body for streaming");
1022
- const i = c.body.getReader(), d = new TextDecoder();
1023
- let p = "";
1024
- try {
1025
- for (; ; ) {
1026
- const { done: u, value: w } = await i.read();
1027
- if (u) break;
1028
- p += d.decode(w, { stream: !0 });
1029
- const E = p.split(`
1030
- `);
1031
- p = E.pop() || "";
1032
- for (const y of E) {
1033
- const f = y.trim();
1034
- if (!f || !f.startsWith("data: ")) continue;
1035
- const b = f.slice(6);
1036
- if (b !== "[DONE]")
1037
- try {
1038
- const _ = (h = (m = (l = JSON.parse(b).choices) == null ? void 0 : l[0]) == null ? void 0 : m.delta) == null ? void 0 : h.content;
1039
- _ && (yield _);
1040
- } catch {
1041
- }
1042
- }
1043
- }
1044
- } finally {
1045
- i.releaseLock();
1046
- }
1047
- }
1048
- async generateObject(o, a, r) {
1049
- var u, w, E;
1050
- const { apiKey: t, model: n = "grok-beta", temperature: s = 0.7, baseUrl: c = "https://api.x.ai/v1" } = r;
1051
- if (!t) throw new Error("Grok API key required");
1052
- const i = `${o}
1053
-
1054
- Respond with valid JSON only.`, d = await fetch(`${c}/chat/completions`, {
1055
- method: "POST",
1056
- headers: {
1057
- "Content-Type": "application/json",
1058
- Authorization: `Bearer ${t}`
1059
- },
1060
- body: JSON.stringify({
1061
- model: n,
1062
- messages: [{ role: "user", content: i }],
1063
- temperature: s
1064
- })
1065
- });
1066
- if (!d.ok) {
1067
- const y = await d.json();
1068
- throw this.normalizeError(d.status, y);
1069
- }
1070
- const l = ((E = (w = (u = (await d.json()).choices) == null ? void 0 : u[0]) == null ? void 0 : w.message) == null ? void 0 : E.content) || "{}", m = l.match(/\{[\s\S]*\}/), h = m ? m[0] : l;
1071
- return JSON.parse(h);
1072
- }
1073
- async listModels(o, a) {
1074
- return ["grok-beta", "grok-vision-beta"];
1075
- }
1076
- normalizeError(o, a) {
1077
- var n;
1078
- const r = ((n = a.error) == null ? void 0 : n.message) || a.message || "Grok request failed";
1079
- if (o === 429) {
1080
- const s = new Error(`Rate limit exceeded: ${r}`);
1081
- return s.code = "RATE_LIMIT_EXCEEDED", s.status = 429, s;
1082
- }
1083
- if (o === 401 || o === 403) {
1084
- const s = new Error(`Authentication failed: ${r}`);
1085
- return s.code = "AUTH_ERROR", s.status = o, s;
1086
- }
1087
- const t = new Error(r);
1088
- return t.code = "API_ERROR", t.status = o, t;
1089
- }
1090
- }
1091
- class oe {
1092
- async generateText(o, a) {
1093
- var d, p, l;
1094
- const { apiKey: r, model: t = "deepseek-chat", temperature: n = 0.7, baseUrl: s = "https://api.deepseek.com/v1" } = a;
1095
- if (!r) throw new Error("DeepSeek API key required");
1096
- const c = await fetch(`${s}/chat/completions`, {
1097
- method: "POST",
1098
- headers: {
1099
- "Content-Type": "application/json",
1100
- Authorization: `Bearer ${r}`
1101
- },
1102
- body: JSON.stringify({
1103
- model: t,
1104
- messages: [{ role: "user", content: o }],
1105
- temperature: n
1106
- })
1107
- });
1108
- if (!c.ok) {
1109
- const m = await c.json();
1110
- throw this.normalizeError(c.status, m);
1111
- }
1112
- return ((l = (p = (d = (await c.json()).choices) == null ? void 0 : d[0]) == null ? void 0 : p.message) == null ? void 0 : l.content) || "";
1113
- }
1114
- async *streamText(o, a) {
1115
- var l, m, h;
1116
- const { apiKey: r, model: t = "deepseek-chat", temperature: n = 0.7, baseUrl: s = "https://api.deepseek.com/v1" } = a;
1117
- if (!r) throw new Error("DeepSeek API key required");
1118
- const c = await fetch(`${s}/chat/completions`, {
1119
- method: "POST",
1120
- headers: {
1121
- "Content-Type": "application/json",
1122
- Authorization: `Bearer ${r}`
1123
- },
1124
- body: JSON.stringify({
1125
- model: t,
1126
- messages: [{ role: "user", content: o }],
1127
- temperature: n,
1128
- stream: !0
1129
- })
1130
- });
1131
- if (!c.ok) {
1132
- const u = await c.json();
1133
- throw this.normalizeError(c.status, u);
1134
- }
1135
- if (!c.body) throw new Error("No response body for streaming");
1136
- const i = c.body.getReader(), d = new TextDecoder();
1137
- let p = "";
1138
- try {
1139
- for (; ; ) {
1140
- const { done: u, value: w } = await i.read();
1141
- if (u) break;
1142
- p += d.decode(w, { stream: !0 });
1143
- const E = p.split(`
1144
- `);
1145
- p = E.pop() || "";
1146
- for (const y of E) {
1147
- const f = y.trim();
1148
- if (!f || !f.startsWith("data: ")) continue;
1149
- const b = f.slice(6);
1150
- if (b !== "[DONE]")
1151
- try {
1152
- const _ = (h = (m = (l = JSON.parse(b).choices) == null ? void 0 : l[0]) == null ? void 0 : m.delta) == null ? void 0 : h.content;
1153
- _ && (yield _);
1154
- } catch {
1155
- }
1156
- }
1157
- }
1158
- } finally {
1159
- i.releaseLock();
1160
- }
1161
- }
1162
- async generateObject(o, a, r) {
1163
- var l, m, h;
1164
- const { apiKey: t, model: n = "deepseek-chat", temperature: s = 0.7, baseUrl: c = "https://api.deepseek.com/v1" } = r;
1165
- if (!t) throw new Error("DeepSeek API key required");
1166
- const i = await fetch(`${c}/chat/completions`, {
1167
- method: "POST",
1168
- headers: {
1169
- "Content-Type": "application/json",
1170
- Authorization: `Bearer ${t}`
1171
- },
1172
- body: JSON.stringify({
1173
- model: n,
1174
- messages: [{ role: "user", content: o }],
1175
- response_format: { type: "json_object" },
1176
- temperature: s
1177
- })
1178
- });
1179
- if (!i.ok) {
1180
- const u = await i.json();
1181
- throw this.normalizeError(i.status, u);
1182
- }
1183
- const p = ((h = (m = (l = (await i.json()).choices) == null ? void 0 : l[0]) == null ? void 0 : m.message) == null ? void 0 : h.content) || "{}";
1184
- return JSON.parse(p);
1185
- }
1186
- async listModels(o, a) {
1187
- return ["deepseek-chat", "deepseek-coder"];
1188
- }
1189
- normalizeError(o, a) {
1190
- var n;
1191
- const r = ((n = a.error) == null ? void 0 : n.message) || a.message || "DeepSeek request failed";
1192
- if (o === 429) {
1193
- const s = new Error(`Rate limit exceeded: ${r}`);
1194
- return s.code = "RATE_LIMIT_EXCEEDED", s.status = 429, s;
1195
- }
1196
- if (o === 401 || o === 403) {
1197
- const s = new Error(`Authentication failed: ${r}`);
1198
- return s.code = "AUTH_ERROR", s.status = o, s;
1199
- }
1200
- const t = new Error(r);
1201
- return t.code = "API_ERROR", t.status = o, t;
1202
- }
1203
- }
1204
- let ae = class {
1205
- constructor(o) {
1206
- this.requests = [], this.config = o;
1207
- }
1208
- checkLimit() {
1209
- const o = Date.now(), a = o - this.config.windowMs;
1210
- return this.requests = this.requests.filter((r) => r > a), this.requests.length >= this.config.maxRequests ? !1 : (this.requests.push(o), !0);
1211
- }
1212
- getRemainingRequests() {
1213
- const a = Date.now() - this.config.windowMs;
1214
- return this.requests = this.requests.filter((r) => r > a), Math.max(0, this.config.maxRequests - this.requests.length);
1215
- }
1216
- getResetTime() {
1217
- return this.requests.length === 0 ? 0 : this.requests[0] + this.config.windowMs;
1218
- }
1219
- };
1220
- class I {
1221
- constructor() {
1222
- this.rateLimiter = new ae({
1223
- maxRequests: 10,
1224
- windowMs: 6e4
1225
- }), this.adapters = /* @__PURE__ */ new Map([
1226
- ["google-gemini", new Q()],
1227
- ["ollama", new Z()],
1228
- ["anthropic", new ee()],
1229
- ["openai", new te()],
1230
- ["grok", new re()],
1231
- ["deepseek", new oe()]
1232
- ]);
1233
- }
1234
- static getInstance() {
1235
- return I.instance || (I.instance = new I()), I.instance;
1236
- }
1237
- /**
1238
- * Generate text with rate limiting and error handling
1239
- */
1240
- async generateText(o, a) {
1241
- if (!this.rateLimiter.checkLimit()) {
1242
- const t = this.rateLimiter.getResetTime(), n = new Error("Rate limit exceeded. Please wait before making another request.");
1243
- throw n.code = "RATE_LIMIT_EXCEEDED", n.resetTime = t, n;
1244
- }
1245
- const r = this.adapters.get(a.provider);
1246
- if (!r)
1247
- throw new Error(`Provider ${a.provider} not supported yet.`);
1248
- try {
1249
- return await r.generateText(o, a);
1250
- } catch (t) {
1251
- throw console.error("[AiGateway] Error:", t), t;
1252
- }
1253
- }
1254
- /**
1255
- * Stream text generation
1256
- */
1257
- async *streamText(o, a) {
1258
- if (!this.rateLimiter.checkLimit()) {
1259
- const t = new Error("Rate limit exceeded");
1260
- throw t.code = "RATE_LIMIT_EXCEEDED", t;
1261
- }
1262
- const r = this.adapters.get(a.provider);
1263
- if (!r)
1264
- throw new Error(`Provider ${a.provider} not supported yet.`);
1265
- yield* r.streamText(o, a);
1266
- }
1267
- /**
1268
- * Generate structured object (JSON mode)
1269
- */
1270
- async generateObject(o, a, r) {
1271
- if (!this.rateLimiter.checkLimit()) {
1272
- const n = new Error("Rate limit exceeded");
1273
- throw n.code = "RATE_LIMIT_EXCEEDED", n;
1274
- }
1275
- const t = this.adapters.get(r.provider);
1276
- if (!t)
1277
- throw new Error(`Provider ${r.provider} not supported yet.`);
1278
- return t.generateObject(o, a, r);
1279
- }
1280
- /**
1281
- * Get remaining requests before rate limit
1282
- */
1283
- getRemainingRequests() {
1284
- return this.rateLimiter.getRemainingRequests();
1285
- }
1286
- /**
1287
- * List available models for a provider
1288
- */
1289
- async listModels(o, a, r) {
1290
- const t = this.adapters.get(o);
1291
- if (!t)
1292
- throw new Error(`Provider ${o} not supported yet.`);
1293
- return t.listModels(a, r);
1294
- }
1295
- }
1296
- const he = I.getInstance(), k = {};
1297
- class ge {
1298
- /**
1299
- * Resolve configuration with 3-tier priority:
1300
- * 1. User's localStorage override (highest priority)
1301
- * 2. App-level .env defaults
1302
- * 3. System defaults (fallback)
1303
- */
1304
- static resolve(o, a) {
1305
- const r = (o == null ? void 0 : o.provider) || (a == null ? void 0 : a.provider) || "ollama", t = (o == null ? void 0 : o.model) || (a == null ? void 0 : a.model) || this.getDefaultModel(r), n = (o == null ? void 0 : o.apiKey) || (a == null ? void 0 : a.apiKey), s = (o == null ? void 0 : o.ollamaUrl) || (a == null ? void 0 : a.ollamaUrl) || "http://localhost:11434";
1306
- if (r !== "ollama" && !n)
1307
- throw new Error(`API key required for provider: ${r}`);
1308
- return {
1309
- provider: r,
1310
- model: t,
1311
- apiKey: n,
1312
- baseUrl: r === "ollama" ? s : void 0
1313
- };
1314
- }
1315
- static getDefaultModel(o) {
1316
- return {
1317
- "google-gemini": "gemini-2.5-flash",
1318
- openai: "gpt-4o-mini",
1319
- anthropic: "claude-sonnet-4-5-20250929",
1320
- grok: "grok-2-1212",
1321
- deepseek: "deepseek-chat",
1322
- ollama: "llama3.2"
1323
- }[o];
1324
- }
1325
- /**
1326
- * Load user preferences from localStorage (client-side)
1327
- */
1328
- static loadUserConfig() {
1329
- if (!(typeof window > "u"))
1330
- return {
1331
- provider: localStorage.getItem("app_ai_provider"),
1332
- model: localStorage.getItem("app_ai_model") || void 0,
1333
- apiKey: localStorage.getItem("app_ai_api_key") || void 0,
1334
- ollamaUrl: localStorage.getItem("app_ollama_url") || void 0
1335
- };
1336
- }
1337
- /**
1338
- * Returns the env key for a specific provider — for REQUEST FLOW ONLY.
1339
- * Never call this from UI components; use hasEnvKey() for status badges.
1340
- */
1341
- static getEnvKeyForProvider(o) {
1342
- var r, t, n, s, c;
1343
- if (typeof import.meta < "u" && k) {
1344
- const i = k, d = (l) => (l == null ? void 0 : l.trim()) || void 0;
1345
- return {
1346
- "google-gemini": d(i == null ? void 0 : i.VITE_DEFAULT_GEMINI_KEY),
1347
- openai: d(i == null ? void 0 : i.VITE_DEFAULT_OPENAI_KEY),
1348
- anthropic: d(i == null ? void 0 : i.VITE_DEFAULT_ANTHROPIC_KEY),
1349
- grok: d(i == null ? void 0 : i.VITE_DEFAULT_GROK_KEY),
1350
- deepseek: d(i == null ? void 0 : i.VITE_DEFAULT_DEEPSEEK_KEY)
1351
- }[o];
1352
- }
1353
- if (typeof process < "u" && process.env)
1354
- return {
1355
- "google-gemini": (r = process.env.VITE_DEFAULT_GEMINI_KEY) == null ? void 0 : r.trim(),
1356
- openai: (t = process.env.VITE_DEFAULT_OPENAI_KEY) == null ? void 0 : t.trim(),
1357
- anthropic: (n = process.env.VITE_DEFAULT_ANTHROPIC_KEY) == null ? void 0 : n.trim(),
1358
- grok: (s = process.env.VITE_DEFAULT_GROK_KEY) == null ? void 0 : s.trim(),
1359
- deepseek: (c = process.env.VITE_DEFAULT_DEEPSEEK_KEY) == null ? void 0 : c.trim()
1360
- }[o];
1361
- }
1362
- /**
1363
- * Returns true if an env key exists for the given provider — boolean only,
1364
- * value never exposed. Safe to call from UI components for status badges.
1365
- */
1366
- static hasEnvKey(o) {
1367
- if (typeof import.meta < "u" && k) {
1368
- const r = k, t = (s) => (s == null ? void 0 : s.trim()) || void 0;
1369
- return !!{
1370
- "google-gemini": t(r == null ? void 0 : r.VITE_DEFAULT_GEMINI_KEY),
1371
- openai: t(r == null ? void 0 : r.VITE_DEFAULT_OPENAI_KEY),
1372
- anthropic: t(r == null ? void 0 : r.VITE_DEFAULT_ANTHROPIC_KEY),
1373
- grok: t(r == null ? void 0 : r.VITE_DEFAULT_GROK_KEY),
1374
- deepseek: t(r == null ? void 0 : r.VITE_DEFAULT_DEEPSEEK_KEY)
1375
- }[o];
1376
- }
1377
- return typeof process < "u" && process.env ? !!{
1378
- "google-gemini": process.env.VITE_DEFAULT_GEMINI_KEY || process.env.NEXT_PUBLIC_GEMINI_KEY,
1379
- openai: process.env.VITE_DEFAULT_OPENAI_KEY || process.env.NEXT_PUBLIC_OPENAI_KEY,
1380
- anthropic: process.env.VITE_DEFAULT_ANTHROPIC_KEY || process.env.NEXT_PUBLIC_ANTHROPIC_KEY
1381
- }[o] : !1;
1382
- }
1383
- /**
1384
- * Load app defaults from environment variables
1385
- * Note: This works differently in Vite vs Next.js
1386
- */
1387
- static loadAppDefaults() {
1388
- var a, r;
1389
- if (typeof import.meta < "u" && k) {
1390
- const t = k, n = (t == null ? void 0 : t.VITE_DEFAULT_AI_PROVIDER) || "", s = (l) => (l == null ? void 0 : l.trim()) || void 0, c = {
1391
- "google-gemini": s(t == null ? void 0 : t.VITE_DEFAULT_GEMINI_KEY),
1392
- openai: s(t == null ? void 0 : t.VITE_DEFAULT_OPENAI_KEY),
1393
- anthropic: s(t == null ? void 0 : t.VITE_DEFAULT_ANTHROPIC_KEY),
1394
- grok: s(t == null ? void 0 : t.VITE_DEFAULT_GROK_KEY),
1395
- deepseek: s(t == null ? void 0 : t.VITE_DEFAULT_DEEPSEEK_KEY)
1396
- };
1397
- let i = n || "ollama";
1398
- const p = ["google-gemini", "anthropic", "openai", "grok", "deepseek"].filter((l) => !!c[l]);
1399
- return i === "ollama" && p.length > 0 && (i = p[0]), {
1400
- provider: i,
1401
- model: t == null ? void 0 : t.VITE_DEFAULT_AI_MODEL,
1402
- apiKey: c[i],
1403
- ollamaUrl: t == null ? void 0 : t.VITE_DEFAULT_OLLAMA_URL
1404
- };
1405
- }
1406
- return typeof process < "u" && process.env ? {
1407
- provider: (a = process.env) == null ? void 0 : a.NEXT_PUBLIC_DEFAULT_AI_PROVIDER,
1408
- model: (r = process.env) == null ? void 0 : r.NEXT_PUBLIC_DEFAULT_AI_MODEL
1409
- } : {};
1410
- }
1411
- }
1412
- class se {
1413
- constructor(o) {
1414
- this.requests = [], this.config = o;
1415
- }
1416
- checkLimit() {
1417
- const o = Date.now(), a = o - this.config.windowMs;
1418
- return this.requests = this.requests.filter((r) => r > a), this.requests.length >= this.config.maxRequests ? !1 : (this.requests.push(o), !0);
1419
- }
1420
- getRemainingRequests() {
1421
- const a = Date.now() - this.config.windowMs;
1422
- return this.requests = this.requests.filter((r) => r > a), Math.max(0, this.config.maxRequests - this.requests.length);
1423
- }
1424
- getResetTime() {
1425
- return this.requests.length === 0 ? 0 : this.requests[0] + this.config.windowMs;
1426
- }
1427
- }
1428
- class ne {
1429
- constructor(o = { maxRequests: 10, windowMs: 6e4 }) {
1430
- this.rateLimiter = new se(o);
1431
- }
1432
- async makeRequest(o, a) {
1433
- if (!this.rateLimiter.checkLimit()) {
1434
- const r = this.rateLimiter.getResetTime(), t = new Error("Rate limit exceeded. Please wait before making another request.");
1435
- throw t.code = "RATE_LIMIT_EXCEEDED", t.resetTime = r, a && a(r), t;
1436
- }
1437
- return await o();
1438
- }
1439
- getRemainingRequests() {
1440
- return this.rateLimiter.getRemainingRequests();
1441
- }
1442
- }
1443
- const we = new ne({ maxRequests: 10, windowMs: 6e4 });
1444
- export {
1445
- ge as A,
1446
- U as B,
1447
- z as D,
1448
- j as E,
1449
- de as F,
1450
- Q as G,
1451
- ae as I,
1452
- Z as O,
1453
- M as P,
1454
- N as R,
1455
- F as S,
1456
- D as T,
1457
- L as W,
1458
- me as a,
1459
- he as b,
1460
- I as c,
1461
- ne as d,
1462
- we as e,
1463
- ce as f,
1464
- ee as g,
1465
- te as h,
1466
- re as i,
1467
- oe as j,
1468
- P as k,
1469
- q as l,
1470
- K as m,
1471
- le as n,
1472
- pe as o,
1473
- S as p
1474
- };