@ramme-io/kernel 7.0.0 → 7.2.0

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