@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
@@ -0,0 +1,3619 @@
1
+ import { z as e } from "zod";
2
+ const Ir = {
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-accent-1",
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-accent-3",
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-accent-2",
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-accent-4",
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 xe = Object.defineProperty, ve = (a, t) => {
118
+ for (var n in t)
119
+ xe(a, n, { get: t[n], enumerable: !0 });
120
+ }, ke = e.object({
121
+ key: e.string(),
122
+ label: e.string(),
123
+ type: e.enum(["text", "number", "currency", "percent", "delta", "date", "boolean", "status", "email", "image", "textarea"]),
124
+ required: e.boolean().optional(),
125
+ description: e.string().optional(),
126
+ defaultValue: e.any().optional()
127
+ }), Se = e.object({
128
+ id: e.string(),
129
+ name: e.string(),
130
+ fields: e.array(ke),
131
+ defaultView: e.enum(["table", "grid", "list"]).optional(),
132
+ features: e.object({
133
+ searchable: e.boolean().optional(),
134
+ creatable: e.boolean().optional(),
135
+ editable: e.boolean().optional(),
136
+ deletable: e.boolean().optional(),
137
+ exportable: e.boolean().optional()
138
+ }).optional()
139
+ }), _e = e.object({
140
+ id: e.string().min(1, "Signal ID is required"),
141
+ label: e.string(),
142
+ description: e.string().optional(),
143
+ kind: e.enum(["sensor", "actuator", "setpoint", "metric", "status", "kpi"]),
144
+ source: e.enum(["mock", "mqtt", "http", "derived", "local"]),
145
+ // Connectivity
146
+ topic: e.string().optional(),
147
+ endpoint: e.string().optional(),
148
+ jsonPath: e.string().optional(),
149
+ refreshRate: e.number().optional().default(1e3),
150
+ // Values
151
+ defaultValue: e.any().optional(),
152
+ unit: e.string().optional(),
153
+ min: e.number().optional(),
154
+ max: e.number().optional()
155
+ }), Te = e.object({
156
+ id: e.string(),
157
+ name: e.string(),
158
+ description: e.string().optional(),
159
+ type: e.string(),
160
+ category: e.string().default("logical"),
161
+ signals: e.array(e.string()),
162
+ ui: e.object({
163
+ icon: e.string().optional(),
164
+ color: e.string().optional(),
165
+ dashboardComponent: e.string().optional()
166
+ }).optional()
167
+ }), Ie = e.object({
168
+ id: e.string(),
169
+ type: e.enum(["signal_change", "manual_action", "schedule", "webhook"]),
170
+ config: e.record(e.string(), e.any())
171
+ }), Oe = e.object({
172
+ id: e.string(),
173
+ type: e.enum([
174
+ "update_resource",
175
+ "send_notification",
176
+ "mqtt_publish",
177
+ "api_call",
178
+ "navigate",
179
+ "agent_task"
180
+ ]),
181
+ config: e.record(e.string(), e.any())
182
+ }), Pe = e.object({
183
+ id: e.string(),
184
+ name: e.string(),
185
+ active: e.boolean().default(!0),
186
+ trigger: Ie,
187
+ actions: e.array(Oe)
188
+ }), je = e.object({
189
+ id: e.string(),
190
+ type: e.string(),
191
+ props: e.record(e.string(), e.any()),
192
+ layout: e.object({
193
+ colSpan: e.number().optional(),
194
+ rowSpan: e.number().optional()
195
+ }).optional()
196
+ }), Re = e.object({
197
+ id: e.string(),
198
+ title: e.string().optional(),
199
+ description: e.string().optional(),
200
+ layout: e.object({
201
+ columns: e.number().optional(),
202
+ variant: e.enum(["grid", "stack", "split"]).optional()
203
+ }).optional(),
204
+ blocks: e.array(je)
205
+ }), Ne = e.object({
206
+ id: e.string(),
207
+ slug: e.string(),
208
+ title: e.string(),
209
+ description: e.string().optional(),
210
+ icon: e.string().optional(),
211
+ sections: e.array(Re)
212
+ }), De = e.enum(["ENVIRONMENT", "SESSION_BYOK", "VAULT"]), Ce = e.object({
213
+ strategy: De,
214
+ status: e.enum(["VALID", "KEY_EXPIRED", "BYOK_REQUIRED", "DEGRADED", "UNKNOWN"]).default("UNKNOWN")
215
+ }), Or = e.object({
216
+ meta: e.object({
217
+ name: e.string(),
218
+ version: e.string(),
219
+ description: e.string().optional(),
220
+ author: e.string().optional(),
221
+ createdAt: e.string().optional()
222
+ }),
223
+ config: e.object({
224
+ theme: e.enum(["light", "dark", "system", "corporate", "midnight", "blueprint"]).default("system"),
225
+ layout: e.enum(["dashboard", "explorer", "studio", "focus"]).default("dashboard"),
226
+ mockMode: e.boolean().default(!0),
227
+ brokerUrl: e.string().optional(),
228
+ aiKeyManifest: Ce.optional()
229
+ }),
230
+ modules: e.array(e.string()).optional(),
231
+ resources: e.array(Se).optional(),
232
+ domain: e.object({
233
+ signals: e.array(_e),
234
+ entities: e.array(Te),
235
+ workflows: e.array(Pe).optional()
236
+ }),
237
+ pages: e.array(Ne).optional()
238
+ }), Pr = e.object({
239
+ timestamp: e.number(),
240
+ soilMoisture: e.number().min(0).max(100),
241
+ ambientLight: e.number().min(0).max(1e5),
242
+ temperature: e.number().min(-40).max(125)
243
+ }), $e = e.object({
244
+ id: e.string(),
245
+ source: e.enum(["mqtt", "http", "ws", "mock"]),
246
+ domain: e.string(),
247
+ key: e.string(),
248
+ value: e.union([e.number(), e.string(), e.boolean()]),
249
+ unit: e.string().optional(),
250
+ timestamp: e.number(),
251
+ meta: e.record(e.unknown()).optional()
252
+ });
253
+ e.array($e);
254
+ var Me = e.enum(["telemetry", "market", "system", "logic"]), Le = e.enum(["mqtt", "http", "ws", "mock"]);
255
+ e.object({
256
+ /**
257
+ * Globally unique signal identifier.
258
+ * Convention: '<device-or-entity-id>:<key>'
259
+ * Examples: 'sensor-01:soil_vwc', 'AAPL:price', 'server-01:cpu_pct'
260
+ */
261
+ id: e.string(),
262
+ /**
263
+ * The semantic category of this signal.
264
+ * Determines which Methodology Engine processes it.
265
+ */
266
+ kind: Me,
267
+ /**
268
+ * The specific measurement or metric key within its kind.
269
+ * RULE: Keys MUST be abstract and domain-agnostic where possible.
270
+ * Use 'price' not 'stock_price'. Use 'moisture' not 'soil_vwc'.
271
+ * Hardware-specific keys (soil_vwc) MUST be mapped to abstract keys
272
+ * at the adapter layer BEFORE the SignalPacket is created.
273
+ */
274
+ key: e.string(),
275
+ /**
276
+ * The scalar value. Accepts number, string, or boolean.
277
+ * Structured data MUST be flattened into multiple SignalPackets,
278
+ * one per measurable dimension.
279
+ */
280
+ value: e.union([e.number(), e.string(), e.boolean()]),
281
+ /**
282
+ * Optional unit of measurement.
283
+ * Examples: 'VWC%', 'USD', 'bpm', 'ms', '°C', 'pct'
284
+ */
285
+ unit: e.string().optional(),
286
+ /**
287
+ * Unix timestamp in milliseconds (Date.now() format).
288
+ * MUST represent when the measurement was taken, not when it was received.
289
+ */
290
+ ts: e.number(),
291
+ /**
292
+ * The transport source that produced this signal.
293
+ */
294
+ source: Le.optional(),
295
+ /**
296
+ * Optional domain namespace for grouping related signals.
297
+ * Examples: 'bodewell', 'finance', 'infrastructure', 'user_behavior'
298
+ */
299
+ domain: e.string().optional(),
300
+ /**
301
+ * Optional pass-through for source-specific metadata that does NOT
302
+ * belong in the core contract (e.g. device firmware version, exchange name).
303
+ * RULE: If you find yourself reading from meta in UI components, that
304
+ * field should be promoted to the core schema or handled in the adapter.
305
+ */
306
+ meta: e.record(e.unknown()).optional()
307
+ });
308
+ var Ue = {};
309
+ ve(Ue, {
310
+ BodewellCommandSchema: () => qe,
311
+ BodewellDeviceID: () => Q,
312
+ BodewellTelemetrySchema: () => Be
313
+ });
314
+ var Q = e.enum([
315
+ "STK-V1-001",
316
+ "STK-V1-002",
317
+ "STK-V1-003",
318
+ "STK-PRO-001",
319
+ "STK-VIS-001"
320
+ ]), Be = e.object({
321
+ device_id: Q,
322
+ stick_id: e.string().optional().describe("Firmware alias for device_id"),
323
+ timestamp: e.number().optional().describe("Epoch timestamp from NTP"),
324
+ air_temp: e.number().optional().describe("Celsius"),
325
+ air_humid: e.number().optional().describe("Relative Humidity %"),
326
+ humidity: e.number().optional().describe("Firmware alias for air_humid"),
327
+ air_pressure: e.number().optional().describe("hPa"),
328
+ pressure: e.number().optional().describe("Firmware alias for air_pressure"),
329
+ light_lux: e.number().optional().describe("Lux level"),
330
+ soil_temp_stemma: e.number().optional().describe("Celsius"),
331
+ soil_vwc: e.number().describe("Volumetric Water Content / Raw Capacitance"),
332
+ soil_moisture: e.number().optional().describe("Firmware alias for raw capacitance"),
333
+ soil_moisture_raw: e.number().optional().describe("Unscaled capacitance (300-1100)")
334
+ }).passthrough(), qe = e.object({
335
+ stick_id: Q,
336
+ // Note: Your API uses stick_id here, not device_id
337
+ type: e.enum(["dry", "wet"]),
338
+ value: e.number()
339
+ }), Ze = e.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
+ ]), me = e.enum([
347
+ "weather",
348
+ "clock",
349
+ "aircraft",
350
+ "sensor",
351
+ "blank"
352
+ ]), Fe = e.object({
353
+ /** Postal code is what a person knows; the portal resolves it to coordinates. */
354
+ postalCode: e.string().min(3).max(12),
355
+ latitude: e.number().min(-90).max(90).optional(),
356
+ longitude: e.number().min(-180).max(180).optional(),
357
+ units: e.enum(["imperial", "metric"]).default("imperial"),
358
+ showForecast: e.boolean().default(!0),
359
+ refreshSeconds: e.number().int().min(300).max(86400).default(900)
360
+ }), ze = e.object({
361
+ /** IANA zone, e.g. "America/New_York". */
362
+ timezone: e.string().default("America/New_York"),
363
+ twentyFourHour: e.boolean().default(!1),
364
+ showSeconds: e.boolean().default(!1),
365
+ showDate: e.boolean().default(!0)
366
+ }), Ve = e.object({
367
+ latitude: e.number().min(-90).max(90),
368
+ longitude: e.number().min(-180).max(180),
369
+ radiusKm: e.number().min(5).max(400).default(80),
370
+ /** Rows the list view can show before the screen runs out. */
371
+ maxRows: e.number().int().min(1).max(12).default(8),
372
+ refreshSeconds: e.number().int().min(10).max(600).default(30)
373
+ }), Je = e.object({
374
+ /** Signal keys to display, in order. Abstract keys per the Signal contract. */
375
+ keys: e.array(e.string()).min(1).max(6),
376
+ refreshSeconds: e.number().int().min(1).max(3600).default(10)
377
+ }), Ke = e.object({
378
+ weather: Fe.optional(),
379
+ clock: ze.optional(),
380
+ aircraft: Ve.optional(),
381
+ sensor: Je.optional()
382
+ }), Ye = e.object({
383
+ brightness: e.number().int().min(5).max(100).default(80),
384
+ /** Degrees clockwise. The board can sit either way up in a case. */
385
+ rotation: e.union([e.literal(0), e.literal(90), e.literal(180), e.literal(270)]).default(0),
386
+ /** Dim rather than sleep — a desk display that blanks looks broken. */
387
+ dimAfterSeconds: e.number().int().min(0).max(86400).default(0),
388
+ dimBrightness: e.number().int().min(0).max(100).default(15),
389
+ /** Local 24h times, e.g. "22:30". Empty disables night dimming. */
390
+ nightStart: e.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/).optional(),
391
+ nightEnd: e.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/).optional()
392
+ }), q = e.string().regex(
393
+ /^\d{1,3} \d{1,3} \d{1,3}$/,
394
+ 'Expected space-separated RGB integers, e.g. "13 110 253"'
395
+ ), Ge = e.object({
396
+ preset: e.enum(["light", "dark", "corporate", "midnight", "blueprint", "custom"]).default("dark"),
397
+ background: q.optional(),
398
+ foreground: q.optional(),
399
+ accent: q.optional(),
400
+ muted: q.optional(),
401
+ warning: q.optional()
402
+ });
403
+ e.object({
404
+ /** Bumped only on breaking shape changes, so old firmware can refuse safely. */
405
+ schemaVersion: e.literal(1),
406
+ deviceId: e.string().min(1),
407
+ /** Monotonic. Portal increments on write; device echoes what it is running. */
408
+ revision: e.number().int().nonnegative(),
409
+ updatedAt: e.string().datetime().optional(),
410
+ activeApp: me,
411
+ apps: Ke,
412
+ display: Ye,
413
+ theme: Ge
414
+ });
415
+ var He = e.enum([
416
+ "unprovisioned",
417
+ "connecting",
418
+ "online",
419
+ "offline",
420
+ "failed"
421
+ ]);
422
+ e.object({
423
+ deviceId: e.string().min(1),
424
+ kind: Ze,
425
+ firmwareVersion: e.string(),
426
+ /** Shown on the device's own screen at boot — how the user finds it. */
427
+ ipAddress: e.string().optional(),
428
+ provisioning: He,
429
+ /** Revision the device is actually running, not the one it was sent. */
430
+ configRevision: e.number().int().nonnegative(),
431
+ activeApp: me,
432
+ rssi: e.number().int().optional().describe("dBm"),
433
+ uptimeSeconds: e.number().int().nonnegative().optional(),
434
+ freeHeapBytes: e.number().int().nonnegative().optional()
435
+ });
436
+ var We = e.enum([
437
+ "background",
438
+ "foreground",
439
+ "muted",
440
+ "accent",
441
+ "success",
442
+ "warning",
443
+ "danger"
444
+ ]), Xe = e.string().regex(/^\d{1,3} \d{1,3} \d{1,3}$/, 'RGB must be three space-separated integers, e.g. "13 110 253"'), J = e.union([We, Xe]), de = e.enum(["xs", "sm", "base", "lg", "xl", "display"]), ee = e.enum(["start", "center", "end"]), Qe = e.discriminatedUnion("kind", [
445
+ e.object({
446
+ kind: e.literal("weather"),
447
+ latitude: e.number().min(-90).max(90),
448
+ longitude: e.number().min(-180).max(180),
449
+ units: e.enum(["imperial", "metric"]).default("imperial"),
450
+ refreshSeconds: e.number().int().min(300).max(86400).default(600)
451
+ }),
452
+ e.object({
453
+ kind: e.literal("clock"),
454
+ /** IANA zone, e.g. "America/New_York". */
455
+ timezone: e.string().default("America/New_York"),
456
+ twentyFourHour: e.boolean().default(!1)
457
+ }),
458
+ e.object({
459
+ kind: e.literal("countdown"),
460
+ /** ISO date or datetime, e.g. "2026-12-25" or "2026-12-25T18:00:00Z". */
461
+ target: e.string().min(4),
462
+ label: e.string().max(24).optional()
463
+ }),
464
+ e.object({
465
+ kind: e.literal("static"),
466
+ values: e.record(e.union([e.string(), e.number(), e.boolean()]))
467
+ })
468
+ ]), X = e.union([
469
+ e.object({ literal: e.number() }),
470
+ e.object({ source: e.string().min(1), field: e.string().min(1) })
471
+ ]), et = e.object({
472
+ compute: e.enum(["add", "subtract", "multiply", "divide"]),
473
+ of: e.tuple([X, X]),
474
+ round: e.boolean().default(!0)
475
+ }), Z = e.union([
476
+ e.object({ literal: e.union([e.string(), e.number(), e.boolean()]) }),
477
+ e.object({
478
+ /** Key into the document's `sources` map. */
479
+ source: e.string().min(1),
480
+ /** Field on that source, e.g. "temperature", "high", "condition". */
481
+ field: e.string().min(1)
482
+ }),
483
+ et
484
+ ]), te = e.object({
485
+ value: X,
486
+ op: e.enum(["<", "<=", ">", ">=", "==", "!="]),
487
+ than: e.union([e.number(), e.string(), e.boolean()])
488
+ }), tt = e.object({
489
+ when: te,
490
+ color: J.optional(),
491
+ size: de.optional()
492
+ }), F = {
493
+ color: J.optional(),
494
+ /** Drawn only when this is false, or absent. */
495
+ hideWhen: te.optional(),
496
+ /** Conditional style. First match wins. */
497
+ rules: e.array(tt).max(4).optional()
498
+ }, rt = e.object({
499
+ type: e.literal("text"),
500
+ value: Z,
501
+ size: de.default("base"),
502
+ align: ee.default("start"),
503
+ /** Printed after the value, e.g. a degree symbol. Never itself bound. */
504
+ suffix: e.string().max(8).optional(),
505
+ ...F
506
+ }), nt = e.object({
507
+ type: e.literal("dial"),
508
+ value: Z,
509
+ min: e.number(),
510
+ max: e.number(),
511
+ label: e.string().max(24).optional(),
512
+ ...F
513
+ }), at = e.object({
514
+ type: e.literal("sparkline"),
515
+ /** A source field holding a series rather than a scalar. */
516
+ series: Z,
517
+ ...F
518
+ }), ot = e.object({
519
+ type: e.literal("bar"),
520
+ value: Z,
521
+ min: e.number(),
522
+ max: e.number(),
523
+ ...F
524
+ }), it = e.object({
525
+ type: e.literal("status"),
526
+ state: Z,
527
+ label: e.string().max(24).optional(),
528
+ ...F
529
+ }), $ = 64, st = $ / 2, ct = Math.ceil(st * $ / 3) * 4, lt = e.object({
530
+ type: e.literal("sprite"),
531
+ width: e.number().int().min(1).max($),
532
+ height: e.number().int().min(1).max($),
533
+ /**
534
+ * Up to sixteen colours, in the same form every other colour in a document
535
+ * takes: a semantic token, or literal RGB.
536
+ *
537
+ * Both are allowed on purpose. A token re-colours with the theme, which is
538
+ * what an icon wants; literal RGB does not, which is what a drawing wants.
539
+ * A picture of a dog is content, not chrome, and should not turn teal
540
+ * because somebody switched to the corporate theme.
541
+ */
542
+ palette: e.array(J).min(1).max(16),
543
+ /** base64 of the packed nibbles. */
544
+ pixels: e.string().min(4).max(ct),
545
+ align: ee.default("start"),
546
+ /** Drawn only when this is false, or absent. */
547
+ hideWhen: te.optional()
548
+ }), pe = e.discriminatedUnion("type", [
549
+ rt,
550
+ nt,
551
+ at,
552
+ ot,
553
+ it,
554
+ lt
555
+ ]), ut = e.object({
556
+ type: e.literal("group"),
557
+ direction: e.enum(["row", "stack"]),
558
+ gap: e.number().int().min(0).max(64).default(4),
559
+ align: ee.default("start"),
560
+ children: e.array(pe).min(1).max(8)
561
+ }), mt = e.union([pe, ut]), dt = e.enum(["240x320"]), jr = e.object({
562
+ /** Bumped only for a breaking change; the device checks it before parsing. */
563
+ schemaVersion: e.literal(1),
564
+ id: e.string().regex(/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/, "lowercase slug"),
565
+ name: e.string().min(1).max(48),
566
+ /** Free text. Never an email or anything else identifying — see the plan. */
567
+ author: e.string().max(32).optional(),
568
+ screen: dt.default("240x320"),
569
+ background: J.default("background"),
570
+ /** Named so bindings can refer to them. */
571
+ sources: e.record(Qe).default({}),
572
+ blocks: e.array(mt).min(1).max(12)
573
+ }).superRefine((a, t) => {
574
+ const n = (o) => Math.ceil(o / 2), r = (o, s) => {
575
+ const i = o;
576
+ if ((i == null ? void 0 : i.type) !== "sprite" || !i.width || !i.height || typeof i.pixels != "string") return;
577
+ const l = n(i.width) * i.height, c = Math.floor(i.pixels.replace(/=+$/, "").length * 3 / 4);
578
+ c !== l && t.addIssue({
579
+ code: e.ZodIssueCode.custom,
580
+ path: [...s, "pixels"],
581
+ message: `${i.width}x${i.height} needs ${l} bytes of pixel data, and this decodes to ${c}. Rows are padded to whole bytes, so the length is ceil(width / 2) * height.`
582
+ });
583
+ };
584
+ a.blocks.forEach((o, s) => {
585
+ r(o, ["blocks", s]);
586
+ const i = o.children;
587
+ Array.isArray(i) && i.forEach((l, c) => r(l, ["blocks", s, "children", c]));
588
+ });
589
+ }), K = e.string().regex(/^[0-9A-HJKMNP-TV-Z]{8}$/, "eight characters, no I L O or U"), re = e.string().regex(/^\d{4}$/);
590
+ e.object({
591
+ deviceId: K,
592
+ code: re,
593
+ /** Firmware build, so a support question has an answer. */
594
+ version: e.string().max(40).optional()
595
+ });
596
+ e.object({
597
+ deviceId: K,
598
+ code: re
599
+ });
600
+ e.object({
601
+ deviceId: K
602
+ });
603
+ e.object({
604
+ revision: e.number().int().nonnegative(),
605
+ sentAt: e.number().int().nonnegative()
606
+ });
607
+ e.object({
608
+ deviceId: K,
609
+ code: re,
610
+ ownerId: e.string().nullable().default(null),
611
+ version: e.string().max(40).optional(),
612
+ createdAt: e.number().int().nonnegative(),
613
+ lastSeenAt: e.number().int().nonnegative()
614
+ });
615
+ e.enum(["register", "poll", "send"]);
616
+ e.object({
617
+ /** When the board last said any of this, by the server's clock. */
618
+ reportedAt: e.number().int().nonnegative().optional(),
619
+ /**
620
+ * The firmware build. Today every board sends the literal "doc-1", which is a
621
+ * protocol marker rather than a build id — so this is shown as reported and
622
+ * labelled as not yet a version. The real value lives in the published
623
+ * manifest until firmware carries it.
624
+ */
625
+ firmwareVersion: e.string().max(40).optional(),
626
+ /** Which board this is. Nothing distinguishes a CYD from a Freenove S3 yet. */
627
+ board: e.string().max(40).optional(),
628
+ /** dBm, negative. -50 is across the room, -85 is a complaint. */
629
+ rssi: e.number().int().min(-127).max(0).optional(),
630
+ /** The board's address on its own network, as the board sees it. */
631
+ ip: e.string().max(45).optional(),
632
+ uptimeSeconds: e.number().int().nonnegative().optional(),
633
+ freeHeapBytes: e.number().int().nonnegative().optional(),
634
+ /**
635
+ * The revision the board is actually showing.
636
+ *
637
+ * Distinct from the revision that was sent, and the difference is the whole
638
+ * value: a send that was never drawn looks identical to a successful one until
639
+ * these two numbers disagree.
640
+ */
641
+ drewRevision: e.number().int().nonnegative().optional(),
642
+ /** Why it last restarted, if it says. A board power-cycling in a loop is a fault. */
643
+ resetReason: e.string().max(40).optional(),
644
+ /** When it last polled — finer-grained than a registration, for liveness only. */
645
+ lastPollAt: e.number().int().nonnegative().optional()
646
+ });
647
+ var Rr = "?", Nr = {
648
+ // Accented Latin, CP437 0x80-0xA5 and 0xE1
649
+ Ç: { byte: 128, shows: "Ç" },
650
+ ü: { byte: 129, shows: "ü" },
651
+ é: { byte: 130, shows: "é" },
652
+ â: { byte: 131, shows: "â" },
653
+ ä: { byte: 132, shows: "ä" },
654
+ à: { byte: 133, shows: "à" },
655
+ å: { byte: 134, shows: "å" },
656
+ ç: { byte: 135, shows: "ç" },
657
+ ê: { byte: 136, shows: "ê" },
658
+ ë: { byte: 137, shows: "ë" },
659
+ è: { byte: 138, shows: "è" },
660
+ ï: { byte: 139, shows: "ï" },
661
+ î: { byte: 140, shows: "î" },
662
+ ì: { byte: 141, shows: "ì" },
663
+ Ä: { byte: 142, shows: "Ä" },
664
+ Å: { byte: 143, shows: "Å" },
665
+ É: { byte: 144, shows: "É" },
666
+ æ: { byte: 145, shows: "æ" },
667
+ Æ: { byte: 146, shows: "Æ" },
668
+ ô: { byte: 147, shows: "ô" },
669
+ ö: { byte: 148, shows: "ö" },
670
+ ò: { byte: 149, shows: "ò" },
671
+ û: { byte: 150, shows: "û" },
672
+ ù: { byte: 151, shows: "ù" },
673
+ ÿ: { byte: 152, shows: "ÿ" },
674
+ Ö: { byte: 153, shows: "Ö" },
675
+ Ü: { byte: 154, shows: "Ü" },
676
+ á: { byte: 160, shows: "á" },
677
+ í: { byte: 161, shows: "í" },
678
+ ó: { byte: 162, shows: "ó" },
679
+ ú: { byte: 163, shows: "ú" },
680
+ ñ: { byte: 164, shows: "ñ" },
681
+ Ñ: { byte: 165, shows: "Ñ" },
682
+ ß: { byte: 225, shows: "ß" },
683
+ // Symbols a readout uses
684
+ "¢": { byte: 155, shows: "¢" },
685
+ "£": { byte: 156, shows: "£" },
686
+ "¥": { byte: 157, shows: "¥" },
687
+ ƒ: { byte: 159, shows: "ƒ" },
688
+ ª: { byte: 166, shows: "ª" },
689
+ º: { byte: 167, shows: "º" },
690
+ "¿": { byte: 168, shows: "¿" },
691
+ "¬": { byte: 170, shows: "¬" },
692
+ "½": { byte: 171, shows: "½" },
693
+ "¼": { byte: 172, shows: "¼" },
694
+ "¡": { byte: 173, shows: "¡" },
695
+ "«": { byte: 174, shows: "«" },
696
+ "»": { byte: 175, shows: "»" },
697
+ π: { byte: 227, shows: "π" },
698
+ µ: { byte: 230, shows: "µ" },
699
+ Ω: { byte: 234, shows: "Ω" },
700
+ "∞": { byte: 236, shows: "∞" },
701
+ "±": { byte: 241, shows: "±" },
702
+ "≥": { byte: 242, shows: "≥" },
703
+ "≤": { byte: 243, shows: "≤" },
704
+ "÷": { byte: 246, shows: "÷" },
705
+ "≈": { byte: 247, shows: "≈" },
706
+ "°": { byte: 248, shows: "°" },
707
+ "·": { byte: 250, shows: "·" },
708
+ "√": { byte: 251, shows: "√" },
709
+ "²": { byte: 253, shows: "²" },
710
+ // Punctuation an AI writes without being asked, folded to ASCII
711
+ "‘": { byte: 39, shows: "'" },
712
+ "’": { byte: 39, shows: "'" },
713
+ "“": { byte: 34, shows: '"' },
714
+ "”": { byte: 34, shows: '"' },
715
+ "–": { byte: 45, shows: "-" },
716
+ "—": { byte: 45, shows: "-" },
717
+ "−": { byte: 45, shows: "-" },
718
+ " ": { byte: 32, shows: " " }
719
+ }, Dr = {
720
+ background: "17 17 17",
721
+ foreground: "238 238 238",
722
+ muted: "153 153 153",
723
+ accent: "23 162 184",
724
+ success: "34 197 94",
725
+ warning: "245 158 11",
726
+ danger: "220 53 69"
727
+ };
728
+ e.object({
729
+ deviceId: e.string().min(1, "Device ID is required"),
730
+ timeRange: e.enum(["1h", "24h", "7d"], {
731
+ errorMap: () => ({ message: "Time range must be 1h, 24h, or 7d" })
732
+ }),
733
+ metrics: e.array(
734
+ e.enum(["temperature", "humidity", "vwc", "ec", "ph", "pressure", "co2"])
735
+ ).min(1, "At least one metric is required").max(4, "Maximum 4 metrics per graph")
736
+ });
737
+ e.object({
738
+ ticker: e.string().min(1).describe("The stock ticker symbol explicitly requested by the user. YOU MUST EXTRACT AND PROVIDE THIS (e.g., 'AAPL', 'MSFT')."),
739
+ timeRange: e.enum(["1D", "1W", "1M", "1Y"], {
740
+ errorMap: () => ({ message: "Time range must be 1D, 1W, 1M, or 1Y" })
741
+ }).describe("The time range for the chart. Choose based on user request or default to '1M'."),
742
+ metrics: e.array(e.enum(["price", "volume", "moving_average"])).min(1, "At least one metric is required").describe("Array of metrics to display. Always include 'price' and 'volume' unless user specifies otherwise.")
743
+ });
744
+ var z = e.string().min(1).describe("The stock ticker symbol (e.g., 'AAPL', 'TSLA', 'MSFT').");
745
+ e.object({ ticker: z });
746
+ e.object({ ticker: z });
747
+ e.object({ ticker: z });
748
+ e.object({
749
+ ticker: z,
750
+ hops: e.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.")
751
+ });
752
+ e.object({ ticker: z });
753
+ e.object({});
754
+ var G = "gemini-2.5-flash", pt = "gemini-2.5-flash", ht = "gemini-2.5-pro", T = {
755
+ "google-gemini": "gemini-2.5-flash",
756
+ openai: "gpt-4o-mini",
757
+ anthropic: "claude-haiku-4-5-20251001",
758
+ grok: "grok-2-1212",
759
+ deepseek: "deepseek-chat",
760
+ ollama: "llama3.3"
761
+ }, Cr = {
762
+ /** The Strategist: high creativity, exploratory conversation */
763
+ STRATEGIST: {
764
+ model: pt,
765
+ provider: "google-gemini",
766
+ temperature: 0.7
767
+ },
768
+ /** The Architect: data schema and resource modeling — precision required */
769
+ ARCHITECT: {
770
+ model: G,
771
+ provider: "google-gemini",
772
+ temperature: 0.3
773
+ },
774
+ /** The Designer: UI layout generation — moderate creativity */
775
+ DESIGNER: {
776
+ model: G,
777
+ provider: "google-gemini",
778
+ temperature: 0.5
779
+ },
780
+ /** The Reviewer/Product Owner: structured plan output — strict adherence.
781
+ * Uses the Pro tier for superior reasoning on complex structured tasks.
782
+ */
783
+ REVIEWER: {
784
+ model: ht,
785
+ provider: "google-gemini",
786
+ temperature: 0.2
787
+ },
788
+ /** The Genesis Engine: one-shot app generation — must be schema-strict */
789
+ GENESIS: {
790
+ model: G,
791
+ provider: "google-gemini",
792
+ temperature: 0.2
793
+ }
794
+ }, $r = `
795
+ You write tiny apps for a 240x320 pixel screen on a small desk device.
796
+
797
+ Reply with ONE JSON object and nothing else. No markdown fences, no explanation.
798
+
799
+ THE SHAPE
800
+
801
+ {
802
+ "schemaVersion": 1,
803
+ "id": "lowercase-slug",
804
+ "name": "Short Name",
805
+ "screen": "240x320",
806
+ "background": "background",
807
+ "sources": { },
808
+ "blocks": [ ]
809
+ }
810
+
811
+ BLOCKS — up to 12, drawn top to bottom. Each is one of:
812
+
813
+ { "type": "text", "value": V, "size": S, "align": A, "color": C, "suffix": "°" }
814
+ { "type": "dial", "value": V, "min": 0, "max": 100, "label": "CPU", "color": C }
815
+ { "type": "bar", "value": V, "min": 0, "max": 100, "color": C }
816
+ { "type": "sparkline", "series": V, "color": C }
817
+ { "type": "status", "state": V, "label": "Door", "color": C }
818
+ { "type": "sprite", "palette": [C, ...], "grid": "0011
819
+ 0110
820
+ 1100
821
+ 0011", "align": A }
822
+ { "type": "group", "direction": "row"|"stack", "gap": 8, "align": A, "children": [ ...leaves... ] }
823
+
824
+ DRAWING A SPRITE — you may, and here is the only form that works.
825
+
826
+ Write a "grid": one line per row, one hex character per pixel, each character
827
+ indexing "palette" (so "0" is the first colour, "1" the second, up to "f").
828
+ Every row must be exactly the same length. Up to 64x64, but 16x16 and 32x32
829
+ look far better — small palettes and bold shapes read on a 320x240 panel, fine
830
+ detail does not.
831
+
832
+ { "type": "sprite",
833
+ "palette": ["background", "255 214 10", "17 17 17"],
834
+ "grid": "0011110
835
+ 0122210
836
+ 1222221
837
+ 1211121
838
+ 1222221
839
+ 0122210
840
+ 0011110" }
841
+
842
+ Put the background colour FIRST so "0" means empty, and use "." as a synonym
843
+ for "0" if it makes the shape easier to see while you write it.
844
+
845
+ Palette entries are the same colours as everywhere else: a semantic token
846
+ re-colours with the theme, which is what an icon wants, and literal "R G B"
847
+ does not, which is what a picture wants.
848
+
849
+ NEVER write a "pixels" field yourself. That is base64 of packed nibbles, one
850
+ wrong character shifts every pixel after it, and you cannot check it. Write the
851
+ grid; it is converted for you. If a document you are editing already has
852
+ "pixels" and no "grid", leave it exactly as it is.
853
+
854
+ Count your rows before you answer. A grid whose rows are different lengths is
855
+ the one mistake that will come back to you.
856
+
857
+ A group holds leaves only. Groups do NOT nest inside groups — the device has no
858
+ layout engine, only computed offsets.
859
+
860
+ CONDITIONS — any block may also carry these:
861
+
862
+ "hideWhen": { "value": O, "op": "<", "than": 32 }
863
+ leave it off the screen entirely while that is true
864
+
865
+ "rules": [ { "when": { "value": O, "op": "<", "than": 32 }, "color": "accent" },
866
+ { "when": { "value": O, "op": ">", "than": 85 }, "color": "danger" } ]
867
+ style that applies only when something is true. First match wins, so write
868
+ the narrowest band first. At most four. Each may set "color", "size" or both.
869
+
870
+ op is one of "<" "<=" ">" ">=" "==" "!="
871
+ Only == and != work on words; the rest are for numbers.
872
+
873
+ O is an operand: { "literal": 32 } or { "source": "forecast", "field": "temperature" }
874
+
875
+ This is how "make it red when it is freezing" is expressed. Use it whenever a
876
+ request contains "when", "if", "unless", "only", or a colour tied to a value.
877
+
878
+ S (size) "xs" | "sm" | "base" | "lg" | "xl" | "display"
879
+ A (align) "start" | "center" | "end"
880
+ C (color) "background" | "foreground" | "muted" | "accent" | "success" | "warning" | "danger"
881
+ or three space-separated RGB numbers, e.g. "220 53 69"
882
+
883
+ VALUES — every V is one of:
884
+
885
+ { "literal": "Hello" } text you wrote
886
+ { "source": "forecast", "field": "temperature" } read from a source
887
+ { "compute": "subtract", "of": [O, O], "round": true } arithmetic
888
+
889
+ compute is "add" | "subtract" | "multiply" | "divide", exactly two operands,
890
+ and it does NOT nest — an operand is a literal or a source field, never
891
+ another compute. "The difference between the high and the low" is the shape
892
+ this is for.
893
+
894
+ SOURCES — declare what the app reads, then bind to it by name:
895
+
896
+ "forecast": { "kind": "weather", "latitude": 39.95, "longitude": -75.17,
897
+ "units": "imperial", "refreshSeconds": 600 }
898
+ fields: temperature, condition, high, low
899
+ "now": { "kind": "clock", "timezone": "America/New_York", "twentyFourHour": false }
900
+ fields: time, date, weekday, hour (hour is 0-23, for rules about time of day)
901
+ "until": { "kind": "countdown", "target": "2026-12-25", "label": "Christmas" }
902
+ fields: days, hours, minutes, seconds, label
903
+ "fixed": { "kind": "static", "values": { "anything": 1 } }
904
+ fields: whatever you put in values
905
+
906
+ RULES
907
+
908
+ 1. 240x320 is small. A "display" size text is about 56 pixels tall — one of
909
+ those and three or four smaller lines is a full screen. Prefer fewer, bigger
910
+ things over a dense dashboard.
911
+ 2. Use semantic colours unless asked for a specific one. They follow the theme.
912
+ 3. There is no scrolling and no text wrapping. Long strings are cut off.
913
+ 4. No tables, no forms, no images, no buttons. The screen shows; it does not
914
+ take input.
915
+ 5. If the request needs something the vocabulary cannot express, build the
916
+ closest thing it can and do not invent a component.
917
+ 6. Prefer a rule over a fixed colour whenever the request ties appearance to a
918
+ value. "Red when cold" is a rule; "red" is not.
919
+ `.trim(), Mr = "Here is the current app. Change only what is asked:", _ = e.string().regex(
920
+ /^\d{1,3}\s+\d{1,3}\s+\d{1,3}$/,
921
+ 'Must be space-separated RGB integers (e.g. "13 110 253")'
922
+ ), gt = e.object({
923
+ // ── Core Brand ───────────────────────────────────────────────────────────
924
+ "--app-primary-color": _.optional(),
925
+ "--app-primary-foreground-color": _.optional(),
926
+ "--app-secondary-color": _.optional(),
927
+ "--app-secondary-foreground-color": _.optional(),
928
+ "--app-accent-color": _.optional(),
929
+ "--app-accent-foreground-color": _.optional(),
930
+ // ── Base Surface ─────────────────────────────────────────────────────────
931
+ "--app-bg-color": _.optional(),
932
+ "--app-card-bg-color": _.optional(),
933
+ "--app-text-color": _.optional(),
934
+ "--app-border-color": _.optional(),
935
+ "--app-muted-bg": _.optional(),
936
+ "--app-muted-text": _.optional(),
937
+ // ── Shape ────────────────────────────────────────────────────────────────
938
+ "--app-border-radius-sm": e.string().optional(),
939
+ "--app-border-radius-md": e.string().optional(),
940
+ "--app-border-radius-lg": e.string().optional(),
941
+ // ── Form Controls ────────────────────────────────────────────────────────
942
+ "--app-input-bg-color": _.optional(),
943
+ "--app-input-text-color": _.optional(),
944
+ "--app-input-border-color": _.optional(),
945
+ "--app-input-focus-ring-color": _.optional(),
946
+ "--app-input-placeholder-color": _.optional(),
947
+ // ── Chart Palette ────────────────────────────────────────────────────────
948
+ "--app-chart-1": _.optional(),
949
+ "--app-chart-2": _.optional(),
950
+ "--app-chart-3": _.optional(),
951
+ "--app-chart-4": _.optional(),
952
+ "--app-chart-5": _.optional()
953
+ }).strict(), ft = e.object({
954
+ /** Google Font name for headings (h1–h4, .font-serif). Example: "Playfair Display" */
955
+ heading: e.string(),
956
+ /** Google Font name for body text. Example: "Inter" */
957
+ body: e.string(),
958
+ /** Optional monospace font. Example: "Roboto Mono" */
959
+ mono: e.string().optional()
960
+ });
961
+ e.object({
962
+ /** Short descriptive theme name. Example: "Midnight Garden" */
963
+ name: e.string(),
964
+ /** One-sentence vibe description. Example: "Dark indigo with golden accents." */
965
+ description: e.string(),
966
+ /** Google Font pairing for heading and body text. */
967
+ fonts: ft.optional(),
968
+ /**
969
+ * CSS variable overrides.
970
+ * Every key must match an --app-* variable name.
971
+ * All color values must be space-separated RGB integers.
972
+ */
973
+ cssVars: gt
974
+ });
975
+ e.object({
976
+ primary: _,
977
+ neutral: _,
978
+ success: _,
979
+ warning: _,
980
+ destructive: _,
981
+ radius: e.enum(["none", "sm", "md", "lg", "full"])
982
+ });
983
+ var Lr = {
984
+ primary: "13 110 253",
985
+ neutral: "24 24 27",
986
+ success: "34 197 94",
987
+ warning: "234 179 8",
988
+ destructive: "239 68 68",
989
+ radius: "md"
990
+ };
991
+ e.object({
992
+ id: e.string().default(""),
993
+ name: e.string(),
994
+ email: e.string().email(),
995
+ password: e.string().optional(),
996
+ role: e.string(),
997
+ status: e.string().optional(),
998
+ joinedAt: e.string().optional(),
999
+ lastActive: e.string().optional(),
1000
+ avatarUrl: e.string().optional()
1001
+ });
1002
+ var U = e.string().regex(/^acct_[0-9a-f]{12}$/, "acct_ and 12 hex digits"), ne = e.enum(["member", "admin"]), he = e.enum(["active", "suspended"]), yt = e.object({
1003
+ algo: e.literal("scrypt"),
1004
+ n: e.number().int().positive(),
1005
+ r: e.number().int().positive(),
1006
+ p: e.number().int().positive(),
1007
+ keylen: e.number().int().positive(),
1008
+ salt: e.string().min(16),
1009
+ hash: e.string().min(16)
1010
+ });
1011
+ e.object({
1012
+ accountId: U,
1013
+ /** Lowercased on write, because a login must not depend on how it was typed. */
1014
+ email: e.string().email().max(254),
1015
+ name: e.string().min(1).max(64),
1016
+ role: ne,
1017
+ status: he,
1018
+ password: yt,
1019
+ createdAt: e.number().int().nonnegative(),
1020
+ lastLoginAt: e.number().int().nonnegative().nullable().default(null),
1021
+ /** Which admin approved this, or null for the bootstrap account. */
1022
+ invitedBy: U.nullable().default(null)
1023
+ });
1024
+ e.object({
1025
+ accountId: U,
1026
+ email: e.string().email(),
1027
+ name: e.string(),
1028
+ role: ne,
1029
+ status: he
1030
+ });
1031
+ e.object({
1032
+ accountId: U,
1033
+ createdAt: e.number().int().nonnegative(),
1034
+ expiresAt: e.number().int().nonnegative(),
1035
+ lastSeenAt: e.number().int().nonnegative()
1036
+ });
1037
+ e.object({
1038
+ email: e.string().email().max(254),
1039
+ role: ne,
1040
+ createdAt: e.number().int().nonnegative(),
1041
+ expiresAt: e.number().int().nonnegative(),
1042
+ invitedBy: U
1043
+ });
1044
+ e.object({
1045
+ email: e.string().email().max(254),
1046
+ name: e.string().min(1).max(64),
1047
+ /** Optional, and never shown publicly. Long enough to be useful, short enough not to be an essay. */
1048
+ reason: e.string().max(500).optional()
1049
+ });
1050
+ var bt = e.enum(["pending", "approved", "denied"]);
1051
+ e.object({
1052
+ requestId: e.string().regex(/^req_[0-9a-f]{12}$/, "req_ and 12 hex digits"),
1053
+ email: e.string().email().max(254),
1054
+ name: e.string().min(1).max(64),
1055
+ reason: e.string().max(500).optional(),
1056
+ status: bt,
1057
+ createdAt: e.number().int().nonnegative(),
1058
+ decidedAt: e.number().int().nonnegative().nullable().default(null),
1059
+ decidedBy: U.nullable().default(null)
1060
+ });
1061
+ var wt = e.enum([
1062
+ "supplier",
1063
+ "customer",
1064
+ "partner",
1065
+ "competitor",
1066
+ "regulator",
1067
+ "unknown"
1068
+ ]), Et = e.enum([
1069
+ "public",
1070
+ "public_uncovered",
1071
+ "private",
1072
+ "unresolved"
1073
+ ]);
1074
+ e.object({
1075
+ id: e.string(),
1076
+ ticker: e.string().nullable(),
1077
+ /** Name as it appeared in the source signal — e.g. "Nike". Not the registered name. */
1078
+ name: e.string(),
1079
+ /** Registered legal name from `profiles` — e.g. "NIKE, Inc.". Null unless `public`. */
1080
+ publicName: e.string().nullable(),
1081
+ lei: e.string().nullable(),
1082
+ resolution: Et,
1083
+ type: wt,
1084
+ confidence: e.number().min(0).max(1),
1085
+ sourceSignalIds: e.array(e.number()),
1086
+ firstSeenAt: e.string().datetime(),
1087
+ lastSeenAt: e.string().datetime()
1088
+ });
1089
+ var At = e.enum([
1090
+ "supplies_to",
1091
+ "purchases_from",
1092
+ "partners_with",
1093
+ "competes_with",
1094
+ "regulated_by",
1095
+ "invests_in",
1096
+ "acquires",
1097
+ /**
1098
+ * Identity equivalence, not a business relationship: source and target are
1099
+ * the same real-world entity under two different node ids (typically a
1100
+ * slug-keyed node that predates LEI resolution, pointing at the canonical
1101
+ * LEI-keyed node once resolution succeeds). Never delete/merge either
1102
+ * node — this edge exists so a consumer wanting a deduped view can follow
1103
+ * it to the canonical id, reversibly.
1104
+ */
1105
+ "same_as"
1106
+ ]);
1107
+ e.object({
1108
+ id: e.string(),
1109
+ sourceId: e.string(),
1110
+ targetId: e.string(),
1111
+ edgeType: At,
1112
+ weight: e.number().min(0).max(1),
1113
+ evidenceSignalIds: e.array(e.number()),
1114
+ updatedAt: e.string().datetime(),
1115
+ validFrom: e.string().datetime(),
1116
+ /** null = currently valid. Set when a differently-typed edge supersedes this one. */
1117
+ validTo: e.string().datetime().nullable()
1118
+ });
1119
+ var xt = e.object({
1120
+ signalId: e.number(),
1121
+ weight: e.number().min(0).max(1),
1122
+ reason: e.string().max(280)
1123
+ });
1124
+ e.object({
1125
+ ticker: e.string(),
1126
+ // 'operations'/'customer' are current; 'operational'/'ux' are pre-rename
1127
+ // values that still exist on rows written before the backend's rename —
1128
+ // kept here so reading old rows doesn't fail validation.
1129
+ metric: e.enum(["operations", "customer", "operational", "ux"]),
1130
+ score: e.number(),
1131
+ baseline: e.number(),
1132
+ observed: e.number(),
1133
+ computedAt: e.string().datetime(),
1134
+ contributingSignals: e.array(xt)
1135
+ });
1136
+ e.object({
1137
+ lei: e.string().nullable(),
1138
+ entityName: e.string(),
1139
+ jurisdiction: e.string().nullable(),
1140
+ registrationStatus: e.string(),
1141
+ parentEntityLei: e.string().nullable(),
1142
+ materialMetadata: e.record(e.unknown()),
1143
+ discoveredAt: e.string().datetime()
1144
+ });
1145
+ var Y = e.enum(["db", "mock"]), ae = e.enum(["news", "filing", "report"]), ge = e.enum(["graded", "binary", "default", "none"]), vt = e.enum(["second", "day"]), kt = e.object({
1146
+ /** Namespaced so ids never collide across sources: `news:1234`, `filing:AAPL:2026-07-31`. */
1147
+ id: e.string(),
1148
+ kind: ae,
1149
+ /**
1150
+ * The producer's own type string, unmodified — `NEWS_YAHOO FINANCE_YAHOO RSS`,
1151
+ * `ANNUAL`, `SNAPSHOT`. There are 31 distinct NEWS variants in the live table,
1152
+ * so this is for filtering and debugging: never render it raw to a user.
1153
+ */
1154
+ subtype: e.string().nullable(),
1155
+ ticker: e.string(),
1156
+ /** Always `YYYY-MM-DDTHH:MM:SSZ`. Fixed-width, so lexical order == chronological order. */
1157
+ occurredAt: e.string(),
1158
+ precision: vt,
1159
+ title: e.string(),
1160
+ summary: e.string().nullable(),
1161
+ url: e.string().nullable(),
1162
+ impact: e.number().nullable(),
1163
+ impactScale: ge,
1164
+ /** 0 bearish … 50 neutral … 100 bullish. */
1165
+ sentiment: e.number().nullable(),
1166
+ /** False for filings, and for any event sitting at exactly neutral. */
1167
+ sentimentIsMeaningful: e.boolean(),
1168
+ source: Y,
1169
+ meta: e.record(e.unknown()).nullable()
1170
+ });
1171
+ e.object({
1172
+ total: e.number(),
1173
+ page: e.number(),
1174
+ page_size: e.number(),
1175
+ data: e.array(kt)
1176
+ });
1177
+ var St = e.enum(["day", "week", "month"]), _t = e.object({
1178
+ bucketStart: e.string(),
1179
+ kind: ae,
1180
+ count: e.number(),
1181
+ /** Null when no event in the bucket had meaningful sentiment. */
1182
+ avgSentiment: e.number().nullable(),
1183
+ maxImpact: e.number().nullable()
1184
+ });
1185
+ e.object({
1186
+ ticker: e.string(),
1187
+ bucket: St,
1188
+ buckets: e.array(_t),
1189
+ /** So the client can set its time domain without a second request. */
1190
+ range: e.object({ min: e.string(), max: e.string() }),
1191
+ source: Y
1192
+ });
1193
+ var Tt = e.object({
1194
+ kind: ae,
1195
+ count: e.number(),
1196
+ earliest: e.string().nullable(),
1197
+ latest: e.string().nullable(),
1198
+ impactScale: ge,
1199
+ sentimentUsable: e.boolean()
1200
+ });
1201
+ e.object({
1202
+ ticker: e.string(),
1203
+ facets: e.array(Tt),
1204
+ source: Y
1205
+ });
1206
+ var It = e.object({
1207
+ date: e.string(),
1208
+ open: e.number().nullable(),
1209
+ high: e.number().nullable(),
1210
+ low: e.number().nullable(),
1211
+ close: e.number(),
1212
+ volume: e.number().nullable()
1213
+ });
1214
+ e.object({
1215
+ ticker: e.string(),
1216
+ series: e.array(It),
1217
+ source: Y
1218
+ });
1219
+ var Ur = 50;
1220
+ const oe = {
1221
+ // May 2026 stable series — gemini-2.0-flash is deprecated (404)
1222
+ "google-gemini": ["gemini-2.5-flash", "gemini-2.5-pro", "gemini-2.5-flash-preview-05-20", "gemini-1.5-flash"],
1223
+ openai: ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "gpt-3.5-turbo"],
1224
+ // Verified live via client.models.list() this session — claude-3-5-haiku
1225
+ // and claude-3-opus (the old list) no longer appear in the current
1226
+ // catalog at all. claude-haiku-4-5 leads (used as PROVIDER_MODELS['anthropic'][0],
1227
+ // the auto-selected default) since it's this app's own real Model
1228
+ // Inventory's top performer (avg comparison score 91.6 across every
1229
+ // Compare Models run it's been in).
1230
+ anthropic: ["claude-haiku-4-5-20251001", "claude-sonnet-5", "claude-opus-5"],
1231
+ grok: ["grok-beta", "grok-vision-beta"],
1232
+ deepseek: ["deepseek-chat", "deepseek-coder"],
1233
+ // Real, currently-pulled models on this deployment's Ollama instance
1234
+ // (verified via GET /api/tags, not guessed) — 'llama3.1'/'mistral'/
1235
+ // 'codellama'/'qwen2.5' were never actually pulled locally, so picking
1236
+ // any of them would 404 at request time. llama3.3 leads the list (used
1237
+ // as PROVIDER_MODELS[provider][0], the auto-selected default on
1238
+ // provider switch) since it's already this app's proven-reliable
1239
+ // default for Ollama-backed report generation elsewhere
1240
+ // (core/ai_router.py's DEFAULT_MODELS) — llama3.2 (3B) was found live
1241
+ // to mis-trigger tool calls on plain greetings.
1242
+ ollama: ["llama3.3", "qwen2.5:32b", "qwen2.5-coder:32b", "qwen2.5-coder:14b", "qwen2.5-coder:7b", "llama3.2"]
1243
+ }, Br = {
1244
+ "google-gemini": "Google Gemini",
1245
+ openai: "OpenAI",
1246
+ anthropic: "Anthropic (Claude)",
1247
+ grok: "xAI Grok",
1248
+ deepseek: "DeepSeek",
1249
+ ollama: "Ollama (Local)"
1250
+ }, qr = {
1251
+ "google-gemini": "AIzaSy…",
1252
+ openai: "sk-…",
1253
+ anthropic: "sk-ant-…",
1254
+ grok: "xai-…",
1255
+ deepseek: "sk-…"
1256
+ }, Ot = Symbol("Let zodToJsonSchema decide on which parser to use"), ce = {
1257
+ name: void 0,
1258
+ $refStrategy: "root",
1259
+ basePath: ["#"],
1260
+ effectStrategy: "input",
1261
+ pipeStrategy: "all",
1262
+ dateStrategy: "format:date-time",
1263
+ mapStrategy: "entries",
1264
+ removeAdditionalStrategy: "passthrough",
1265
+ allowedAdditionalProperties: !0,
1266
+ rejectedAdditionalProperties: !1,
1267
+ definitionPath: "definitions",
1268
+ target: "jsonSchema7",
1269
+ strictUnions: !1,
1270
+ definitions: {},
1271
+ errorMessages: !1,
1272
+ markdownDescription: !1,
1273
+ patternStrategy: "escape",
1274
+ applyRegexFlags: !1,
1275
+ emailStrategy: "format:email",
1276
+ base64Strategy: "contentEncoding:base64",
1277
+ nameStrategy: "ref",
1278
+ openAiAnyTypeName: "OpenAiAnyType"
1279
+ }, Pt = (a) => typeof a == "string" ? {
1280
+ ...ce,
1281
+ name: a
1282
+ } : {
1283
+ ...ce,
1284
+ ...a
1285
+ }, jt = (a) => {
1286
+ const t = Pt(a), n = t.name !== void 0 ? [...t.basePath, t.definitionPath, t.name] : t.basePath;
1287
+ return {
1288
+ ...t,
1289
+ flags: { hasReferencedOpenAiAnyType: !1 },
1290
+ currentPath: n,
1291
+ propertyPath: void 0,
1292
+ seen: new Map(Object.entries(t.definitions).map(([r, o]) => [
1293
+ o._def,
1294
+ {
1295
+ def: o._def,
1296
+ path: [...t.basePath, t.definitionPath, r],
1297
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1298
+ jsonSchema: void 0
1299
+ }
1300
+ ]))
1301
+ };
1302
+ };
1303
+ function fe(a, t, n, r) {
1304
+ r != null && r.errorMessages && n && (a.errorMessage = {
1305
+ ...a.errorMessage,
1306
+ [t]: n
1307
+ });
1308
+ }
1309
+ function k(a, t, n, r, o) {
1310
+ a[t] = n, fe(a, t, r, o);
1311
+ }
1312
+ const ye = (a, t) => {
1313
+ let n = 0;
1314
+ for (; n < a.length && n < t.length && a[n] === t[n]; n++)
1315
+ ;
1316
+ return [(a.length - n).toString(), ...t.slice(n)].join("/");
1317
+ };
1318
+ var y;
1319
+ (function(a) {
1320
+ 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";
1321
+ })(y || (y = {}));
1322
+ function O(a) {
1323
+ if (a.target !== "openAi")
1324
+ return {};
1325
+ const t = [
1326
+ ...a.basePath,
1327
+ a.definitionPath,
1328
+ a.openAiAnyTypeName
1329
+ ];
1330
+ return a.flags.hasReferencedOpenAiAnyType = !0, {
1331
+ $ref: a.$refStrategy === "relative" ? ye(t, a.currentPath) : t.join("/")
1332
+ };
1333
+ }
1334
+ function Rt(a, t) {
1335
+ var r, o, s;
1336
+ const n = {
1337
+ type: "array"
1338
+ };
1339
+ return (r = a.type) != null && r._def && ((s = (o = a.type) == null ? void 0 : o._def) == null ? void 0 : s.typeName) !== y.ZodAny && (n.items = x(a.type._def, {
1340
+ ...t,
1341
+ currentPath: [...t.currentPath, "items"]
1342
+ })), a.minLength && k(n, "minItems", a.minLength.value, a.minLength.message, t), a.maxLength && k(n, "maxItems", a.maxLength.value, a.maxLength.message, t), a.exactLength && (k(n, "minItems", a.exactLength.value, a.exactLength.message, t), k(n, "maxItems", a.exactLength.value, a.exactLength.message, t)), n;
1343
+ }
1344
+ function Nt(a, t) {
1345
+ const n = {
1346
+ type: "integer",
1347
+ format: "int64"
1348
+ };
1349
+ if (!a.checks)
1350
+ return n;
1351
+ for (const r of a.checks)
1352
+ switch (r.kind) {
1353
+ case "min":
1354
+ t.target === "jsonSchema7" ? r.inclusive ? k(n, "minimum", r.value, r.message, t) : k(n, "exclusiveMinimum", r.value, r.message, t) : (r.inclusive || (n.exclusiveMinimum = !0), k(n, "minimum", r.value, r.message, t));
1355
+ break;
1356
+ case "max":
1357
+ t.target === "jsonSchema7" ? r.inclusive ? k(n, "maximum", r.value, r.message, t) : k(n, "exclusiveMaximum", r.value, r.message, t) : (r.inclusive || (n.exclusiveMaximum = !0), k(n, "maximum", r.value, r.message, t));
1358
+ break;
1359
+ case "multipleOf":
1360
+ k(n, "multipleOf", r.value, r.message, t);
1361
+ break;
1362
+ }
1363
+ return n;
1364
+ }
1365
+ function Dt() {
1366
+ return {
1367
+ type: "boolean"
1368
+ };
1369
+ }
1370
+ function be(a, t) {
1371
+ return x(a.type._def, t);
1372
+ }
1373
+ const Ct = (a, t) => x(a.innerType._def, t);
1374
+ function we(a, t, n) {
1375
+ const r = n ?? t.dateStrategy;
1376
+ if (Array.isArray(r))
1377
+ return {
1378
+ anyOf: r.map((o, s) => we(a, t, o))
1379
+ };
1380
+ switch (r) {
1381
+ case "string":
1382
+ case "format:date-time":
1383
+ return {
1384
+ type: "string",
1385
+ format: "date-time"
1386
+ };
1387
+ case "format:date":
1388
+ return {
1389
+ type: "string",
1390
+ format: "date"
1391
+ };
1392
+ case "integer":
1393
+ return $t(a, t);
1394
+ }
1395
+ }
1396
+ const $t = (a, t) => {
1397
+ const n = {
1398
+ type: "integer",
1399
+ format: "unix-time"
1400
+ };
1401
+ if (t.target === "openApi3")
1402
+ return n;
1403
+ for (const r of a.checks)
1404
+ switch (r.kind) {
1405
+ case "min":
1406
+ k(
1407
+ n,
1408
+ "minimum",
1409
+ r.value,
1410
+ // This is in milliseconds
1411
+ r.message,
1412
+ t
1413
+ );
1414
+ break;
1415
+ case "max":
1416
+ k(
1417
+ n,
1418
+ "maximum",
1419
+ r.value,
1420
+ // This is in milliseconds
1421
+ r.message,
1422
+ t
1423
+ );
1424
+ break;
1425
+ }
1426
+ return n;
1427
+ };
1428
+ function Mt(a, t) {
1429
+ return {
1430
+ ...x(a.innerType._def, t),
1431
+ default: a.defaultValue()
1432
+ };
1433
+ }
1434
+ function Lt(a, t) {
1435
+ return t.effectStrategy === "input" ? x(a.schema._def, t) : O(t);
1436
+ }
1437
+ function Ut(a) {
1438
+ return {
1439
+ type: "string",
1440
+ enum: Array.from(a.values)
1441
+ };
1442
+ }
1443
+ const Bt = (a) => "type" in a && a.type === "string" ? !1 : "allOf" in a;
1444
+ function qt(a, t) {
1445
+ const n = [
1446
+ x(a.left._def, {
1447
+ ...t,
1448
+ currentPath: [...t.currentPath, "allOf", "0"]
1449
+ }),
1450
+ x(a.right._def, {
1451
+ ...t,
1452
+ currentPath: [...t.currentPath, "allOf", "1"]
1453
+ })
1454
+ ].filter((s) => !!s);
1455
+ let r = t.target === "jsonSchema2019-09" ? { unevaluatedProperties: !1 } : void 0;
1456
+ const o = [];
1457
+ return n.forEach((s) => {
1458
+ if (Bt(s))
1459
+ o.push(...s.allOf), s.unevaluatedProperties === void 0 && (r = void 0);
1460
+ else {
1461
+ let i = s;
1462
+ if ("additionalProperties" in s && s.additionalProperties === !1) {
1463
+ const { additionalProperties: l, ...c } = s;
1464
+ i = c;
1465
+ } else
1466
+ r = void 0;
1467
+ o.push(i);
1468
+ }
1469
+ }), o.length ? {
1470
+ allOf: o,
1471
+ ...r
1472
+ } : void 0;
1473
+ }
1474
+ function Zt(a, t) {
1475
+ const n = typeof a.value;
1476
+ return n !== "bigint" && n !== "number" && n !== "boolean" && n !== "string" ? {
1477
+ type: Array.isArray(a.value) ? "array" : "object"
1478
+ } : t.target === "openApi3" ? {
1479
+ type: n === "bigint" ? "integer" : n,
1480
+ enum: [a.value]
1481
+ } : {
1482
+ type: n === "bigint" ? "integer" : n,
1483
+ const: a.value
1484
+ };
1485
+ }
1486
+ let H;
1487
+ const j = {
1488
+ /**
1489
+ * `c` was changed to `[cC]` to replicate /i flag
1490
+ */
1491
+ cuid: /^[cC][^\s-]{8,}$/,
1492
+ cuid2: /^[0-9a-z]+$/,
1493
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
1494
+ /**
1495
+ * `a-z` was added to replicate /i flag
1496
+ */
1497
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
1498
+ /**
1499
+ * Constructed a valid Unicode RegExp
1500
+ *
1501
+ * Lazily instantiate since this type of regex isn't supported
1502
+ * in all envs (e.g. React Native).
1503
+ *
1504
+ * See:
1505
+ * https://github.com/colinhacks/zod/issues/2433
1506
+ * Fix in Zod:
1507
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
1508
+ */
1509
+ emoji: () => (H === void 0 && (H = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u")), H),
1510
+ /**
1511
+ * Unused
1512
+ */
1513
+ 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}$/,
1514
+ /**
1515
+ * Unused
1516
+ */
1517
+ 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])$/,
1518
+ 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])$/,
1519
+ /**
1520
+ * Unused
1521
+ */
1522
+ 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})))$/,
1523
+ 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])$/,
1524
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
1525
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
1526
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
1527
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1528
+ };
1529
+ function Ee(a, t) {
1530
+ const n = {
1531
+ type: "string"
1532
+ };
1533
+ if (a.checks)
1534
+ for (const r of a.checks)
1535
+ switch (r.kind) {
1536
+ case "min":
1537
+ k(n, "minLength", typeof n.minLength == "number" ? Math.max(n.minLength, r.value) : r.value, r.message, t);
1538
+ break;
1539
+ case "max":
1540
+ k(n, "maxLength", typeof n.maxLength == "number" ? Math.min(n.maxLength, r.value) : r.value, r.message, t);
1541
+ break;
1542
+ case "email":
1543
+ switch (t.emailStrategy) {
1544
+ case "format:email":
1545
+ R(n, "email", r.message, t);
1546
+ break;
1547
+ case "format:idn-email":
1548
+ R(n, "idn-email", r.message, t);
1549
+ break;
1550
+ case "pattern:zod":
1551
+ I(n, j.email, r.message, t);
1552
+ break;
1553
+ }
1554
+ break;
1555
+ case "url":
1556
+ R(n, "uri", r.message, t);
1557
+ break;
1558
+ case "uuid":
1559
+ R(n, "uuid", r.message, t);
1560
+ break;
1561
+ case "regex":
1562
+ I(n, r.regex, r.message, t);
1563
+ break;
1564
+ case "cuid":
1565
+ I(n, j.cuid, r.message, t);
1566
+ break;
1567
+ case "cuid2":
1568
+ I(n, j.cuid2, r.message, t);
1569
+ break;
1570
+ case "startsWith":
1571
+ I(n, RegExp(`^${W(r.value, t)}`), r.message, t);
1572
+ break;
1573
+ case "endsWith":
1574
+ I(n, RegExp(`${W(r.value, t)}$`), r.message, t);
1575
+ break;
1576
+ case "datetime":
1577
+ R(n, "date-time", r.message, t);
1578
+ break;
1579
+ case "date":
1580
+ R(n, "date", r.message, t);
1581
+ break;
1582
+ case "time":
1583
+ R(n, "time", r.message, t);
1584
+ break;
1585
+ case "duration":
1586
+ R(n, "duration", r.message, t);
1587
+ break;
1588
+ case "length":
1589
+ k(n, "minLength", typeof n.minLength == "number" ? Math.max(n.minLength, r.value) : r.value, r.message, t), k(n, "maxLength", typeof n.maxLength == "number" ? Math.min(n.maxLength, r.value) : r.value, r.message, t);
1590
+ break;
1591
+ case "includes": {
1592
+ I(n, RegExp(W(r.value, t)), r.message, t);
1593
+ break;
1594
+ }
1595
+ case "ip": {
1596
+ r.version !== "v6" && R(n, "ipv4", r.message, t), r.version !== "v4" && R(n, "ipv6", r.message, t);
1597
+ break;
1598
+ }
1599
+ case "base64url":
1600
+ I(n, j.base64url, r.message, t);
1601
+ break;
1602
+ case "jwt":
1603
+ I(n, j.jwt, r.message, t);
1604
+ break;
1605
+ case "cidr": {
1606
+ r.version !== "v6" && I(n, j.ipv4Cidr, r.message, t), r.version !== "v4" && I(n, j.ipv6Cidr, r.message, t);
1607
+ break;
1608
+ }
1609
+ case "emoji":
1610
+ I(n, j.emoji(), r.message, t);
1611
+ break;
1612
+ case "ulid": {
1613
+ I(n, j.ulid, r.message, t);
1614
+ break;
1615
+ }
1616
+ case "base64": {
1617
+ switch (t.base64Strategy) {
1618
+ case "format:binary": {
1619
+ R(n, "binary", r.message, t);
1620
+ break;
1621
+ }
1622
+ case "contentEncoding:base64": {
1623
+ k(n, "contentEncoding", "base64", r.message, t);
1624
+ break;
1625
+ }
1626
+ case "pattern:zod": {
1627
+ I(n, j.base64, r.message, t);
1628
+ break;
1629
+ }
1630
+ }
1631
+ break;
1632
+ }
1633
+ case "nanoid":
1634
+ I(n, j.nanoid, r.message, t);
1635
+ }
1636
+ return n;
1637
+ }
1638
+ function W(a, t) {
1639
+ return t.patternStrategy === "escape" ? zt(a) : a;
1640
+ }
1641
+ const Ft = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
1642
+ function zt(a) {
1643
+ let t = "";
1644
+ for (let n = 0; n < a.length; n++)
1645
+ Ft.has(a[n]) || (t += "\\"), t += a[n];
1646
+ return t;
1647
+ }
1648
+ function R(a, t, n, r) {
1649
+ var o;
1650
+ a.format || (o = a.anyOf) != null && o.some((s) => s.format) ? (a.anyOf || (a.anyOf = []), a.format && (a.anyOf.push({
1651
+ format: a.format,
1652
+ ...a.errorMessage && r.errorMessages && {
1653
+ errorMessage: { format: a.errorMessage.format }
1654
+ }
1655
+ }), delete a.format, a.errorMessage && (delete a.errorMessage.format, Object.keys(a.errorMessage).length === 0 && delete a.errorMessage)), a.anyOf.push({
1656
+ format: t,
1657
+ ...n && r.errorMessages && { errorMessage: { format: n } }
1658
+ })) : k(a, "format", t, n, r);
1659
+ }
1660
+ function I(a, t, n, r) {
1661
+ var o;
1662
+ a.pattern || (o = a.allOf) != null && o.some((s) => s.pattern) ? (a.allOf || (a.allOf = []), a.pattern && (a.allOf.push({
1663
+ pattern: a.pattern,
1664
+ ...a.errorMessage && r.errorMessages && {
1665
+ errorMessage: { pattern: a.errorMessage.pattern }
1666
+ }
1667
+ }), delete a.pattern, a.errorMessage && (delete a.errorMessage.pattern, Object.keys(a.errorMessage).length === 0 && delete a.errorMessage)), a.allOf.push({
1668
+ pattern: le(t, r),
1669
+ ...n && r.errorMessages && { errorMessage: { pattern: n } }
1670
+ })) : k(a, "pattern", le(t, r), n, r);
1671
+ }
1672
+ function le(a, t) {
1673
+ var c;
1674
+ if (!t.applyRegexFlags || !a.flags)
1675
+ return a.source;
1676
+ const n = {
1677
+ i: a.flags.includes("i"),
1678
+ m: a.flags.includes("m"),
1679
+ s: a.flags.includes("s")
1680
+ // `.` matches newlines
1681
+ }, r = n.i ? a.source.toLowerCase() : a.source;
1682
+ let o = "", s = !1, i = !1, l = !1;
1683
+ for (let u = 0; u < r.length; u++) {
1684
+ if (s) {
1685
+ o += r[u], s = !1;
1686
+ continue;
1687
+ }
1688
+ if (n.i) {
1689
+ if (i) {
1690
+ if (r[u].match(/[a-z]/)) {
1691
+ l ? (o += r[u], o += `${r[u - 2]}-${r[u]}`.toUpperCase(), l = !1) : r[u + 1] === "-" && ((c = r[u + 2]) != null && c.match(/[a-z]/)) ? (o += r[u], l = !0) : o += `${r[u]}${r[u].toUpperCase()}`;
1692
+ continue;
1693
+ }
1694
+ } else if (r[u].match(/[a-z]/)) {
1695
+ o += `[${r[u]}${r[u].toUpperCase()}]`;
1696
+ continue;
1697
+ }
1698
+ }
1699
+ if (n.m) {
1700
+ if (r[u] === "^") {
1701
+ o += `(^|(?<=[\r
1702
+ ]))`;
1703
+ continue;
1704
+ } else if (r[u] === "$") {
1705
+ o += `($|(?=[\r
1706
+ ]))`;
1707
+ continue;
1708
+ }
1709
+ }
1710
+ if (n.s && r[u] === ".") {
1711
+ o += i ? `${r[u]}\r
1712
+ ` : `[${r[u]}\r
1713
+ ]`;
1714
+ continue;
1715
+ }
1716
+ o += r[u], r[u] === "\\" ? s = !0 : i && r[u] === "]" ? i = !1 : !i && r[u] === "[" && (i = !0);
1717
+ }
1718
+ try {
1719
+ new RegExp(o);
1720
+ } catch {
1721
+ return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`), a.source;
1722
+ }
1723
+ return o;
1724
+ }
1725
+ function Ae(a, t) {
1726
+ var r, o, s, i, l, c;
1727
+ if (t.target === "openAi" && console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."), t.target === "openApi3" && ((r = a.keyType) == null ? void 0 : r._def.typeName) === y.ZodEnum)
1728
+ return {
1729
+ type: "object",
1730
+ required: a.keyType._def.values,
1731
+ properties: a.keyType._def.values.reduce((u, m) => ({
1732
+ ...u,
1733
+ [m]: x(a.valueType._def, {
1734
+ ...t,
1735
+ currentPath: [...t.currentPath, "properties", m]
1736
+ }) ?? O(t)
1737
+ }), {}),
1738
+ additionalProperties: t.rejectedAdditionalProperties
1739
+ };
1740
+ const n = {
1741
+ type: "object",
1742
+ additionalProperties: x(a.valueType._def, {
1743
+ ...t,
1744
+ currentPath: [...t.currentPath, "additionalProperties"]
1745
+ }) ?? t.allowedAdditionalProperties
1746
+ };
1747
+ if (t.target === "openApi3")
1748
+ return n;
1749
+ if (((o = a.keyType) == null ? void 0 : o._def.typeName) === y.ZodString && ((s = a.keyType._def.checks) != null && s.length)) {
1750
+ const { type: u, ...m } = Ee(a.keyType._def, t);
1751
+ return {
1752
+ ...n,
1753
+ propertyNames: m
1754
+ };
1755
+ } else {
1756
+ if (((i = a.keyType) == null ? void 0 : i._def.typeName) === y.ZodEnum)
1757
+ return {
1758
+ ...n,
1759
+ propertyNames: {
1760
+ enum: a.keyType._def.values
1761
+ }
1762
+ };
1763
+ 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)) {
1764
+ const { type: u, ...m } = be(a.keyType._def, t);
1765
+ return {
1766
+ ...n,
1767
+ propertyNames: m
1768
+ };
1769
+ }
1770
+ }
1771
+ return n;
1772
+ }
1773
+ function Vt(a, t) {
1774
+ if (t.mapStrategy === "record")
1775
+ return Ae(a, t);
1776
+ const n = x(a.keyType._def, {
1777
+ ...t,
1778
+ currentPath: [...t.currentPath, "items", "items", "0"]
1779
+ }) || O(t), r = x(a.valueType._def, {
1780
+ ...t,
1781
+ currentPath: [...t.currentPath, "items", "items", "1"]
1782
+ }) || O(t);
1783
+ return {
1784
+ type: "array",
1785
+ maxItems: 125,
1786
+ items: {
1787
+ type: "array",
1788
+ items: [n, r],
1789
+ minItems: 2,
1790
+ maxItems: 2
1791
+ }
1792
+ };
1793
+ }
1794
+ function Jt(a) {
1795
+ const t = a.values, r = Object.keys(a.values).filter((s) => typeof t[t[s]] != "number").map((s) => t[s]), o = Array.from(new Set(r.map((s) => typeof s)));
1796
+ return {
1797
+ type: o.length === 1 ? o[0] === "string" ? "string" : "number" : ["string", "number"],
1798
+ enum: r
1799
+ };
1800
+ }
1801
+ function Kt(a) {
1802
+ return a.target === "openAi" ? void 0 : {
1803
+ not: O({
1804
+ ...a,
1805
+ currentPath: [...a.currentPath, "not"]
1806
+ })
1807
+ };
1808
+ }
1809
+ function Yt(a) {
1810
+ return a.target === "openApi3" ? {
1811
+ enum: ["null"],
1812
+ nullable: !0
1813
+ } : {
1814
+ type: "null"
1815
+ };
1816
+ }
1817
+ const V = {
1818
+ ZodString: "string",
1819
+ ZodNumber: "number",
1820
+ ZodBigInt: "integer",
1821
+ ZodBoolean: "boolean",
1822
+ ZodNull: "null"
1823
+ };
1824
+ function Gt(a, t) {
1825
+ if (t.target === "openApi3")
1826
+ return ue(a, t);
1827
+ const n = a.options instanceof Map ? Array.from(a.options.values()) : a.options;
1828
+ if (n.every((r) => r._def.typeName in V && (!r._def.checks || !r._def.checks.length))) {
1829
+ const r = n.reduce((o, s) => {
1830
+ const i = V[s._def.typeName];
1831
+ return i && !o.includes(i) ? [...o, i] : o;
1832
+ }, []);
1833
+ return {
1834
+ type: r.length > 1 ? r : r[0]
1835
+ };
1836
+ } else if (n.every((r) => r._def.typeName === "ZodLiteral" && !r.description)) {
1837
+ const r = n.reduce((o, s) => {
1838
+ const i = typeof s._def.value;
1839
+ switch (i) {
1840
+ case "string":
1841
+ case "number":
1842
+ case "boolean":
1843
+ return [...o, i];
1844
+ case "bigint":
1845
+ return [...o, "integer"];
1846
+ case "object":
1847
+ if (s._def.value === null)
1848
+ return [...o, "null"];
1849
+ case "symbol":
1850
+ case "undefined":
1851
+ case "function":
1852
+ default:
1853
+ return o;
1854
+ }
1855
+ }, []);
1856
+ if (r.length === n.length) {
1857
+ const o = r.filter((s, i, l) => l.indexOf(s) === i);
1858
+ return {
1859
+ type: o.length > 1 ? o : o[0],
1860
+ enum: n.reduce((s, i) => s.includes(i._def.value) ? s : [...s, i._def.value], [])
1861
+ };
1862
+ }
1863
+ } else if (n.every((r) => r._def.typeName === "ZodEnum"))
1864
+ return {
1865
+ type: "string",
1866
+ enum: n.reduce((r, o) => [
1867
+ ...r,
1868
+ ...o._def.values.filter((s) => !r.includes(s))
1869
+ ], [])
1870
+ };
1871
+ return ue(a, t);
1872
+ }
1873
+ const ue = (a, t) => {
1874
+ const n = (a.options instanceof Map ? Array.from(a.options.values()) : a.options).map((r, o) => x(r._def, {
1875
+ ...t,
1876
+ currentPath: [...t.currentPath, "anyOf", `${o}`]
1877
+ })).filter((r) => !!r && (!t.strictUnions || typeof r == "object" && Object.keys(r).length > 0));
1878
+ return n.length ? { anyOf: n } : void 0;
1879
+ };
1880
+ function Ht(a, t) {
1881
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(a.innerType._def.typeName) && (!a.innerType._def.checks || !a.innerType._def.checks.length))
1882
+ return t.target === "openApi3" ? {
1883
+ type: V[a.innerType._def.typeName],
1884
+ nullable: !0
1885
+ } : {
1886
+ type: [
1887
+ V[a.innerType._def.typeName],
1888
+ "null"
1889
+ ]
1890
+ };
1891
+ if (t.target === "openApi3") {
1892
+ const r = x(a.innerType._def, {
1893
+ ...t,
1894
+ currentPath: [...t.currentPath]
1895
+ });
1896
+ return r && "$ref" in r ? { allOf: [r], nullable: !0 } : r && { ...r, nullable: !0 };
1897
+ }
1898
+ const n = x(a.innerType._def, {
1899
+ ...t,
1900
+ currentPath: [...t.currentPath, "anyOf", "0"]
1901
+ });
1902
+ return n && { anyOf: [n, { type: "null" }] };
1903
+ }
1904
+ function Wt(a, t) {
1905
+ const n = {
1906
+ type: "number"
1907
+ };
1908
+ if (!a.checks)
1909
+ return n;
1910
+ for (const r of a.checks)
1911
+ switch (r.kind) {
1912
+ case "int":
1913
+ n.type = "integer", fe(n, "type", r.message, t);
1914
+ break;
1915
+ case "min":
1916
+ t.target === "jsonSchema7" ? r.inclusive ? k(n, "minimum", r.value, r.message, t) : k(n, "exclusiveMinimum", r.value, r.message, t) : (r.inclusive || (n.exclusiveMinimum = !0), k(n, "minimum", r.value, r.message, t));
1917
+ break;
1918
+ case "max":
1919
+ t.target === "jsonSchema7" ? r.inclusive ? k(n, "maximum", r.value, r.message, t) : k(n, "exclusiveMaximum", r.value, r.message, t) : (r.inclusive || (n.exclusiveMaximum = !0), k(n, "maximum", r.value, r.message, t));
1920
+ break;
1921
+ case "multipleOf":
1922
+ k(n, "multipleOf", r.value, r.message, t);
1923
+ break;
1924
+ }
1925
+ return n;
1926
+ }
1927
+ function Xt(a, t) {
1928
+ const n = t.target === "openAi", r = {
1929
+ type: "object",
1930
+ properties: {}
1931
+ }, o = [], s = a.shape();
1932
+ for (const l in s) {
1933
+ let c = s[l];
1934
+ if (c === void 0 || c._def === void 0)
1935
+ continue;
1936
+ let u = er(c);
1937
+ u && n && (c._def.typeName === "ZodOptional" && (c = c._def.innerType), c.isNullable() || (c = c.nullable()), u = !1);
1938
+ const m = x(c._def, {
1939
+ ...t,
1940
+ currentPath: [...t.currentPath, "properties", l],
1941
+ propertyPath: [...t.currentPath, "properties", l]
1942
+ });
1943
+ m !== void 0 && (r.properties[l] = m, u || o.push(l));
1944
+ }
1945
+ o.length && (r.required = o);
1946
+ const i = Qt(a, t);
1947
+ return i !== void 0 && (r.additionalProperties = i), r;
1948
+ }
1949
+ function Qt(a, t) {
1950
+ if (a.catchall._def.typeName !== "ZodNever")
1951
+ return x(a.catchall._def, {
1952
+ ...t,
1953
+ currentPath: [...t.currentPath, "additionalProperties"]
1954
+ });
1955
+ switch (a.unknownKeys) {
1956
+ case "passthrough":
1957
+ return t.allowedAdditionalProperties;
1958
+ case "strict":
1959
+ return t.rejectedAdditionalProperties;
1960
+ case "strip":
1961
+ return t.removeAdditionalStrategy === "strict" ? t.allowedAdditionalProperties : t.rejectedAdditionalProperties;
1962
+ }
1963
+ }
1964
+ function er(a) {
1965
+ try {
1966
+ return a.isOptional();
1967
+ } catch {
1968
+ return !0;
1969
+ }
1970
+ }
1971
+ const tr = (a, t) => {
1972
+ var r;
1973
+ if (t.currentPath.toString() === ((r = t.propertyPath) == null ? void 0 : r.toString()))
1974
+ return x(a.innerType._def, t);
1975
+ const n = x(a.innerType._def, {
1976
+ ...t,
1977
+ currentPath: [...t.currentPath, "anyOf", "1"]
1978
+ });
1979
+ return n ? {
1980
+ anyOf: [
1981
+ {
1982
+ not: O(t)
1983
+ },
1984
+ n
1985
+ ]
1986
+ } : O(t);
1987
+ }, rr = (a, t) => {
1988
+ if (t.pipeStrategy === "input")
1989
+ return x(a.in._def, t);
1990
+ if (t.pipeStrategy === "output")
1991
+ return x(a.out._def, t);
1992
+ const n = x(a.in._def, {
1993
+ ...t,
1994
+ currentPath: [...t.currentPath, "allOf", "0"]
1995
+ }), r = x(a.out._def, {
1996
+ ...t,
1997
+ currentPath: [...t.currentPath, "allOf", n ? "1" : "0"]
1998
+ });
1999
+ return {
2000
+ allOf: [n, r].filter((o) => o !== void 0)
2001
+ };
2002
+ };
2003
+ function nr(a, t) {
2004
+ return x(a.type._def, t);
2005
+ }
2006
+ function ar(a, t) {
2007
+ const r = {
2008
+ type: "array",
2009
+ uniqueItems: !0,
2010
+ items: x(a.valueType._def, {
2011
+ ...t,
2012
+ currentPath: [...t.currentPath, "items"]
2013
+ })
2014
+ };
2015
+ return a.minSize && k(r, "minItems", a.minSize.value, a.minSize.message, t), a.maxSize && k(r, "maxItems", a.maxSize.value, a.maxSize.message, t), r;
2016
+ }
2017
+ function or(a, t) {
2018
+ return a.rest ? {
2019
+ type: "array",
2020
+ minItems: a.items.length,
2021
+ items: a.items.map((n, r) => x(n._def, {
2022
+ ...t,
2023
+ currentPath: [...t.currentPath, "items", `${r}`]
2024
+ })).reduce((n, r) => r === void 0 ? n : [...n, r], []),
2025
+ additionalItems: x(a.rest._def, {
2026
+ ...t,
2027
+ currentPath: [...t.currentPath, "additionalItems"]
2028
+ })
2029
+ } : {
2030
+ type: "array",
2031
+ minItems: a.items.length,
2032
+ maxItems: a.items.length,
2033
+ items: a.items.map((n, r) => x(n._def, {
2034
+ ...t,
2035
+ currentPath: [...t.currentPath, "items", `${r}`]
2036
+ })).reduce((n, r) => r === void 0 ? n : [...n, r], [])
2037
+ };
2038
+ }
2039
+ function ir(a) {
2040
+ return {
2041
+ not: O(a)
2042
+ };
2043
+ }
2044
+ function sr(a) {
2045
+ return O(a);
2046
+ }
2047
+ const cr = (a, t) => x(a.innerType._def, t), lr = (a, t, n) => {
2048
+ switch (t) {
2049
+ case y.ZodString:
2050
+ return Ee(a, n);
2051
+ case y.ZodNumber:
2052
+ return Wt(a, n);
2053
+ case y.ZodObject:
2054
+ return Xt(a, n);
2055
+ case y.ZodBigInt:
2056
+ return Nt(a, n);
2057
+ case y.ZodBoolean:
2058
+ return Dt();
2059
+ case y.ZodDate:
2060
+ return we(a, n);
2061
+ case y.ZodUndefined:
2062
+ return ir(n);
2063
+ case y.ZodNull:
2064
+ return Yt(n);
2065
+ case y.ZodArray:
2066
+ return Rt(a, n);
2067
+ case y.ZodUnion:
2068
+ case y.ZodDiscriminatedUnion:
2069
+ return Gt(a, n);
2070
+ case y.ZodIntersection:
2071
+ return qt(a, n);
2072
+ case y.ZodTuple:
2073
+ return or(a, n);
2074
+ case y.ZodRecord:
2075
+ return Ae(a, n);
2076
+ case y.ZodLiteral:
2077
+ return Zt(a, n);
2078
+ case y.ZodEnum:
2079
+ return Ut(a);
2080
+ case y.ZodNativeEnum:
2081
+ return Jt(a);
2082
+ case y.ZodNullable:
2083
+ return Ht(a, n);
2084
+ case y.ZodOptional:
2085
+ return tr(a, n);
2086
+ case y.ZodMap:
2087
+ return Vt(a, n);
2088
+ case y.ZodSet:
2089
+ return ar(a, n);
2090
+ case y.ZodLazy:
2091
+ return () => a.getter()._def;
2092
+ case y.ZodPromise:
2093
+ return nr(a, n);
2094
+ case y.ZodNaN:
2095
+ case y.ZodNever:
2096
+ return Kt(n);
2097
+ case y.ZodEffects:
2098
+ return Lt(a, n);
2099
+ case y.ZodAny:
2100
+ return O(n);
2101
+ case y.ZodUnknown:
2102
+ return sr(n);
2103
+ case y.ZodDefault:
2104
+ return Mt(a, n);
2105
+ case y.ZodBranded:
2106
+ return be(a, n);
2107
+ case y.ZodReadonly:
2108
+ return cr(a, n);
2109
+ case y.ZodCatch:
2110
+ return Ct(a, n);
2111
+ case y.ZodPipeline:
2112
+ return rr(a, n);
2113
+ case y.ZodFunction:
2114
+ case y.ZodVoid:
2115
+ case y.ZodSymbol:
2116
+ return;
2117
+ default:
2118
+ return /* @__PURE__ */ ((r) => {
2119
+ })();
2120
+ }
2121
+ };
2122
+ function x(a, t, n = !1) {
2123
+ var l;
2124
+ const r = t.seen.get(a);
2125
+ if (t.override) {
2126
+ const c = (l = t.override) == null ? void 0 : l.call(t, a, t, r, n);
2127
+ if (c !== Ot)
2128
+ return c;
2129
+ }
2130
+ if (r && !n) {
2131
+ const c = ur(r, t);
2132
+ if (c !== void 0)
2133
+ return c;
2134
+ }
2135
+ const o = { def: a, path: t.currentPath, jsonSchema: void 0 };
2136
+ t.seen.set(a, o);
2137
+ const s = lr(a, a.typeName, t), i = typeof s == "function" ? x(s(), t) : s;
2138
+ if (i && mr(a, t, i), t.postProcess) {
2139
+ const c = t.postProcess(i, a, t);
2140
+ return o.jsonSchema = i, c;
2141
+ }
2142
+ return o.jsonSchema = i, i;
2143
+ }
2144
+ const ur = (a, t) => {
2145
+ switch (t.$refStrategy) {
2146
+ case "root":
2147
+ return { $ref: a.path.join("/") };
2148
+ case "relative":
2149
+ return { $ref: ye(t.currentPath, a.path) };
2150
+ case "none":
2151
+ case "seen":
2152
+ return a.path.length < t.currentPath.length && a.path.every((n, r) => t.currentPath[r] === n) ? (console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`), O(t)) : t.$refStrategy === "seen" ? O(t) : void 0;
2153
+ }
2154
+ }, mr = (a, t, n) => (a.description && (n.description = a.description, t.markdownDescription && (n.markdownDescription = a.description)), n), dr = (a, t) => {
2155
+ const n = jt(t);
2156
+ let r = typeof t == "object" && t.definitions ? Object.entries(t.definitions).reduce((c, [u, m]) => ({
2157
+ ...c,
2158
+ [u]: x(m._def, {
2159
+ ...n,
2160
+ currentPath: [...n.basePath, n.definitionPath, u]
2161
+ }, !0) ?? O(n)
2162
+ }), {}) : void 0;
2163
+ const o = typeof t == "string" ? t : (t == null ? void 0 : t.nameStrategy) === "title" || t == null ? void 0 : t.name, s = x(a._def, o === void 0 ? n : {
2164
+ ...n,
2165
+ currentPath: [...n.basePath, n.definitionPath, o]
2166
+ }, !1) ?? O(n), i = typeof t == "object" && t.name !== void 0 && t.nameStrategy === "title" ? t.name : void 0;
2167
+ i !== void 0 && (s.title = i), n.flags.hasReferencedOpenAiAnyType && (r || (r = {}), r[n.openAiAnyTypeName] || (r[n.openAiAnyTypeName] = {
2168
+ // Skipping "object" as no properties can be defined and additionalProperties must be "false"
2169
+ type: ["string", "number", "integer", "boolean", "array", "null"],
2170
+ items: {
2171
+ $ref: n.$refStrategy === "relative" ? "1" : [
2172
+ ...n.basePath,
2173
+ n.definitionPath,
2174
+ n.openAiAnyTypeName
2175
+ ].join("/")
2176
+ }
2177
+ }));
2178
+ const l = o === void 0 ? r ? {
2179
+ ...s,
2180
+ [n.definitionPath]: r
2181
+ } : s : {
2182
+ $ref: [
2183
+ ...n.$refStrategy === "relative" ? [] : n.basePath,
2184
+ n.definitionPath,
2185
+ o
2186
+ ].join("/"),
2187
+ [n.definitionPath]: {
2188
+ ...r,
2189
+ [o]: s
2190
+ }
2191
+ };
2192
+ return n.target === "jsonSchema7" ? l.$schema = "http://json-schema.org/draft-07/schema#" : (n.target === "jsonSchema2019-09" || n.target === "openAi") && (l.$schema = "https://json-schema.org/draft/2019-09/schema#"), n.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;
2193
+ };
2194
+ function Zr(a) {
2195
+ const t = dr(a.parameters, { target: "jsonSchema7", $refStrategy: "none" });
2196
+ return {
2197
+ name: a.name,
2198
+ description: a.description,
2199
+ parameters: t
2200
+ };
2201
+ }
2202
+ function pr(a) {
2203
+ const t = /* @__PURE__ */ new Set(["$schema", "additionalProperties", "default"]), n = (r) => Array.isArray(r) ? r.map(n) : r && typeof r == "object" ? Object.fromEntries(
2204
+ Object.entries(r).filter(([o]) => !t.has(o)).map(([o, s]) => [o, n(s)])
2205
+ ) : r;
2206
+ return n(a);
2207
+ }
2208
+ class hr {
2209
+ async *streamChat(t, n, r) {
2210
+ var h, g, E, f;
2211
+ const { apiKey: o, model: s = T["google-gemini"] } = n;
2212
+ if (!o) throw new Error("Gemini API key required");
2213
+ const i = t.find((w) => w.role === "system"), l = t.filter((w) => w.role !== "system").map((w) => ({ role: w.role === "assistant" ? "model" : "user", parts: [{ text: w.content }] })), c = r != null && r.length ? [{
2214
+ functionDeclarations: r.map((w) => ({
2215
+ name: w.name,
2216
+ description: w.description,
2217
+ parameters: pr(w.parameters)
2218
+ }))
2219
+ }] : void 0, u = await fetch(
2220
+ `https://generativelanguage.googleapis.com/v1beta/models/${s}:streamGenerateContent?alt=sse`,
2221
+ {
2222
+ method: "POST",
2223
+ headers: { "Content-Type": "application/json", "x-goog-api-key": o },
2224
+ body: JSON.stringify({
2225
+ contents: l,
2226
+ ...i && { systemInstruction: { parts: [{ text: i.content }] } },
2227
+ ...c && { tools: c }
2228
+ })
2229
+ }
2230
+ );
2231
+ if (!u.ok) {
2232
+ const w = await u.text();
2233
+ throw new Error(`Gemini Error ${u.status}: ${w}`);
2234
+ }
2235
+ const m = (h = u.body) == null ? void 0 : h.getReader();
2236
+ if (!m) throw new Error("No response body");
2237
+ const d = new TextDecoder();
2238
+ let p = "";
2239
+ for (; ; ) {
2240
+ const { done: w, value: A } = await m.read();
2241
+ if (w) break;
2242
+ p += d.decode(A, { stream: !0 });
2243
+ const S = p.split(`
2244
+ `);
2245
+ p = S.pop() || "";
2246
+ for (const b of S) {
2247
+ const v = b.trim();
2248
+ if (!(!v || !v.startsWith("data: ")))
2249
+ try {
2250
+ const C = ((f = (E = (g = JSON.parse(v.slice(6)).candidates) == null ? void 0 : g[0]) == null ? void 0 : E.content) == null ? void 0 : f.parts) ?? [];
2251
+ for (const D of C)
2252
+ D.text && (yield { type: "text-delta", text: D.text }), D.functionCall && (yield {
2253
+ type: "tool-call",
2254
+ toolCall: { name: D.functionCall.name, arguments: D.functionCall.args ?? {} }
2255
+ });
2256
+ } catch {
2257
+ }
2258
+ }
2259
+ }
2260
+ }
2261
+ async generateText(t, n) {
2262
+ var c, u, m, d, p;
2263
+ const { apiKey: r, model: o = T["google-gemini"], temperature: s = 0.7 } = n;
2264
+ if (!r) throw new Error("Gemini API key required");
2265
+ if (!o) throw new Error("GeminiAdapter: model is required but was undefined");
2266
+ const i = await fetch(
2267
+ `https://generativelanguage.googleapis.com/v1beta/models/${o}:generateContent`,
2268
+ {
2269
+ method: "POST",
2270
+ headers: {
2271
+ "Content-Type": "application/json",
2272
+ "x-goog-api-key": r
2273
+ },
2274
+ body: JSON.stringify({
2275
+ contents: [{ parts: [{ text: t }] }],
2276
+ generationConfig: { temperature: s }
2277
+ })
2278
+ }
2279
+ );
2280
+ if (!i.ok) {
2281
+ const h = await i.text();
2282
+ throw new Error(`Gemini Error ${i.status}: ${h}`);
2283
+ }
2284
+ return ((p = (d = (m = (u = (c = (await i.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) || "";
2285
+ }
2286
+ async *streamText(t, n) {
2287
+ var u, m, d, p, h, g;
2288
+ const { apiKey: r, model: o = T["google-gemini"] } = n;
2289
+ if (!r) throw new Error("Gemini API key required");
2290
+ if (!o) throw new Error("GeminiAdapter: model is required but was undefined");
2291
+ const s = await fetch(
2292
+ `https://generativelanguage.googleapis.com/v1beta/models/${o}:streamGenerateContent?alt=sse`,
2293
+ {
2294
+ method: "POST",
2295
+ headers: {
2296
+ "Content-Type": "application/json",
2297
+ "x-goog-api-key": r
2298
+ },
2299
+ body: JSON.stringify({
2300
+ contents: [{ parts: [{ text: t }] }]
2301
+ })
2302
+ }
2303
+ );
2304
+ if (!s.ok) {
2305
+ const E = await s.text();
2306
+ throw new Error(`Gemini Error ${s.status}: ${E}`);
2307
+ }
2308
+ const i = (u = s.body) == null ? void 0 : u.getReader();
2309
+ if (!i) throw new Error("No response body");
2310
+ const l = new TextDecoder();
2311
+ let c = "";
2312
+ for (; ; ) {
2313
+ const { done: E, value: f } = await i.read();
2314
+ if (E) break;
2315
+ c += l.decode(f, { stream: !0 });
2316
+ const w = c.split(`
2317
+ `);
2318
+ c = w.pop() || "";
2319
+ for (const A of w) {
2320
+ const S = A.trim();
2321
+ if (!(!S || !S.startsWith("data: ")))
2322
+ try {
2323
+ const v = (g = (h = (p = (d = (m = JSON.parse(S.slice(6)).candidates) == null ? void 0 : m[0]) == null ? void 0 : d.content) == null ? void 0 : p.parts) == null ? void 0 : h[0]) == null ? void 0 : g.text;
2324
+ v && (yield v);
2325
+ } catch {
2326
+ continue;
2327
+ }
2328
+ }
2329
+ }
2330
+ }
2331
+ async generateObject(t, n, r) {
2332
+ var u, m, d, p, h;
2333
+ const { apiKey: o, model: s = T["google-gemini"] } = r;
2334
+ if (!o) throw new Error("Gemini API key required");
2335
+ if (!s) throw new Error("GeminiAdapter: model is required but was undefined");
2336
+ const i = await fetch(
2337
+ `https://generativelanguage.googleapis.com/v1beta/models/${s}:generateContent`,
2338
+ {
2339
+ method: "POST",
2340
+ headers: {
2341
+ "Content-Type": "application/json",
2342
+ "x-goog-api-key": o
2343
+ },
2344
+ body: JSON.stringify({
2345
+ contents: [{ parts: [{ text: t }] }],
2346
+ generationConfig: {
2347
+ responseMimeType: "application/json",
2348
+ responseSchema: n
2349
+ }
2350
+ })
2351
+ }
2352
+ );
2353
+ if (!i.ok) {
2354
+ const g = await i.json();
2355
+ throw this.normalizeError(g, i.status);
2356
+ }
2357
+ const c = ((h = (p = (d = (m = (u = (await i.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 : h.text) || "{}";
2358
+ return JSON.parse(c);
2359
+ }
2360
+ async listModels(t) {
2361
+ var o;
2362
+ if (!t) throw new Error("API key required to list models");
2363
+ const n = await fetch(
2364
+ "https://generativelanguage.googleapis.com/v1beta/models",
2365
+ {
2366
+ headers: { "x-goog-api-key": t }
2367
+ }
2368
+ );
2369
+ if (!n.ok)
2370
+ throw new Error("Failed to fetch model list");
2371
+ return ((o = (await n.json()).models) == null ? void 0 : o.map((s) => s.name)) || [];
2372
+ }
2373
+ normalizeError(t, n) {
2374
+ var r;
2375
+ if (n === 429) {
2376
+ const o = new Error("Rate limit exceeded. Please wait 30 seconds before retrying.");
2377
+ return o.code = "RATE_LIMIT", o;
2378
+ }
2379
+ if (n === 401 || n === 403) {
2380
+ const o = new Error("Invalid API key.");
2381
+ return o.code = "AUTH_ERROR", o;
2382
+ }
2383
+ return new Error(((r = t.error) == null ? void 0 : r.message) || "Unknown error");
2384
+ }
2385
+ }
2386
+ class gr {
2387
+ /**
2388
+ * Tool calling requires /api/chat, not /api/generate (which has no tool
2389
+ * support at all). Tool support itself is model-dependent (llama3.1+,
2390
+ * qwen2.5, mistral-nemo, etc.) — a non-tool-capable model just replies
2391
+ * with plain text; there's no reliable way to detect that in advance, so
2392
+ * this degrades gracefully rather than special-casing it.
2393
+ */
2394
+ async *streamChat(t, n, r) {
2395
+ var d, p, h, g, E;
2396
+ const { baseUrl: o = "http://localhost:11434", model: s = T.ollama } = n, i = r != null && r.length ? r.map((f) => ({ type: "function", function: { name: f.name, description: f.description, parameters: f.parameters } })) : void 0, l = await fetch(`${o}/api/chat`, {
2397
+ method: "POST",
2398
+ headers: { "Content-Type": "application/json" },
2399
+ body: JSON.stringify({
2400
+ model: s,
2401
+ messages: t.map((f) => ({ role: f.role, content: f.content })),
2402
+ stream: !0,
2403
+ ...i && { tools: i }
2404
+ })
2405
+ });
2406
+ if (!l.ok) {
2407
+ const f = await l.text();
2408
+ throw new Error(`Ollama Error ${l.status}: ${f}`);
2409
+ }
2410
+ const c = (d = l.body) == null ? void 0 : d.getReader();
2411
+ if (!c) throw new Error("No response body");
2412
+ const u = new TextDecoder();
2413
+ let m = "";
2414
+ for (; ; ) {
2415
+ const { done: f, value: w } = await c.read();
2416
+ if (f) break;
2417
+ m += u.decode(w, { stream: !0 });
2418
+ const A = m.split(`
2419
+ `);
2420
+ m = A.pop() || "";
2421
+ for (const S of A) {
2422
+ const b = S.trim();
2423
+ if (b)
2424
+ try {
2425
+ const v = JSON.parse(b);
2426
+ if ((p = v.message) != null && p.content && (yield { type: "text-delta", text: v.message.content }), (h = v.message) != null && h.tool_calls)
2427
+ for (const N of v.message.tool_calls)
2428
+ yield {
2429
+ type: "tool-call",
2430
+ toolCall: { name: (g = N.function) == null ? void 0 : g.name, arguments: ((E = N.function) == null ? void 0 : E.arguments) ?? {} }
2431
+ };
2432
+ } catch {
2433
+ }
2434
+ }
2435
+ }
2436
+ }
2437
+ async generateText(t, n) {
2438
+ const { baseUrl: r = "http://localhost:11434", model: o = T.ollama } = n, s = await fetch(`${r}/api/generate`, {
2439
+ method: "POST",
2440
+ headers: { "Content-Type": "application/json" },
2441
+ body: JSON.stringify({
2442
+ model: o,
2443
+ prompt: t,
2444
+ stream: !1
2445
+ })
2446
+ });
2447
+ if (!s.ok) {
2448
+ const l = await s.text();
2449
+ throw new Error(`Ollama Error ${s.status}: ${l}`);
2450
+ }
2451
+ return (await s.json()).response;
2452
+ }
2453
+ async *streamText(t, n) {
2454
+ var u;
2455
+ const { baseUrl: r = "http://localhost:11434", model: o = T.ollama } = n, s = await fetch(`${r}/api/generate`, {
2456
+ method: "POST",
2457
+ headers: { "Content-Type": "application/json" },
2458
+ body: JSON.stringify({
2459
+ model: o,
2460
+ prompt: t,
2461
+ stream: !0
2462
+ })
2463
+ });
2464
+ if (!s.ok) {
2465
+ const m = await s.text();
2466
+ throw new Error(`Ollama Error ${s.status}: ${m}`);
2467
+ }
2468
+ const i = (u = s.body) == null ? void 0 : u.getReader();
2469
+ if (!i) throw new Error("No response body");
2470
+ const l = new TextDecoder();
2471
+ let c = "";
2472
+ for (; ; ) {
2473
+ const { done: m, value: d } = await i.read();
2474
+ if (m) break;
2475
+ c += l.decode(d, { stream: !0 });
2476
+ const p = c.split(`
2477
+ `);
2478
+ c = p.pop() || "";
2479
+ for (const h of p) {
2480
+ const g = h.trim();
2481
+ if (g)
2482
+ try {
2483
+ const E = JSON.parse(g);
2484
+ E.response && (yield E.response);
2485
+ } catch {
2486
+ continue;
2487
+ }
2488
+ }
2489
+ }
2490
+ }
2491
+ async generateObject(t, n, r) {
2492
+ const o = `${t}
2493
+
2494
+ IMPORTANT: Return ONLY valid JSON matching this schema:
2495
+ ${JSON.stringify(n, null, 2)}
2496
+
2497
+ Do not include any explanation, only the raw JSON object.`, s = await this.generateText(o, r), i = s.match(/```json\n?([\s\S]*?)\n?```/) || s.match(/\{[\s\S]*\}/), l = i ? i[1] || i[0] : s;
2498
+ return JSON.parse(l.trim());
2499
+ }
2500
+ async listModels(t, n = "http://localhost:11434") {
2501
+ var s;
2502
+ const r = await fetch(`${n}/api/tags`);
2503
+ if (!r.ok)
2504
+ throw new Error(`Failed to fetch Ollama models. Is Ollama running at ${n}?`);
2505
+ return ((s = (await r.json()).models) == null ? void 0 : s.map((i) => i.name)) || [];
2506
+ }
2507
+ }
2508
+ class fr {
2509
+ async *streamChat(t, n, r) {
2510
+ var w, A, S;
2511
+ const {
2512
+ apiKey: o,
2513
+ model: s = T.anthropic,
2514
+ temperature: i = 0.7,
2515
+ maxTokens: l = 4096,
2516
+ baseUrl: c = "https://api.anthropic.com/v1"
2517
+ } = n;
2518
+ if (!o) throw new Error("Anthropic API key required");
2519
+ const u = t.find((b) => b.role === "system"), m = t.filter((b) => b.role !== "system").map((b) => ({ role: b.role, content: b.content })), d = r != null && r.length ? r.map((b) => ({ name: b.name, description: b.description, input_schema: b.parameters })) : void 0, p = await fetch(`${c}/messages`, {
2520
+ method: "POST",
2521
+ headers: {
2522
+ "Content-Type": "application/json",
2523
+ "x-api-key": o,
2524
+ "anthropic-version": "2023-06-01",
2525
+ "anthropic-dangerous-direct-browser-access": "true"
2526
+ },
2527
+ body: JSON.stringify({
2528
+ model: s,
2529
+ messages: m,
2530
+ ...u && { system: u.content },
2531
+ max_tokens: l,
2532
+ temperature: i,
2533
+ stream: !0,
2534
+ ...d && { tools: d }
2535
+ })
2536
+ });
2537
+ if (!p.ok) {
2538
+ const b = await p.text();
2539
+ throw new Error(`Anthropic ${p.status}: ${b}`);
2540
+ }
2541
+ if (!p.body) throw new Error("No response body for streaming");
2542
+ const h = p.body.getReader(), g = new TextDecoder();
2543
+ let E = "", f = null;
2544
+ try {
2545
+ for (; ; ) {
2546
+ const { done: b, value: v } = await h.read();
2547
+ if (b) break;
2548
+ E += g.decode(v, { stream: !0 });
2549
+ const N = E.split(`
2550
+ `);
2551
+ E = N.pop() || "";
2552
+ for (const C of N) {
2553
+ const D = C.trim();
2554
+ if (!(!D || !D.startsWith("data: ")))
2555
+ try {
2556
+ const P = JSON.parse(D.slice(6));
2557
+ if (P.type === "content_block_start" && ((w = P.content_block) == null ? void 0 : w.type) === "tool_use")
2558
+ f = { id: P.content_block.id, name: P.content_block.name, argsBuf: "" };
2559
+ else if (P.type === "content_block_delta")
2560
+ ((A = P.delta) == null ? void 0 : A.type) === "text_delta" && P.delta.text ? yield { type: "text-delta", text: P.delta.text } : ((S = P.delta) == null ? void 0 : S.type) === "input_json_delta" && f && (f.argsBuf += P.delta.partial_json ?? "");
2561
+ else if (P.type === "content_block_stop" && f) {
2562
+ try {
2563
+ yield {
2564
+ type: "tool-call",
2565
+ toolCall: {
2566
+ id: f.id,
2567
+ name: f.name,
2568
+ arguments: f.argsBuf ? JSON.parse(f.argsBuf) : {}
2569
+ }
2570
+ };
2571
+ } catch {
2572
+ }
2573
+ f = null;
2574
+ }
2575
+ } catch {
2576
+ }
2577
+ }
2578
+ }
2579
+ } finally {
2580
+ h.releaseLock();
2581
+ }
2582
+ }
2583
+ async generateText(t, n) {
2584
+ var m, d, p;
2585
+ const {
2586
+ apiKey: r,
2587
+ model: o = T.anthropic,
2588
+ temperature: s = 0.7,
2589
+ maxTokens: i = 4096,
2590
+ baseUrl: l = "https://api.anthropic.com/v1"
2591
+ } = n;
2592
+ if (!r) throw new Error("Anthropic API key required");
2593
+ if (!o) throw new Error("Model is required but was undefined");
2594
+ console.log("🔵 Anthropic Request:", {
2595
+ model: o,
2596
+ maxTokens: i,
2597
+ temperature: s,
2598
+ endpoint: `${l}/messages`,
2599
+ keyPrefix: r.slice(0, 12) + "…",
2600
+ keyLength: r.length
2601
+ });
2602
+ const c = await fetch(`${l}/messages`, {
2603
+ method: "POST",
2604
+ headers: {
2605
+ "Content-Type": "application/json",
2606
+ "x-api-key": r,
2607
+ "anthropic-version": "2023-06-01",
2608
+ "anthropic-dangerous-direct-browser-access": "true"
2609
+ },
2610
+ body: JSON.stringify({
2611
+ model: o,
2612
+ messages: [{ role: "user", content: t }],
2613
+ max_tokens: i,
2614
+ // REQUIRED by Anthropic
2615
+ temperature: s
2616
+ })
2617
+ });
2618
+ if (!c.ok) {
2619
+ const h = await c.text();
2620
+ console.error("🔴 RAW ANTHROPIC ERROR:", c.status, h), console.error("🔴 Request was made to:", `${l}/messages`), console.error("🔴 Model requested:", o);
2621
+ try {
2622
+ const g = JSON.parse(h);
2623
+ throw new Error(`Anthropic ${c.status}: ${((m = g.error) == null ? void 0 : m.message) || JSON.stringify(g)}`);
2624
+ } catch {
2625
+ throw new Error(`Anthropic ${c.status}: ${h}`);
2626
+ }
2627
+ }
2628
+ return ((p = (d = (await c.json()).content) == null ? void 0 : d[0]) == null ? void 0 : p.text) || "";
2629
+ }
2630
+ async *streamText(t, n) {
2631
+ var p, h;
2632
+ const {
2633
+ apiKey: r,
2634
+ model: o = T.anthropic,
2635
+ temperature: s = 0.7,
2636
+ maxTokens: i = 4096,
2637
+ baseUrl: l = "https://api.anthropic.com/v1"
2638
+ } = n;
2639
+ if (!r) throw new Error("Anthropic API key required");
2640
+ if (!o) throw new Error("Model is required but was undefined");
2641
+ const c = await fetch(`${l}/messages`, {
2642
+ method: "POST",
2643
+ headers: {
2644
+ "Content-Type": "application/json",
2645
+ "x-api-key": r,
2646
+ "anthropic-version": "2023-06-01",
2647
+ "anthropic-dangerous-direct-browser-access": "true"
2648
+ },
2649
+ body: JSON.stringify({
2650
+ model: o,
2651
+ messages: [{ role: "user", content: t }],
2652
+ max_tokens: i,
2653
+ // REQUIRED by Anthropic
2654
+ temperature: s,
2655
+ stream: !0
2656
+ })
2657
+ });
2658
+ if (!c.ok) {
2659
+ const g = await c.text();
2660
+ console.error("🔴 RAW ANTHROPIC STREAM ERROR:", c.status, g), console.error("🔴 Request was made to:", `${l}/messages`), console.error("🔴 Model requested:", o);
2661
+ try {
2662
+ const E = JSON.parse(g);
2663
+ throw new Error(`Anthropic ${c.status}: ${((p = E.error) == null ? void 0 : p.message) || JSON.stringify(E)}`);
2664
+ } catch {
2665
+ throw new Error(`Anthropic ${c.status}: ${g}`);
2666
+ }
2667
+ }
2668
+ if (!c.body) throw new Error("No response body for streaming");
2669
+ const u = c.body.getReader(), m = new TextDecoder();
2670
+ let d = "";
2671
+ try {
2672
+ for (; ; ) {
2673
+ const { done: g, value: E } = await u.read();
2674
+ if (g) break;
2675
+ d += m.decode(E, { stream: !0 });
2676
+ const f = d.split(`
2677
+ `);
2678
+ d = f.pop() || "";
2679
+ for (const w of f) {
2680
+ const A = w.trim();
2681
+ if (!A || !A.startsWith("data: ")) continue;
2682
+ const S = A.slice(6);
2683
+ try {
2684
+ const b = JSON.parse(S);
2685
+ b.type === "content_block_delta" && ((h = b.delta) != null && h.text) && (yield b.delta.text);
2686
+ } catch {
2687
+ continue;
2688
+ }
2689
+ }
2690
+ }
2691
+ } finally {
2692
+ u.releaseLock();
2693
+ }
2694
+ }
2695
+ /**
2696
+ * NOTE ON THE SIGNATURE
2697
+ *
2698
+ * This took `(prompt, config)` while the AiProvider interface — and every
2699
+ * other adapter — declares `(prompt, schema, config)`. Because `schema` is
2700
+ * typed `unknown`, TypeScript accepted the mismatch at the call site, so
2701
+ * AiGatewayService.generateObject() passed the schema where config belonged.
2702
+ * Destructuring `apiKey` off a schema yields undefined, and the call died
2703
+ * with "Anthropic API key required" — a message pointing at configuration for
2704
+ * a fault that was arity. Structured output was broken on this provider for
2705
+ * anyone who used the gateway.
2706
+ *
2707
+ * Claude has no native JSON mode, so `schema` is folded into the prompt
2708
+ * rather than sent as a parameter.
2709
+ */
2710
+ async generateObject(t, n, r) {
2711
+ var f, w, A;
2712
+ const {
2713
+ apiKey: o,
2714
+ model: s = T.anthropic,
2715
+ temperature: i = 0.7,
2716
+ maxTokens: l = 4096,
2717
+ baseUrl: c = "https://api.anthropic.com/v1"
2718
+ } = r;
2719
+ if (!o) throw new Error("Anthropic API key required");
2720
+ if (!s) throw new Error("Model is required but was undefined");
2721
+ const u = n ? `
2722
+
2723
+ It must match this shape:
2724
+ ${JSON.stringify(n)}` : "", m = `${t}${u}
2725
+
2726
+ IMPORTANT: Respond ONLY with valid JSON. No markdown, no explanation, just the JSON object.`, d = await fetch(`${c}/messages`, {
2727
+ method: "POST",
2728
+ headers: {
2729
+ "Content-Type": "application/json",
2730
+ "x-api-key": o,
2731
+ "anthropic-version": "2023-06-01",
2732
+ "anthropic-dangerous-direct-browser-access": "true"
2733
+ },
2734
+ body: JSON.stringify({
2735
+ model: s,
2736
+ messages: [{ role: "user", content: m }],
2737
+ max_tokens: l,
2738
+ // REQUIRED by Anthropic
2739
+ temperature: i
2740
+ })
2741
+ });
2742
+ if (!d.ok) {
2743
+ const S = await d.text();
2744
+ console.error("🔴 RAW ANTHROPIC OBJECT ERROR:", d.status, S), console.error("🔴 Request was made to:", `${c}/messages`), console.error("🔴 Model requested:", s);
2745
+ try {
2746
+ const b = JSON.parse(S);
2747
+ throw new Error(`Anthropic ${d.status}: ${((f = b.error) == null ? void 0 : f.message) || JSON.stringify(b)}`);
2748
+ } catch {
2749
+ throw new Error(`Anthropic ${d.status}: ${S}`);
2750
+ }
2751
+ }
2752
+ const h = ((A = (w = (await d.json()).content) == null ? void 0 : w[0]) == null ? void 0 : A.text) || "{}", g = h.match(/\{[\s\S]*\}/), E = g ? g[0] : h;
2753
+ return JSON.parse(E);
2754
+ }
2755
+ async listModels(t, n) {
2756
+ return [...oe.anthropic];
2757
+ }
2758
+ normalizeError(t, n) {
2759
+ var s;
2760
+ const r = ((s = n.error) == null ? void 0 : s.message) || n.message || "Anthropic request failed";
2761
+ if (t === 429) {
2762
+ const i = new Error(`Rate limit exceeded: ${r}`);
2763
+ return i.code = "RATE_LIMIT_EXCEEDED", i.status = 429, i;
2764
+ }
2765
+ if (t === 401 || t === 403) {
2766
+ const i = new Error(`Authentication failed: ${r}`);
2767
+ return i.code = "AUTH_ERROR", i.status = t, i;
2768
+ }
2769
+ if (t === 400) {
2770
+ const i = new Error(`Bad request: ${r}`);
2771
+ return i.code = "INVALID_REQUEST", i.status = 400, i;
2772
+ }
2773
+ const o = new Error(r);
2774
+ return o.code = "API_ERROR", o.status = t, o;
2775
+ }
2776
+ }
2777
+ function B(a) {
2778
+ if (!(!a || a.length === 0))
2779
+ return a.map((t) => ({
2780
+ type: "function",
2781
+ function: { name: t.name, description: t.description, parameters: t.parameters }
2782
+ }));
2783
+ }
2784
+ async function* ie(a, t, n, r) {
2785
+ var u, m, d, p;
2786
+ const o = await fetch(a, {
2787
+ method: "POST",
2788
+ headers: t,
2789
+ body: JSON.stringify(n)
2790
+ });
2791
+ if (!o.ok) {
2792
+ const h = await o.json().catch(() => ({}));
2793
+ throw r(o.status, h);
2794
+ }
2795
+ if (!o.body) throw new Error("No response body for streaming");
2796
+ const s = o.body.getReader(), i = new TextDecoder();
2797
+ let l = "";
2798
+ const c = /* @__PURE__ */ new Map();
2799
+ try {
2800
+ for (; ; ) {
2801
+ const { done: h, value: g } = await s.read();
2802
+ if (h) break;
2803
+ l += i.decode(g, { stream: !0 });
2804
+ const E = l.split(`
2805
+ `);
2806
+ l = E.pop() || "";
2807
+ for (const f of E) {
2808
+ const w = f.trim();
2809
+ if (!w || !w.startsWith("data: ")) continue;
2810
+ const A = w.slice(6);
2811
+ if (A !== "[DONE]")
2812
+ try {
2813
+ const b = (m = (u = JSON.parse(A).choices) == null ? void 0 : u[0]) == null ? void 0 : m.delta;
2814
+ if (!b) continue;
2815
+ if (b.content && (yield { type: "text-delta", text: b.content }), b.tool_calls)
2816
+ for (const v of b.tool_calls) {
2817
+ const N = v.index ?? 0, C = c.get(N) ?? { name: "", args: "" };
2818
+ v.id && (C.id = v.id), (d = v.function) != null && d.name && (C.name += v.function.name), (p = v.function) != null && p.arguments && (C.args += v.function.arguments), c.set(N, C);
2819
+ }
2820
+ } catch {
2821
+ }
2822
+ }
2823
+ }
2824
+ } finally {
2825
+ s.releaseLock();
2826
+ }
2827
+ for (const h of c.values())
2828
+ if (h.name)
2829
+ try {
2830
+ yield {
2831
+ type: "tool-call",
2832
+ toolCall: {
2833
+ id: h.id,
2834
+ name: h.name,
2835
+ arguments: h.args ? JSON.parse(h.args) : {}
2836
+ }
2837
+ };
2838
+ } catch {
2839
+ }
2840
+ }
2841
+ function se(a) {
2842
+ return a.map((t) => ({ role: t.role, content: t.content }));
2843
+ }
2844
+ class yr {
2845
+ async *streamChat(t, n, r) {
2846
+ const { apiKey: o, model: s = T.openai, temperature: i = 0.7, baseUrl: l = "https://api.openai.com/v1" } = n;
2847
+ if (!o) throw new Error("OpenAI API key required");
2848
+ yield* ie(
2849
+ `${l}/chat/completions`,
2850
+ { "Content-Type": "application/json", Authorization: `Bearer ${o}` },
2851
+ {
2852
+ model: s,
2853
+ messages: se(t),
2854
+ temperature: i,
2855
+ stream: !0,
2856
+ ...B(r) && { tools: B(r), tool_choice: "auto" }
2857
+ },
2858
+ this.normalizeError
2859
+ );
2860
+ }
2861
+ async generateText(t, n) {
2862
+ var u, m, d;
2863
+ const { apiKey: r, model: o = T.openai, temperature: s = 0.7, baseUrl: i = "https://api.openai.com/v1" } = n;
2864
+ if (!r) throw new Error("OpenAI API key required");
2865
+ const l = await fetch(`${i}/chat/completions`, {
2866
+ method: "POST",
2867
+ headers: {
2868
+ "Content-Type": "application/json",
2869
+ Authorization: `Bearer ${r}`
2870
+ },
2871
+ body: JSON.stringify({
2872
+ model: o,
2873
+ messages: [{ role: "user", content: t }],
2874
+ temperature: s
2875
+ })
2876
+ });
2877
+ if (!l.ok) {
2878
+ const p = await l.json();
2879
+ throw this.normalizeError(l.status, p);
2880
+ }
2881
+ return ((d = (m = (u = (await l.json()).choices) == null ? void 0 : u[0]) == null ? void 0 : m.message) == null ? void 0 : d.content) || "";
2882
+ }
2883
+ async *streamText(t, n) {
2884
+ var d, p, h;
2885
+ const { apiKey: r, model: o = T.openai, temperature: s = 0.7, baseUrl: i = "https://api.openai.com/v1" } = n;
2886
+ if (!r) throw new Error("OpenAI API key required");
2887
+ const l = await fetch(`${i}/chat/completions`, {
2888
+ method: "POST",
2889
+ headers: {
2890
+ "Content-Type": "application/json",
2891
+ Authorization: `Bearer ${r}`
2892
+ },
2893
+ body: JSON.stringify({
2894
+ model: o,
2895
+ messages: [{ role: "user", content: t }],
2896
+ temperature: s,
2897
+ stream: !0
2898
+ })
2899
+ });
2900
+ if (!l.ok) {
2901
+ const g = await l.json();
2902
+ throw this.normalizeError(l.status, g);
2903
+ }
2904
+ if (!l.body) throw new Error("No response body for streaming");
2905
+ const c = l.body.getReader(), u = new TextDecoder();
2906
+ let m = "";
2907
+ try {
2908
+ for (; ; ) {
2909
+ const { done: g, value: E } = await c.read();
2910
+ if (g) break;
2911
+ m += u.decode(E, { stream: !0 });
2912
+ const f = m.split(`
2913
+ `);
2914
+ m = f.pop() || "";
2915
+ for (const w of f) {
2916
+ const A = w.trim();
2917
+ if (!A || !A.startsWith("data: ")) continue;
2918
+ const S = A.slice(6);
2919
+ if (S !== "[DONE]")
2920
+ try {
2921
+ const v = (h = (p = (d = JSON.parse(S).choices) == null ? void 0 : d[0]) == null ? void 0 : p.delta) == null ? void 0 : h.content;
2922
+ v && (yield v);
2923
+ } catch {
2924
+ }
2925
+ }
2926
+ }
2927
+ } finally {
2928
+ c.releaseLock();
2929
+ }
2930
+ }
2931
+ async generateObject(t, n, r) {
2932
+ var d, p, h;
2933
+ const { apiKey: o, model: s = T.openai, temperature: i = 0.7, baseUrl: l = "https://api.openai.com/v1" } = r;
2934
+ if (!o) throw new Error("OpenAI API key required");
2935
+ const c = await fetch(`${l}/chat/completions`, {
2936
+ method: "POST",
2937
+ headers: {
2938
+ "Content-Type": "application/json",
2939
+ Authorization: `Bearer ${o}`
2940
+ },
2941
+ body: JSON.stringify({
2942
+ model: s,
2943
+ messages: [{ role: "user", content: t }],
2944
+ response_format: { type: "json_object" },
2945
+ temperature: i
2946
+ })
2947
+ });
2948
+ if (!c.ok) {
2949
+ const g = await c.json();
2950
+ throw this.normalizeError(c.status, g);
2951
+ }
2952
+ const m = ((h = (p = (d = (await c.json()).choices) == null ? void 0 : d[0]) == null ? void 0 : p.message) == null ? void 0 : h.content) || "{}";
2953
+ return JSON.parse(m);
2954
+ }
2955
+ async listModels(t, n) {
2956
+ var i, l;
2957
+ const r = n || "https://api.openai.com/v1";
2958
+ if (!t) throw new Error("OpenAI API key required");
2959
+ const o = await fetch(`${r}/models`, {
2960
+ headers: {
2961
+ Authorization: `Bearer ${t}`
2962
+ }
2963
+ });
2964
+ if (!o.ok) {
2965
+ const c = await o.json();
2966
+ throw this.normalizeError(o.status, c);
2967
+ }
2968
+ return ((l = (i = (await o.json()).data) == null ? void 0 : i.filter((c) => c.id.startsWith("gpt-"))) == null ? void 0 : l.map((c) => c.id)) || [];
2969
+ }
2970
+ normalizeError(t, n) {
2971
+ var s;
2972
+ const r = ((s = n.error) == null ? void 0 : s.message) || n.message || "OpenAI request failed";
2973
+ if (t === 429) {
2974
+ const i = new Error(`Rate limit exceeded: ${r}`);
2975
+ return i.code = "RATE_LIMIT_EXCEEDED", i.status = 429, i;
2976
+ }
2977
+ if (t === 401 || t === 403) {
2978
+ const i = new Error(`Authentication failed: ${r}`);
2979
+ return i.code = "AUTH_ERROR", i.status = t, i;
2980
+ }
2981
+ const o = new Error(r);
2982
+ return o.code = "API_ERROR", o.status = t, o;
2983
+ }
2984
+ }
2985
+ class br {
2986
+ async *streamChat(t, n, r) {
2987
+ const { apiKey: o, model: s = T.grok, temperature: i = 0.7, baseUrl: l = "https://api.x.ai/v1" } = n;
2988
+ if (!o) throw new Error("Grok API key required");
2989
+ yield* ie(
2990
+ `${l}/chat/completions`,
2991
+ { "Content-Type": "application/json", Authorization: `Bearer ${o}` },
2992
+ {
2993
+ model: s,
2994
+ messages: se(t),
2995
+ temperature: i,
2996
+ stream: !0,
2997
+ ...B(r) && { tools: B(r), tool_choice: "auto" }
2998
+ },
2999
+ this.normalizeError
3000
+ );
3001
+ }
3002
+ async generateText(t, n) {
3003
+ var u, m, d;
3004
+ const { apiKey: r, model: o = T.grok, temperature: s = 0.7, baseUrl: i = "https://api.x.ai/v1" } = n;
3005
+ if (!r) throw new Error("Grok API key required");
3006
+ const l = await fetch(`${i}/chat/completions`, {
3007
+ method: "POST",
3008
+ headers: {
3009
+ "Content-Type": "application/json",
3010
+ Authorization: `Bearer ${r}`
3011
+ },
3012
+ body: JSON.stringify({
3013
+ model: o,
3014
+ messages: [{ role: "user", content: t }],
3015
+ temperature: s
3016
+ })
3017
+ });
3018
+ if (!l.ok) {
3019
+ const p = await l.json();
3020
+ throw this.normalizeError(l.status, p);
3021
+ }
3022
+ return ((d = (m = (u = (await l.json()).choices) == null ? void 0 : u[0]) == null ? void 0 : m.message) == null ? void 0 : d.content) || "";
3023
+ }
3024
+ async *streamText(t, n) {
3025
+ var d, p, h;
3026
+ const { apiKey: r, model: o = T.grok, temperature: s = 0.7, baseUrl: i = "https://api.x.ai/v1" } = n;
3027
+ if (!r) throw new Error("Grok API key required");
3028
+ const l = await fetch(`${i}/chat/completions`, {
3029
+ method: "POST",
3030
+ headers: {
3031
+ "Content-Type": "application/json",
3032
+ Authorization: `Bearer ${r}`
3033
+ },
3034
+ body: JSON.stringify({
3035
+ model: o,
3036
+ messages: [{ role: "user", content: t }],
3037
+ temperature: s,
3038
+ stream: !0
3039
+ })
3040
+ });
3041
+ if (!l.ok) {
3042
+ const g = await l.json();
3043
+ throw this.normalizeError(l.status, g);
3044
+ }
3045
+ if (!l.body) throw new Error("No response body for streaming");
3046
+ const c = l.body.getReader(), u = new TextDecoder();
3047
+ let m = "";
3048
+ try {
3049
+ for (; ; ) {
3050
+ const { done: g, value: E } = await c.read();
3051
+ if (g) break;
3052
+ m += u.decode(E, { stream: !0 });
3053
+ const f = m.split(`
3054
+ `);
3055
+ m = f.pop() || "";
3056
+ for (const w of f) {
3057
+ const A = w.trim();
3058
+ if (!A || !A.startsWith("data: ")) continue;
3059
+ const S = A.slice(6);
3060
+ if (S !== "[DONE]")
3061
+ try {
3062
+ const v = (h = (p = (d = JSON.parse(S).choices) == null ? void 0 : d[0]) == null ? void 0 : p.delta) == null ? void 0 : h.content;
3063
+ v && (yield v);
3064
+ } catch {
3065
+ }
3066
+ }
3067
+ }
3068
+ } finally {
3069
+ c.releaseLock();
3070
+ }
3071
+ }
3072
+ async generateObject(t, n, r) {
3073
+ var g, E, f;
3074
+ const { apiKey: o, model: s = T.grok, temperature: i = 0.7, baseUrl: l = "https://api.x.ai/v1" } = r;
3075
+ if (!o) throw new Error("Grok API key required");
3076
+ const c = `${t}
3077
+
3078
+ Respond with valid JSON only.`, u = await fetch(`${l}/chat/completions`, {
3079
+ method: "POST",
3080
+ headers: {
3081
+ "Content-Type": "application/json",
3082
+ Authorization: `Bearer ${o}`
3083
+ },
3084
+ body: JSON.stringify({
3085
+ model: s,
3086
+ messages: [{ role: "user", content: c }],
3087
+ temperature: i
3088
+ })
3089
+ });
3090
+ if (!u.ok) {
3091
+ const w = await u.json();
3092
+ throw this.normalizeError(u.status, w);
3093
+ }
3094
+ const d = ((f = (E = (g = (await u.json()).choices) == null ? void 0 : g[0]) == null ? void 0 : E.message) == null ? void 0 : f.content) || "{}", p = d.match(/\{[\s\S]*\}/), h = p ? p[0] : d;
3095
+ return JSON.parse(h);
3096
+ }
3097
+ async listModels(t, n) {
3098
+ return [...oe.grok];
3099
+ }
3100
+ normalizeError(t, n) {
3101
+ var s;
3102
+ const r = ((s = n.error) == null ? void 0 : s.message) || n.message || "Grok request failed";
3103
+ if (t === 429) {
3104
+ const i = new Error(`Rate limit exceeded: ${r}`);
3105
+ return i.code = "RATE_LIMIT_EXCEEDED", i.status = 429, i;
3106
+ }
3107
+ if (t === 401 || t === 403) {
3108
+ const i = new Error(`Authentication failed: ${r}`);
3109
+ return i.code = "AUTH_ERROR", i.status = t, i;
3110
+ }
3111
+ const o = new Error(r);
3112
+ return o.code = "API_ERROR", o.status = t, o;
3113
+ }
3114
+ }
3115
+ class wr {
3116
+ async *streamChat(t, n, r) {
3117
+ const { apiKey: o, model: s = T.deepseek, temperature: i = 0.7, baseUrl: l = "https://api.deepseek.com/v1" } = n;
3118
+ if (!o) throw new Error("DeepSeek API key required");
3119
+ yield* ie(
3120
+ `${l}/chat/completions`,
3121
+ { "Content-Type": "application/json", Authorization: `Bearer ${o}` },
3122
+ {
3123
+ model: s,
3124
+ messages: se(t),
3125
+ temperature: i,
3126
+ stream: !0,
3127
+ ...B(r) && { tools: B(r), tool_choice: "auto" }
3128
+ },
3129
+ this.normalizeError
3130
+ );
3131
+ }
3132
+ async generateText(t, n) {
3133
+ var u, m, d;
3134
+ const { apiKey: r, model: o = T.deepseek, temperature: s = 0.7, baseUrl: i = "https://api.deepseek.com/v1" } = n;
3135
+ if (!r) throw new Error("DeepSeek API key required");
3136
+ const l = await fetch(`${i}/chat/completions`, {
3137
+ method: "POST",
3138
+ headers: {
3139
+ "Content-Type": "application/json",
3140
+ Authorization: `Bearer ${r}`
3141
+ },
3142
+ body: JSON.stringify({
3143
+ model: o,
3144
+ messages: [{ role: "user", content: t }],
3145
+ temperature: s
3146
+ })
3147
+ });
3148
+ if (!l.ok) {
3149
+ const p = await l.json();
3150
+ throw this.normalizeError(l.status, p);
3151
+ }
3152
+ return ((d = (m = (u = (await l.json()).choices) == null ? void 0 : u[0]) == null ? void 0 : m.message) == null ? void 0 : d.content) || "";
3153
+ }
3154
+ async *streamText(t, n) {
3155
+ var d, p, h;
3156
+ const { apiKey: r, model: o = T.deepseek, temperature: s = 0.7, baseUrl: i = "https://api.deepseek.com/v1" } = n;
3157
+ if (!r) throw new Error("DeepSeek API key required");
3158
+ const l = await fetch(`${i}/chat/completions`, {
3159
+ method: "POST",
3160
+ headers: {
3161
+ "Content-Type": "application/json",
3162
+ Authorization: `Bearer ${r}`
3163
+ },
3164
+ body: JSON.stringify({
3165
+ model: o,
3166
+ messages: [{ role: "user", content: t }],
3167
+ temperature: s,
3168
+ stream: !0
3169
+ })
3170
+ });
3171
+ if (!l.ok) {
3172
+ const g = await l.json();
3173
+ throw this.normalizeError(l.status, g);
3174
+ }
3175
+ if (!l.body) throw new Error("No response body for streaming");
3176
+ const c = l.body.getReader(), u = new TextDecoder();
3177
+ let m = "";
3178
+ try {
3179
+ for (; ; ) {
3180
+ const { done: g, value: E } = await c.read();
3181
+ if (g) break;
3182
+ m += u.decode(E, { stream: !0 });
3183
+ const f = m.split(`
3184
+ `);
3185
+ m = f.pop() || "";
3186
+ for (const w of f) {
3187
+ const A = w.trim();
3188
+ if (!A || !A.startsWith("data: ")) continue;
3189
+ const S = A.slice(6);
3190
+ if (S !== "[DONE]")
3191
+ try {
3192
+ const v = (h = (p = (d = JSON.parse(S).choices) == null ? void 0 : d[0]) == null ? void 0 : p.delta) == null ? void 0 : h.content;
3193
+ v && (yield v);
3194
+ } catch {
3195
+ }
3196
+ }
3197
+ }
3198
+ } finally {
3199
+ c.releaseLock();
3200
+ }
3201
+ }
3202
+ async generateObject(t, n, r) {
3203
+ var d, p, h;
3204
+ const { apiKey: o, model: s = T.deepseek, temperature: i = 0.7, baseUrl: l = "https://api.deepseek.com/v1" } = r;
3205
+ if (!o) throw new Error("DeepSeek API key required");
3206
+ const c = await fetch(`${l}/chat/completions`, {
3207
+ method: "POST",
3208
+ headers: {
3209
+ "Content-Type": "application/json",
3210
+ Authorization: `Bearer ${o}`
3211
+ },
3212
+ body: JSON.stringify({
3213
+ model: s,
3214
+ messages: [{ role: "user", content: t }],
3215
+ response_format: { type: "json_object" },
3216
+ temperature: i
3217
+ })
3218
+ });
3219
+ if (!c.ok) {
3220
+ const g = await c.json();
3221
+ throw this.normalizeError(c.status, g);
3222
+ }
3223
+ const m = ((h = (p = (d = (await c.json()).choices) == null ? void 0 : d[0]) == null ? void 0 : p.message) == null ? void 0 : h.content) || "{}";
3224
+ return JSON.parse(m);
3225
+ }
3226
+ async listModels(t, n) {
3227
+ return [...oe.deepseek];
3228
+ }
3229
+ normalizeError(t, n) {
3230
+ var s;
3231
+ const r = ((s = n.error) == null ? void 0 : s.message) || n.message || "DeepSeek request failed";
3232
+ if (t === 429) {
3233
+ const i = new Error(`Rate limit exceeded: ${r}`);
3234
+ return i.code = "RATE_LIMIT_EXCEEDED", i.status = 429, i;
3235
+ }
3236
+ if (t === 401 || t === 403) {
3237
+ const i = new Error(`Authentication failed: ${r}`);
3238
+ return i.code = "AUTH_ERROR", i.status = t, i;
3239
+ }
3240
+ const o = new Error(r);
3241
+ return o.code = "API_ERROR", o.status = t, o;
3242
+ }
3243
+ }
3244
+ let Er = class {
3245
+ constructor(t) {
3246
+ this.requests = [], this.config = t;
3247
+ }
3248
+ checkLimit() {
3249
+ const t = Date.now(), n = t - this.config.windowMs;
3250
+ return this.requests = this.requests.filter((r) => r > n), this.requests.length >= this.config.maxRequests ? !1 : (this.requests.push(t), !0);
3251
+ }
3252
+ getRemainingRequests() {
3253
+ const n = Date.now() - this.config.windowMs;
3254
+ return this.requests = this.requests.filter((r) => r > n), Math.max(0, this.config.maxRequests - this.requests.length);
3255
+ }
3256
+ getResetTime() {
3257
+ return this.requests.length === 0 ? 0 : this.requests[0] + this.config.windowMs;
3258
+ }
3259
+ };
3260
+ class L {
3261
+ constructor() {
3262
+ this.rateLimiter = new Er({
3263
+ maxRequests: 10,
3264
+ windowMs: 6e4
3265
+ }), this.adapters = /* @__PURE__ */ new Map([
3266
+ ["google-gemini", new hr()],
3267
+ ["ollama", new gr()],
3268
+ ["anthropic", new fr()],
3269
+ ["openai", new yr()],
3270
+ ["grok", new br()],
3271
+ ["deepseek", new wr()]
3272
+ ]);
3273
+ }
3274
+ static getInstance() {
3275
+ return L.instance || (L.instance = new L()), L.instance;
3276
+ }
3277
+ /**
3278
+ * Generate text with rate limiting and error handling
3279
+ */
3280
+ async generateText(t, n) {
3281
+ if (!this.rateLimiter.checkLimit()) {
3282
+ const o = this.rateLimiter.getResetTime(), s = new Error("Rate limit exceeded. Please wait before making another request.");
3283
+ throw s.code = "RATE_LIMIT_EXCEEDED", s.resetTime = o, s;
3284
+ }
3285
+ const r = this.adapters.get(n.provider);
3286
+ if (!r)
3287
+ throw new Error(`Provider ${n.provider} not supported yet.`);
3288
+ try {
3289
+ return await r.generateText(t, n);
3290
+ } catch (o) {
3291
+ throw console.error("[AiGateway] Error:", o), o;
3292
+ }
3293
+ }
3294
+ /**
3295
+ * Stream text generation
3296
+ */
3297
+ async *streamText(t, n) {
3298
+ if (!this.rateLimiter.checkLimit()) {
3299
+ const o = new Error("Rate limit exceeded");
3300
+ throw o.code = "RATE_LIMIT_EXCEEDED", o;
3301
+ }
3302
+ const r = this.adapters.get(n.provider);
3303
+ if (!r)
3304
+ throw new Error(`Provider ${n.provider} not supported yet.`);
3305
+ yield* r.streamText(t, n);
3306
+ }
3307
+ /**
3308
+ * Multi-turn chat streaming with optional native tool/function-calling.
3309
+ * Additive alongside streamText — does not touch its prompt-flattened path.
3310
+ */
3311
+ async *streamChat(t, n, r) {
3312
+ if (!this.rateLimiter.checkLimit()) {
3313
+ const s = new Error("Rate limit exceeded");
3314
+ throw s.code = "RATE_LIMIT_EXCEEDED", s;
3315
+ }
3316
+ const o = this.adapters.get(n.provider);
3317
+ if (!o)
3318
+ throw new Error(`Provider ${n.provider} not supported yet.`);
3319
+ if (!o.streamChat)
3320
+ throw new Error(`Provider ${n.provider} does not implement native chat streaming yet.`);
3321
+ yield* o.streamChat(t, n, r);
3322
+ }
3323
+ /**
3324
+ * Generate structured object (JSON mode)
3325
+ */
3326
+ async generateObject(t, n, r) {
3327
+ if (!this.rateLimiter.checkLimit()) {
3328
+ const s = new Error("Rate limit exceeded");
3329
+ throw s.code = "RATE_LIMIT_EXCEEDED", s;
3330
+ }
3331
+ const o = this.adapters.get(r.provider);
3332
+ if (!o)
3333
+ throw new Error(`Provider ${r.provider} not supported yet.`);
3334
+ return o.generateObject(t, n, r);
3335
+ }
3336
+ /**
3337
+ * Get remaining requests before rate limit
3338
+ */
3339
+ getRemainingRequests() {
3340
+ return this.rateLimiter.getRemainingRequests();
3341
+ }
3342
+ /**
3343
+ * List available models for a provider
3344
+ */
3345
+ async listModels(t, n, r) {
3346
+ const o = this.adapters.get(t);
3347
+ if (!o)
3348
+ throw new Error(`Provider ${t} not supported yet.`);
3349
+ return o.listModels(n, r);
3350
+ }
3351
+ }
3352
+ const zr = L.getInstance(), M = {};
3353
+ class Vr {
3354
+ /**
3355
+ * Resolve configuration with 3-tier priority:
3356
+ * 1. User's localStorage override (highest priority)
3357
+ * 2. App-level .env defaults
3358
+ * 3. System defaults (fallback)
3359
+ */
3360
+ static resolve(t, n) {
3361
+ const r = (t == null ? void 0 : t.provider) || (n == null ? void 0 : n.provider) || "ollama", o = (t == null ? void 0 : t.model) || (n == null ? void 0 : n.model) || this.getDefaultModel(r), s = (t == null ? void 0 : t.apiKey) || (n == null ? void 0 : n.apiKey), i = (t == null ? void 0 : t.ollamaUrl) || (n == null ? void 0 : n.ollamaUrl) || "/ollama";
3362
+ if (r !== "ollama" && !s)
3363
+ throw new Error(`API key required for provider: ${r}`);
3364
+ return {
3365
+ provider: r,
3366
+ model: o,
3367
+ apiKey: s,
3368
+ baseUrl: r === "ollama" ? i : void 0
3369
+ };
3370
+ }
3371
+ static getDefaultModel(t) {
3372
+ return T[t];
3373
+ }
3374
+ /**
3375
+ * Load user preferences from localStorage (client-side)
3376
+ */
3377
+ static loadUserConfig() {
3378
+ if (!(typeof window > "u"))
3379
+ return {
3380
+ provider: localStorage.getItem("app_ai_provider"),
3381
+ model: localStorage.getItem("app_ai_model") || void 0,
3382
+ apiKey: localStorage.getItem("app_ai_api_key") || void 0,
3383
+ ollamaUrl: localStorage.getItem("app_ollama_url") || void 0
3384
+ };
3385
+ }
3386
+ /**
3387
+ * Returns the env key for a specific provider — for REQUEST FLOW ONLY.
3388
+ * Never call this from UI components; use hasEnvKey() for status badges.
3389
+ */
3390
+ static getEnvKeyForProvider(t) {
3391
+ var r, o, s, i, l;
3392
+ if (typeof import.meta < "u" && M) {
3393
+ const c = M, u = (d) => (d == null ? void 0 : d.trim()) || void 0;
3394
+ return {
3395
+ "google-gemini": u(c == null ? void 0 : c.VITE_DEFAULT_GEMINI_KEY),
3396
+ openai: u(c == null ? void 0 : c.VITE_DEFAULT_OPENAI_KEY),
3397
+ anthropic: u(c == null ? void 0 : c.VITE_DEFAULT_ANTHROPIC_KEY),
3398
+ grok: u(c == null ? void 0 : c.VITE_DEFAULT_GROK_KEY),
3399
+ deepseek: u(c == null ? void 0 : c.VITE_DEFAULT_DEEPSEEK_KEY)
3400
+ }[t];
3401
+ }
3402
+ if (typeof process < "u" && process.env)
3403
+ return {
3404
+ "google-gemini": (r = process.env.VITE_DEFAULT_GEMINI_KEY) == null ? void 0 : r.trim(),
3405
+ openai: (o = process.env.VITE_DEFAULT_OPENAI_KEY) == null ? void 0 : o.trim(),
3406
+ anthropic: (s = process.env.VITE_DEFAULT_ANTHROPIC_KEY) == null ? void 0 : s.trim(),
3407
+ grok: (i = process.env.VITE_DEFAULT_GROK_KEY) == null ? void 0 : i.trim(),
3408
+ deepseek: (l = process.env.VITE_DEFAULT_DEEPSEEK_KEY) == null ? void 0 : l.trim()
3409
+ }[t];
3410
+ }
3411
+ /**
3412
+ * Returns true if an env key exists for the given provider — boolean only,
3413
+ * value never exposed. Safe to call from UI components for status badges.
3414
+ */
3415
+ static hasEnvKey(t) {
3416
+ if (typeof import.meta < "u" && M) {
3417
+ const r = M, o = (i) => (i == null ? void 0 : i.trim()) || void 0;
3418
+ return !!{
3419
+ "google-gemini": o(r == null ? void 0 : r.VITE_DEFAULT_GEMINI_KEY),
3420
+ openai: o(r == null ? void 0 : r.VITE_DEFAULT_OPENAI_KEY),
3421
+ anthropic: o(r == null ? void 0 : r.VITE_DEFAULT_ANTHROPIC_KEY),
3422
+ grok: o(r == null ? void 0 : r.VITE_DEFAULT_GROK_KEY),
3423
+ deepseek: o(r == null ? void 0 : r.VITE_DEFAULT_DEEPSEEK_KEY)
3424
+ }[t];
3425
+ }
3426
+ return typeof process < "u" && process.env ? !!{
3427
+ "google-gemini": process.env.VITE_DEFAULT_GEMINI_KEY || process.env.NEXT_PUBLIC_GEMINI_KEY,
3428
+ openai: process.env.VITE_DEFAULT_OPENAI_KEY || process.env.NEXT_PUBLIC_OPENAI_KEY,
3429
+ anthropic: process.env.VITE_DEFAULT_ANTHROPIC_KEY || process.env.NEXT_PUBLIC_ANTHROPIC_KEY
3430
+ }[t] : !1;
3431
+ }
3432
+ /**
3433
+ * Load app defaults from environment variables
3434
+ * Note: This works differently in Vite vs Next.js
3435
+ */
3436
+ static loadAppDefaults() {
3437
+ var n, r;
3438
+ if (typeof import.meta < "u" && M) {
3439
+ const o = M, s = (o == null ? void 0 : o.VITE_DEFAULT_AI_PROVIDER) || "", i = (d) => (d == null ? void 0 : d.trim()) || void 0, l = {
3440
+ "google-gemini": i(o == null ? void 0 : o.VITE_DEFAULT_GEMINI_KEY),
3441
+ openai: i(o == null ? void 0 : o.VITE_DEFAULT_OPENAI_KEY),
3442
+ anthropic: i(o == null ? void 0 : o.VITE_DEFAULT_ANTHROPIC_KEY),
3443
+ grok: i(o == null ? void 0 : o.VITE_DEFAULT_GROK_KEY),
3444
+ deepseek: i(o == null ? void 0 : o.VITE_DEFAULT_DEEPSEEK_KEY)
3445
+ };
3446
+ let c = s || "ollama";
3447
+ const m = ["google-gemini", "anthropic", "openai", "grok", "deepseek"].filter((d) => !!l[d]);
3448
+ return c === "ollama" && m.length > 0 && (c = m[0]), {
3449
+ provider: c,
3450
+ model: o == null ? void 0 : o.VITE_DEFAULT_AI_MODEL,
3451
+ apiKey: l[c],
3452
+ ollamaUrl: o == null ? void 0 : o.VITE_DEFAULT_OLLAMA_URL
3453
+ };
3454
+ }
3455
+ return typeof process < "u" && process.env ? {
3456
+ provider: (n = process.env) == null ? void 0 : n.NEXT_PUBLIC_DEFAULT_AI_PROVIDER,
3457
+ model: (r = process.env) == null ? void 0 : r.NEXT_PUBLIC_DEFAULT_AI_MODEL
3458
+ } : {};
3459
+ }
3460
+ }
3461
+ const Ar = (a) => {
3462
+ let t = "";
3463
+ for (const n of a) t += String.fromCharCode(n);
3464
+ return btoa(t);
3465
+ }, xr = (a) => Uint8Array.from(atob(a), (t) => t.charCodeAt(0)), vr = (a) => {
3466
+ if (a === "." || a === " " || a === "_") return 0;
3467
+ const t = parseInt(a, 16);
3468
+ return Number.isNaN(t) ? -1 : t;
3469
+ }, kr = (a, t) => {
3470
+ if (t.length === 0) return { ok: !1, error: "palette is empty" };
3471
+ if (t.length > 16)
3472
+ return { ok: !1, error: `palette has ${t.length} colours and a sprite holds at most 16` };
3473
+ const n = a.split(`
3474
+ `).map((c) => c.trim()).filter((c) => c.length > 0);
3475
+ if (n.length === 0) return { ok: !1, error: "grid has no rows" };
3476
+ const r = n.length, o = n[0].length;
3477
+ if (o > $ || r > $)
3478
+ return {
3479
+ ok: !1,
3480
+ error: `grid is ${o}x${r} and the largest sprite is ${$}x${$}`
3481
+ };
3482
+ const s = n.map((c, u) => ({ i: u, len: c.length })).filter((c) => c.len !== o);
3483
+ if (s.length > 0) {
3484
+ const c = s[0];
3485
+ return {
3486
+ ok: !1,
3487
+ error: `row ${c.i + 1} is ${c.len} characters and row 1 is ${o}. Every row must be the same width (${s.length} row(s) differ).`
3488
+ };
3489
+ }
3490
+ const i = Math.ceil(o / 2), l = new Uint8Array(i * r);
3491
+ for (let c = 0; c < r; c++)
3492
+ for (let u = 0; u < o; u++) {
3493
+ const m = vr(n[c][u]);
3494
+ if (m < 0)
3495
+ return {
3496
+ ok: !1,
3497
+ error: `row ${c + 1}, column ${u + 1}: '${n[c][u]}' is not a hex digit 0-f`
3498
+ };
3499
+ if (m >= t.length)
3500
+ return {
3501
+ ok: !1,
3502
+ error: `row ${c + 1}, column ${u + 1}: index ${m.toString(16)} but the palette has ${t.length} colour(s), so the highest is ${(t.length - 1).toString(16)}`
3503
+ };
3504
+ const d = c * i + (u >> 1);
3505
+ l[d] |= u & 1 ? m : m << 4;
3506
+ }
3507
+ return { ok: !0, sprite: { width: o, height: r, palette: t, pixels: Ar(l) } };
3508
+ }, Jr = (a) => {
3509
+ const t = xr(a.pixels), n = Math.ceil(a.width / 2), r = [];
3510
+ for (let o = 0; o < a.height; o++) {
3511
+ let s = "";
3512
+ for (let i = 0; i < a.width; i++) {
3513
+ const l = t[o * n + (i >> 1)] ?? 0;
3514
+ s += ((i & 1 ? l & 15 : l >> 4) & 15).toString(16);
3515
+ }
3516
+ r.push(s);
3517
+ }
3518
+ return r.join(`
3519
+ `);
3520
+ }, Kr = (a) => {
3521
+ const t = [];
3522
+ if (!a || typeof a != "object") return { value: a, issues: t };
3523
+ const n = a.blocks;
3524
+ if (!Array.isArray(n)) return { value: a, issues: t };
3525
+ const r = (o, s) => {
3526
+ if (!o || typeof o != "object") return o;
3527
+ const i = o;
3528
+ if (Array.isArray(i.children))
3529
+ return { ...i, children: i.children.map((d, p) => r(d, [...s, "children", p])) };
3530
+ if (i.type !== "sprite" || typeof i.grid != "string") return o;
3531
+ const l = Array.isArray(i.palette) ? i.palette : [], c = kr(i.grid, l);
3532
+ if (!c.ok)
3533
+ return t.push({ path: [...s, "grid"], message: c.error }), o;
3534
+ const { grid: u, ...m } = i;
3535
+ return { ...m, ...c.sprite };
3536
+ };
3537
+ return {
3538
+ value: { ...a, blocks: n.map((o, s) => r(o, ["blocks", s])) },
3539
+ issues: t
3540
+ };
3541
+ };
3542
+ class Sr {
3543
+ constructor(t) {
3544
+ this.requests = [], this.config = t;
3545
+ }
3546
+ checkLimit() {
3547
+ const t = Date.now(), n = t - this.config.windowMs;
3548
+ return this.requests = this.requests.filter((r) => r > n), this.requests.length >= this.config.maxRequests ? !1 : (this.requests.push(t), !0);
3549
+ }
3550
+ getRemainingRequests() {
3551
+ const n = Date.now() - this.config.windowMs;
3552
+ return this.requests = this.requests.filter((r) => r > n), Math.max(0, this.config.maxRequests - this.requests.length);
3553
+ }
3554
+ getResetTime() {
3555
+ return this.requests.length === 0 ? 0 : this.requests[0] + this.config.windowMs;
3556
+ }
3557
+ }
3558
+ class _r {
3559
+ constructor(t = { maxRequests: 10, windowMs: 6e4 }) {
3560
+ this.rateLimiter = new Sr(t);
3561
+ }
3562
+ async makeRequest(t, n) {
3563
+ if (!this.rateLimiter.checkLimit()) {
3564
+ const r = this.rateLimiter.getResetTime(), o = new Error("Rate limit exceeded. Please wait before making another request.");
3565
+ throw o.code = "RATE_LIMIT_EXCEEDED", o.resetTime = r, n && n(r), o;
3566
+ }
3567
+ return await t();
3568
+ }
3569
+ getRemainingRequests() {
3570
+ return this.rateLimiter.getRemainingRequests();
3571
+ }
3572
+ }
3573
+ const Yr = new _r({ maxRequests: 10, windowMs: 6e4 });
3574
+ export {
3575
+ Vr as A,
3576
+ je as B,
3577
+ Cr as C,
3578
+ Lr as D,
3579
+ Te as E,
3580
+ Pr as F,
3581
+ hr as G,
3582
+ G as H,
3583
+ Er as I,
3584
+ $r as J,
3585
+ Mr as K,
3586
+ jr as L,
3587
+ gr as O,
3588
+ oe as P,
3589
+ Se as R,
3590
+ $e as S,
3591
+ Ie as T,
3592
+ Pe as W,
3593
+ pt as a,
3594
+ zr as b,
3595
+ Dr as c,
3596
+ Nr as d,
3597
+ Rr as e,
3598
+ Br as f,
3599
+ L as g,
3600
+ Ur as h,
3601
+ _r as i,
3602
+ Yr as j,
3603
+ Ir as k,
3604
+ kr as l,
3605
+ qr as m,
3606
+ Kr as n,
3607
+ fr as o,
3608
+ yr as p,
3609
+ br as q,
3610
+ wr as r,
3611
+ Jr as s,
3612
+ Zr as t,
3613
+ pr as u,
3614
+ ke as v,
3615
+ Oe as w,
3616
+ Re as x,
3617
+ Ne as y,
3618
+ Or as z
3619
+ };