@ramme-io/kernel 7.2.0 → 7.3.1

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