@ramme-io/kernel 6.0.0 → 6.0.1

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