@bivelio/savings-layer 0.2.0 → 0.2.2

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.
package/README.md CHANGED
@@ -28,26 +28,54 @@ then subscribe (**€4 / seat / month** or **€39 / seat / year**, EUR) to get
28
28
  ## Quick start
29
29
 
30
30
  ```ts
31
- import { createSavingsLayer } from "@bivelio/savings-layer";
31
+ import { createSavingsLayer, OpenAICompatibleProvider } from "@bivelio/savings-layer";
32
+
33
+ // Your provider. LLM traffic goes straight to it — BV-SALA never proxies it.
34
+ // Any OpenAI-compatible endpoint works: OpenAI, Azure, vLLM, SGLang, a gateway.
35
+ const provider = new OpenAICompatibleProvider({
36
+ baseUrl: "https://api.openai.com/v1",
37
+ apiKey: process.env.OPENAI_API_KEY,
38
+ });
32
39
 
33
40
  const layer = createSavingsLayer({
34
- provider: yourProvider, // any OpenAI-compatible / self-hosted provider
35
- licenseKey: process.env.BIVELIO_LICENSE_KEY, // required — from your savings.bivelio.com dashboard
36
- licenseServerUrl: "https://savings.bivelio.com", // license check + kill-switch
41
+ provider,
42
+ licenseKey: process.env.BIVELIO_LICENSE_KEY, // required — from your savings.bivelio.com dashboard
43
+ licenseServerUrl: "https://savings.bivelio.com", // license check + kill-switch
37
44
  serviceAccountKey: process.env.BIVELIO_SERVICE_KEY, // seat metering + AUTO-RENEWAL pickup
38
45
  });
39
46
 
40
- const { data, text, report } = await layer.generate({
47
+ const { text, report } = await layer.generate({
41
48
  model: "openai/gpt-4o-mini",
42
49
  messages: [{ role: "user", content: "What is 2 + 2 * 3?" }],
43
- response: { contractId: "answer:v1", schema, maxOutputTokens: 220 },
44
50
  });
45
51
 
46
- console.log(text); // "8" (computed locally — no LLM call)
52
+ console.log(text); // "8" (computed locally — no LLM call)
47
53
  console.log(report.calls.avoidedLlm); // → whole calls you never paid for
48
54
  console.log(report.cost.netSavings); // → verified savings, per request
49
55
  ```
50
56
 
57
+ Ask for a **structured contract** and you also get `data`, validated against your
58
+ schema — the JSON-repair and constrained-decoding levers switch on here:
59
+
60
+ ```ts
61
+ const { data, text } = await layer.generate<{ answer: number }>({
62
+ model: "openai/gpt-4o-mini",
63
+ messages: [{ role: "user", content: "What is 2 + 2 * 3?" }],
64
+ response: {
65
+ contractId: "answer:v1",
66
+ schema: {
67
+ type: "object",
68
+ properties: { answer: { type: "number" } },
69
+ required: ["answer"],
70
+ additionalProperties: false,
71
+ },
72
+ maxOutputTokens: 220,
73
+ },
74
+ });
75
+
76
+ console.log(data.answer); // 8
77
+ ```
78
+
51
79
  The hard requirements are a `provider` and a valid `licenseKey`: BV‑SALA is a paid
52
80
  product and **refuses to run unlicensed, expired, or tampered** (it throws
53
81
  `LicenseError` at the `generate()` entry). Get a key at
@@ -88,10 +116,35 @@ answer: `text` is empty by design and the request is in `toolCalls`. Execute it,
88
116
  append the result to `messages`, and call `generate()` again.
89
117
 
90
118
  ```ts
91
- const res = await layer.generate({ model, messages, tools });
119
+ import type { ToolDescriptor } from "@bivelio/savings-layer";
120
+
121
+ const tools: ToolDescriptor[] = [
122
+ {
123
+ id: "get_weather",
124
+ intents: ["weather", "forecast"],
125
+ risk: "read",
126
+ description: "Current weather for a city",
127
+ parameters: {
128
+ type: "object",
129
+ properties: { city: { type: "string" } },
130
+ required: ["city"],
131
+ additionalProperties: false,
132
+ },
133
+ },
134
+ ];
135
+
136
+ const res = await layer.generate({
137
+ model: "openai/gpt-4o-mini",
138
+ messages: [{ role: "user", content: "What's the weather in Madrid?" }],
139
+ tools,
140
+ });
141
+
92
142
  if (res.toolCalls?.length) {
93
143
  // res.finishReason === "tool_calls"
94
- for (const call of res.toolCalls) await run(call.name, JSON.parse(call.arguments));
144
+ for (const call of res.toolCalls) {
145
+ const args = JSON.parse(call.arguments) as { city: string };
146
+ console.log(call.name, args); // ← run your tool here, then append its result
147
+ }
95
148
  } else {
96
149
  console.log(res.text);
97
150
  }
package/dist/index.d.ts CHANGED
@@ -11,7 +11,8 @@ declare function randomId(): string;
11
11
  /**
12
12
  * The four-ledger savings accounting.
13
13
  *
14
- * These ledgers are kept strictly separate on purpose (see contracts/types.ts).
14
+ * These ledgers are kept strictly separate on purpose: each answers a different
15
+ * question, and summing them would double-count.
15
16
  * The ledger is a pure accumulator: the pipeline records events into it, and it
16
17
  * produces the numbers that populate the SavingsReport. It never guesses — every
17
18
  * increment is driven by an explicit pipeline decision.
@@ -61,24 +62,17 @@ declare class SavingsLedger {
61
62
  /**
62
63
  * ¿El estimador que produjo las dos cifras anteriores cuenta con la regla del
63
64
  * proveedor? Lo fija el pipeline al resolver el tokenizador del modelo.
64
- * Por defecto NO: asumir exactitud sin comprobarla es el fallo que esto cierra.
65
+ * Defaults to NO: exactness is claimed only once it has been verified.
65
66
  */
66
67
  estimatorExact: boolean;
67
68
  /** Salida del reintento de reparación. Es coste NUESTRO, nunca del baseline. */
68
69
  repairOutput: number;
69
70
  /**
70
- * ENTRADA del reintento de reparación. Simétrico de `repairOutput`, y faltaba.
71
+ * INPUT of the repair retry. Mirrors `repairOutput`.
71
72
  *
72
- * El baseline de una llamada ejecutada se reconstruye desde `actualInput`, y
73
- * `actualInput` ya acumula las DOS llamadas (pipeline.ts:623). Sin descontar la
74
- * del reintento, el baseline se inflaba con un coste que es NUESTRO, no del
75
- * cliente: una petición que costó el doble que el camino naive se publicaba con
76
- * ahorro POSITIVO. Medido: netSavings = -0,2857 cuando la verdad era -100 %, y
77
- * con `structuredData` llegaba a +36,4 % — y encima con `basis: 'measured'`,
78
- * que es justo lo que el panel presenta como contrastable con la factura.
79
- *
80
- * Para la salida ya existía la corrección (`baselineOutputHonesto`); para la
81
- * entrada no había nada.
73
+ * Both are OUR cost, never the customer's, so both are subtracted from the
74
+ * reconstructed baseline. The baseline is what the naive path would have
75
+ * cost; work the layer does to fix its own output has no place in it.
82
76
  */
83
77
  repairInput: number;
84
78
  /**
@@ -258,12 +252,9 @@ interface SavingsResult<T = unknown> {
258
252
  * `data` NO son la respuesta final: el modelo devolvió `content` vacío y pide
259
253
  * ejecutar la acción (`finishReason === "tool_calls"`).
260
254
  *
261
- * Faltaba: el adaptador ya propagaba `tool_calls` (content:null + tool_calls es
262
- * el camino NORMAL en cuanto hay herramientas), pero el pipeline construía la
263
- * respuesta solo con `{text, data, rendered}` y este contrato ni declaraba el
264
- * campo — el cliente recibía "" como si fuera la respuesta buena y la
265
- * invocación se perdía entera. La palanca de herramientas que vende el README
266
- * era inservible en el paquete publicado.
255
+ * `content: null` + `tool_calls` is the NORMAL shape as soon as tools are in
256
+ * play, so treat an empty `text` together with a populated `toolCalls` as a
257
+ * tool invocation to execute — not as an empty answer.
267
258
  */
268
259
  toolCalls?: ToolCallRequest[];
269
260
  /**
@@ -390,7 +381,18 @@ interface LicenseGate {
390
381
  * `devUnlicensed: true`, que es explícito y no se cuela sin querer.
391
382
  */
392
383
  isActive(): boolean;
393
- /** Resolved status (active|grace|expired|invalid|revoked), for error messages. */
384
+ /**
385
+ * Resolved status (active|grace|expired|invalid|revoked|stale), for error messages.
386
+ *
387
+ * `stale` es una licencia PAGADA Y VIGENTE que no ha podido confirmarse contra
388
+ * el control plane — un problema de red, no de dinero. Se distingue de
389
+ * `expired` porque el mensaje que se le da al cliente NO puede mandarle a
390
+ * renovar algo que ya tiene pagado.
391
+ *
392
+ * El tipo es `string` y no el union a propósito: un gate lo implementa el
393
+ * llamante y puede devolver cualquier cosa, así que `mensajeDeLicencia` tiene
394
+ * que tener una rama por defecto de todas formas.
395
+ */
394
396
  status?(): string;
395
397
  }
396
398
  interface TraceEvent {
@@ -530,7 +532,7 @@ declare const defaultTokenizerRegistry: TokenizerRegistry;
530
532
  */
531
533
 
532
534
  /** Lo que necesitamos de gpt-tokenizer. Tipado aquí para no depender de sus tipos. */
533
- interface CodificadorBpe {
535
+ interface BpeEncoder {
534
536
  encode(text: string): number[] | {
535
537
  length: number;
536
538
  };
@@ -538,19 +540,19 @@ interface CodificadorBpe {
538
540
  /**
539
541
  * Estimador exacto sobre una codificación BPE ya cargada.
540
542
  *
541
- * Se construye con el codificador ya resuelto en vez de importarlo dentro: así
543
+ * Se construye con el encoder ya resuelto en vez de importarlo dentro: así
542
544
  * este módulo no obliga a nadie a tener el paquete, y quien lo tiene decide qué
543
545
  * codificación carga (o200k_base para gpt-4o/4.1/5, cl100k_base para 3.5/4).
544
546
  */
545
547
  declare class ExactTokenizer implements TokenEstimator {
546
- private readonly codificador;
548
+ private readonly encoder;
547
549
  readonly id: string;
548
550
  readonly exact = true;
549
- constructor(id: string, codificador: CodificadorBpe);
551
+ constructor(id: string, encoder: BpeEncoder);
550
552
  count(text: string): number;
551
553
  }
552
554
  /** Modelos que usan cada codificación. Sirve para mapear el registro de una vez. */
553
- declare const MODELOS_POR_CODIFICACION: Readonly<Record<string, readonly string[]>>;
555
+ declare const MODELS_BY_ENCODING: Readonly<Record<string, readonly string[]>>;
554
556
  /**
555
557
  * Carga `gpt-tokenizer` si está instalado y registra el tokenizador exacto para
556
558
  * los modelos de OpenAI. Devuelve `false` —sin lanzar— cuando no está: la
@@ -561,12 +563,20 @@ declare const MODELOS_POR_CODIFICACION: Readonly<Record<string, readonly string[
561
563
  * expone un punto de entrada por codificación y cargarlas todas serían decenas
562
564
  * de MB en memoria sin motivo.
563
565
  */
564
- declare function registrarTokenizadorExacto(registro: {
566
+ declare function registerExactTokenizer(registro: {
565
567
  register(e: TokenEstimator): unknown;
566
568
  mapModel(model: string, tokenizerId: string): unknown;
567
569
  }, opciones?: {
568
570
  codificaciones?: readonly string[];
569
571
  }): Promise<boolean>;
572
+ /**
573
+ * @deprecated Spanish-named aliases kept for one minor version. Use
574
+ * {@link MODELS_BY_ENCODING} and {@link registerExactTokenizer}. The public
575
+ * surface of this package is English-only; these leaked and are on the way out.
576
+ */
577
+ declare const MODELOS_POR_CODIFICACION: Readonly<Record<string, readonly string[]>>;
578
+ /** @deprecated Use {@link registerExactTokenizer}. */
579
+ declare const registrarTokenizadorExacto: typeof registerExactTokenizer;
570
580
 
571
581
  /**
572
582
  * Canonicalization turns a raw request into a normalized, hashable form. This
@@ -627,14 +637,10 @@ declare function buildExactKey(c: CanonicalRequest): string;
627
637
  * need freshness bucketing, since the work is happening *now*), but must still
628
638
  * isolate tenants and permissions.
629
639
  *
630
- * `schema` NO es opcional aquí, por mucho que ya esté `contract`. Faltaba, y el
631
- * efecto era servirle a un llamante la respuesta de OTRO contrato: dos
632
- * `generate()` concurrentes que solo difieren en `schemaVersion` colapsaban en
633
- * una, y el seguidor recibía el objeto del líder —que viola su esquema— con
634
- * `structurallyValid: true`, porque `asCoalescedFollower` clona el informe del
635
- * líder sin recalcular `constraints` ni pasar por la validación. `buildExactKey`
636
- * ya lo incluía y la caché semántica lo filtra a mano; esta era la única de las
637
- * tres puertas que no lo miraba.
640
+ * `schema` is REQUIRED here, even though `contract` is already part of the key:
641
+ * two concurrent calls that differ only in `schemaVersion` are different
642
+ * requests and must never coalesce. All three doors — exact key, in-flight key
643
+ * and semantic filter — key on the same identity, by design.
638
644
  */
639
645
  declare function buildInflightKey(c: CanonicalRequest): string;
640
646
 
@@ -769,23 +775,20 @@ interface SemanticRecord {
769
775
  knowledgeEpoch: string;
770
776
  contractId: string | null;
771
777
  /**
772
- * QUIÉN hizo la petición (sessionId/principal), o null si es anónima.
778
+ * Who made the request (session/principal), or null when anonymous.
773
779
  *
774
- * Faltaba, y era la fuga más cara: la caché exacta aísla por principal pero la
775
- * semántica no lo miraba, así que dos usuarios distintos del MISMO tenant con
776
- * la misma pregunta casaban por embedding y el segundo recibía la respuesta
777
- * calculada para el primero. `tenantId` separa organizaciones, no personas.
780
+ * Isolation boundary: `tenantId` separates organizations, `principal`
781
+ * separates people within one. Both are hard filters applied BEFORE any
782
+ * similarity scoring — a semantic match never crosses either.
778
783
  */
779
784
  principal: string | null;
780
785
  /**
781
- * Identidad COMPLETA de la petición que produjo esta respuesta.
786
+ * The COMPLETE identity of the request that produced this answer.
782
787
  *
783
- * Antes solo se guardaban tenant, scope, epoch y contrato: la clave exacta
784
- * declara necesarios otros cinco campos, y la semántica los ignoraba. El peor
785
- * era `structuredDataHash` — dos preguntas redactadas igual pero con datos
786
- * ADJUNTOS distintos casan por embedding, así que se servía la respuesta
787
- * calculada sobre la tabla de otro. `model` y `systemPromptHash` van detrás:
788
- * un modelo o un system prompt distintos son otra respuesta.
788
+ * Every field here is a hard filter, checked before similarity is scored, and
789
+ * the set is identical to the one the exact cache keys on. Two questions
790
+ * worded alike but carrying different attached data, a different model or a
791
+ * different system prompt are different questions, and never match.
789
792
  */
790
793
  model: string;
791
794
  systemPromptHash: string;
@@ -1386,13 +1389,10 @@ interface ProviderResponse {
1386
1389
  * Llamadas a herramienta que pidió el modelo, tal cual las devolvió el
1387
1390
  * proveedor.
1388
1391
  *
1389
- * Faltaba, y el adaptador hacía `content ?? ""`: cuando el modelo invoca una
1390
- * herramienta devuelve `content: null` + `tool_calls`, así que la capa entregaba
1391
- * CADENA VACÍA y la petición del modelo se perdía por completo. El pipeline
1392
- * transmite herramientas por diseño y son una palanca que el README vende, de
1393
- * modo que el caso no es exótico: es el camino normal en cuanto hay tools.
1394
- * Mismo tipo que expone `SavingsResult.toolCalls`: el pipeline lo transmite
1395
- * tal cual hasta el llamante (no solo hasta aquí).
1392
+ * When the model invokes a tool it returns `content: null` + `tool_calls`, so
1393
+ * this is the normal shape as soon as tools are in play — not an edge case.
1394
+ * Same type as `SavingsResult.toolCalls`: the pipeline forwards it unchanged
1395
+ * all the way to the caller.
1396
1396
  */
1397
1397
  toolCalls?: ToolCallRequest[];
1398
1398
  raw?: unknown;
@@ -1514,11 +1514,26 @@ declare class LicenseError extends Error {
1514
1514
  * against BiVelio's public key, decode the payload, and apply the same grace
1515
1515
  * policy the license-client uses. Verification is **browser-safe**: it uses
1516
1516
  * `@noble/curves` (pure JS) + Web primitives (`atob`, `TextEncoder`) rather than
1517
- * `node:crypto`, so the shared `src/index.ts` still compiles into the browser
1517
+ * `node:crypto`, so the shared entry point still compiles into the browser
1518
1518
  * demo bundle. The private signing key never leaves the control plane; only the
1519
1519
  * public key is embedded here, so a token cannot be forged or tampered with.
1520
1520
  */
1521
- type LicenseStatus = "active" | "grace" | "expired" | "invalid" | "revoked";
1521
+ /**
1522
+ * `stale` NO es una licencia caducada: es una licencia PAGADA Y VIGENTE que no ha
1523
+ * podido confirmar su estado contra el control plane dentro de la ventana de
1524
+ * frescura — típicamente porque la salida de red está bloqueada.
1525
+ *
1526
+ * Existe porque antes ese caso reutilizaba `expired` "para que el union y todos
1527
+ * los consumidores siguieran igual", y el ahorro de tipo se pagaba con el peor
1528
+ * mensaje posible del producto: a un cliente al día, cuyo único problema era un
1529
+ * cortafuegos, se le decía *"license is not active (expired). Renew your
1530
+ * subscription"*. Le mandábamos a pagar otra vez algo que ya había pagado, y a
1531
+ * mirar donde no estaba el problema.
1532
+ *
1533
+ * El comportamiento no cambia —sigue siendo fail-closed, `granted()` no lo
1534
+ * concede— pero ahora el mensaje puede decir la verdad.
1535
+ */
1536
+ type LicenseStatus = "active" | "grace" | "expired" | "invalid" | "revoked" | "stale";
1522
1537
  /** Decoded license token body (mirror of `@bivelio/protocol`'s LicensePayload,
1523
1538
  * declared locally so the SDK stays free of a control-plane dependency). */
1524
1539
  interface LicenseTokenPayload {
@@ -1711,7 +1726,7 @@ declare function liveGateFromKey(licenseKey: string, publicKey: string | License
1711
1726
  * hole the old one-shot resolution left open. `isActive()` is true while active or
1712
1727
  * in grace; `isEntitled` additionally requires the feature in the token's grant.
1713
1728
  * Online revocation is added by pairing {@link liveGateFromKey} with a
1714
- * poller-fed snapshot (see src/pipeline/create.ts + poller.ts).
1729
+ * poller-fed snapshot, which `createSavingsLayer` wires up for you.
1715
1730
  */
1716
1731
  declare function gateFromKey(licenseKey: string, publicKey: string | LicenseKeyset, now?: () => number): ResolvedGate;
1717
1732
 
@@ -1755,6 +1770,20 @@ interface RevocationPollerOptions {
1755
1770
  random?: () => number;
1756
1771
  /** Optional observer (telemetry/tests). */
1757
1772
  onEvent?: (e: RevocationPollEvent) => void;
1773
+ /**
1774
+ * Silencia los avisos por consola. Por defecto están ENCENDIDOS, y ese defecto
1775
+ * es la corrección: el sondeo es fail-open, así que un call-home roto no rompe
1776
+ * nada visible — la lista de revocaciones simplemente se queda vieja, en
1777
+ * silencio, durante días. Quien tenga observabilidad propia puede apagarlos;
1778
+ * quien no la tenga, que es casi todo el mundo, se entera igual.
1779
+ */
1780
+ silenceWarnings?: boolean;
1781
+ /**
1782
+ * @deprecated Spanish name that leaked into the public options. Use
1783
+ * {@link RevocationPollerOptions.silenceWarnings}. Honoured for one minor
1784
+ * version so nobody gets their warnings back by surprise.
1785
+ */
1786
+ silenciarAvisos?: boolean;
1758
1787
  }
1759
1788
  /**
1760
1789
  * PURE, unit-testable next-delay policy (seconds). Steady state anchors to the
@@ -1793,6 +1822,24 @@ declare class RevocationPoller {
1793
1822
  * last-known-good. Only a transport/abort/parse error counts as a failure.
1794
1823
  */
1795
1824
  pollOnce(): Promise<void>;
1825
+ /** El interruptor, aceptando todavía el nombre viejo. */
1826
+ private callado;
1827
+ /** Un aviso por causa y por proceso, respetando el interruptor. */
1828
+ private avisar;
1829
+ /**
1830
+ * THE CONTROL PLANE HAS BEEN UNREACHABLE FOR A WHILE.
1831
+ *
1832
+ * Polling is fail-open by design: a network outage must never take down the
1833
+ * customer's production traffic. The trade-off is that an unreachable control
1834
+ * plane has no visible symptom — the license keeps working and requests keep
1835
+ * flowing while the revocation list quietly goes stale.
1836
+ *
1837
+ * So the warning goes to the console BY DEFAULT, not only through the optional
1838
+ * `onEvent` observer. It fires on the third consecutive failure and then every
1839
+ * twelfth: a lost request is normal, a week-long outage must keep reminding.
1840
+ * Silence it with `silenceWarnings` if you have your own observability.
1841
+ */
1842
+ private avisarFalloDeRed;
1796
1843
  /** Fire one non-blocking warm poll, then self-schedule. Idempotent. */
1797
1844
  start(): void;
1798
1845
  private schedule;
@@ -1819,6 +1866,14 @@ interface UsageEmitterOptions {
1819
1866
  now?: () => number;
1820
1867
  /** Whether this process is a CI/ephemeral runner (excluded from billable seats). */
1821
1868
  ci?: boolean;
1869
+ /**
1870
+ * Se llama cuando el ingest rechaza la credencial (401/403). Existe para que un
1871
+ * despliegue con observabilidad pueda ENTERARSE: el aviso por consola sirve en
1872
+ * un portátil, pero en producción los `console.warn` no despiertan a nadie, y
1873
+ * este fallo concreto es invisible por definición —deja de llegar uso, que es
1874
+ * exactamente lo mismo que se ve cuando no hay tráfico—.
1875
+ */
1876
+ onAuthError?: (status: number) => void;
1822
1877
  }
1823
1878
  /**
1824
1879
  * Buffers counts-only usage and flushes it to the control plane. DETECTIVE
@@ -2123,20 +2178,13 @@ declare function createSavingsLayer(config: Omit<SavingsLayerConfig, "tokenizer"
2123
2178
  * misleading metrics.
2124
2179
  */
2125
2180
  /**
2126
- * La versión que el SDK declara de sí mismo. Va a mano y NO se lee de
2127
- * package.json a propósito: el bundle publicado no incluye package.json, así que
2128
- * un `require` aquí rompería en tiempo de ejecución en casa del cliente.
2129
- *
2130
- * El precio de escribirla a mano es que se queda atrás — y se quedó: el paquete
2131
- * pasó a 0.2.0 y esto seguía diciendo "0.1.0", que es justamente la versión que
2132
- * vamos a marcar como rota. Todo cliente instalado se habría identificado como
2133
- * la versión defectuosa en soporte y en telemetría, y no habría forma de
2134
- * distinguir a quien ya actualizó de quien no.
2181
+ * The version the SDK reports for itself.
2135
2182
  *
2136
- * Por eso hay un test que la ata a package.json (`test/version-declarada.test.ts`).
2137
- * Si subes la versión del paquete y olvidas esta línea, la suite se pone roja
2138
- * antes de que la Release llegue a npm.
2183
+ * Written by hand and deliberately NOT read from package.json: the published
2184
+ * bundle does not ship package.json, so a `require` here would fail at runtime
2185
+ * on the customer's machine. `test/version-declarada.test.ts` ties this
2186
+ * constant to package.json so the two can never drift.
2139
2187
  */
2140
- declare const BV_SALA_VERSION = "0.2.0";
2188
+ declare const BV_SALA_VERSION = "0.2.2";
2141
2189
 
2142
- export { BV_SALA_VERSION, type BivelioHandoff, type CacheOutcome, type CachedAnswer, type CanonicalRequest, type ChatMessage, type CompactVerification, type CompressionPolicyInput, type CompressionRequest, type CompressionResult, type Compressor, type ConstraintBackend, type ConstraintBackendId, type ConstraintPlan, type ConversationState, type CostBasis, type CostModel, DEFAULT_COST_MODEL, type DeterministicResolver, EMBEDDED_PUBLIC_KEY, type EmbeddingFn, type EvidenceDoc, type ExactCache, ExactTokenizer, type ExecutionClass, ExecutionRouter, type FormatChoice, FormatSelector, type FormatSelectorOptions, type HandoffFact, HeuristicEstimator, InMemoryExactCache, InMemorySemanticCache, type JsonSchema, LicenseError, type LicenseGate, type LicenseKeyset, type LicenseStatus, type LicenseTokenPayload, type LocalClassifier, MODELOS_POR_CODIFICACION, type MemoryDelta, type MessageRole, MockProvider, type MockProviderOptions, type OpenAICompatibleOptions, OpenAICompatibleProvider, type OutputContract, type Policy, type ProtectedSpan, type Provider, type ProviderRequest, type ProviderResponse, type ProviderUsage, type RequestContext, type Reranker, type ResolvedDeps, type ResolvedGate, type ResolvedLicense, ResolverRegistry, type ResolverResult, type RetrievalOptions, type RetrievalOutcome, type RetrievalPlan, type Retriever, type RevocationListBody, type RevocationListVerification, type RevocationPollEvent, RevocationPoller, type RevocationPollerOptions, RevocationSnapshot, type RouteDecision, type SavingsLayer, type SavingsLayerConfig, SavingsLedger, type SavingsReport, type SavingsRequest, type SavingsResult, type SavingsToggles, SchemaRegistry, type SemanticCacheOptions, type SemanticHit, type SemanticRecord, type SemanticVerifier, type SerializationFormat, type Serializer, Singleflight, TOON_INSTRUCTION, type TokenEstimator, TokenizerRegistry, type ToolCallRequest, type ToolDescriptor, type ToolRisk, type ToolSelection, ToolSelector, type ToolSelectorOptions, type ToonDecodeOptions, type ToonOptions, TraceCollector, type TraceEvent, UsageEmitter, type UsageEmitterOptions, type ValidationError, type ValidationResult, adaptiveK, arithmeticResolver, buildExactKey, buildInflightKey, canonicalize, computeNextDelay, cosine, createDefaultResolvers, createHandoff, createMockProvider, createSavingsLayer, createToonSerializer, csvSerializer, decodeToon, dedupe, defaultTokenizerRegistry, deriveSeatId, deriveStatus, detectCi, emptyState, encodeToon, evalArithmetic, evaluatePolicy, executeRetrievalPlan, gateFromKey, heuristicEstimator, isKeyset, isStrictCompatible, jsonCompactSerializer, keyTokensMatch, liveGateFromKey, mergeDelta, noopCompressor, normalizeText, projectContext, providerNativeBackend, randomId, registrarTokenizadorExacto, renderState, resolveConstraintBackend, resolveDependencies, resolveLicense, sha256, shouldCompress, stableStringify, toonSerializer, uniformColumns, validateAgainstSchema, verifyCompactSignature, verifyLicenseToken, verifyRevocationList, withProtectedSpans };
2190
+ export { BV_SALA_VERSION, type BivelioHandoff, type CacheOutcome, type CachedAnswer, type CanonicalRequest, type ChatMessage, type CompactVerification, type CompressionPolicyInput, type CompressionRequest, type CompressionResult, type Compressor, type ConstraintBackend, type ConstraintBackendId, type ConstraintPlan, type ConversationState, type CostBasis, type CostModel, DEFAULT_COST_MODEL, type DeterministicResolver, EMBEDDED_PUBLIC_KEY, type EmbeddingFn, type EvidenceDoc, type ExactCache, ExactTokenizer, type ExecutionClass, ExecutionRouter, type FormatChoice, FormatSelector, type FormatSelectorOptions, type HandoffFact, HeuristicEstimator, InMemoryExactCache, InMemorySemanticCache, type JsonSchema, LicenseError, type LicenseGate, type LicenseKeyset, type LicenseStatus, type LicenseTokenPayload, type LocalClassifier, MODELOS_POR_CODIFICACION, MODELS_BY_ENCODING, type MemoryDelta, type MessageRole, MockProvider, type MockProviderOptions, type OpenAICompatibleOptions, OpenAICompatibleProvider, type OutputContract, type Policy, type ProtectedSpan, type Provider, type ProviderRequest, type ProviderResponse, type ProviderUsage, type RequestContext, type Reranker, type ResolvedDeps, type ResolvedGate, type ResolvedLicense, ResolverRegistry, type ResolverResult, type RetrievalOptions, type RetrievalOutcome, type RetrievalPlan, type Retriever, type RevocationListBody, type RevocationListVerification, type RevocationPollEvent, RevocationPoller, type RevocationPollerOptions, RevocationSnapshot, type RouteDecision, type SavingsLayer, type SavingsLayerConfig, SavingsLedger, type SavingsReport, type SavingsRequest, type SavingsResult, type SavingsToggles, SchemaRegistry, type SemanticCacheOptions, type SemanticHit, type SemanticRecord, type SemanticVerifier, type SerializationFormat, type Serializer, Singleflight, TOON_INSTRUCTION, type TokenEstimator, TokenizerRegistry, type ToolCallRequest, type ToolDescriptor, type ToolRisk, type ToolSelection, ToolSelector, type ToolSelectorOptions, type ToonDecodeOptions, type ToonOptions, TraceCollector, type TraceEvent, UsageEmitter, type UsageEmitterOptions, type ValidationError, type ValidationResult, adaptiveK, arithmeticResolver, buildExactKey, buildInflightKey, canonicalize, computeNextDelay, cosine, createDefaultResolvers, createHandoff, createMockProvider, createSavingsLayer, createToonSerializer, csvSerializer, decodeToon, dedupe, defaultTokenizerRegistry, deriveSeatId, deriveStatus, detectCi, emptyState, encodeToon, evalArithmetic, evaluatePolicy, executeRetrievalPlan, gateFromKey, heuristicEstimator, isKeyset, isStrictCompatible, jsonCompactSerializer, keyTokensMatch, liveGateFromKey, mergeDelta, noopCompressor, normalizeText, projectContext, providerNativeBackend, randomId, registerExactTokenizer, registrarTokenizadorExacto, renderState, resolveConstraintBackend, resolveDependencies, resolveLicense, sha256, shouldCompress, stableStringify, toonSerializer, uniformColumns, validateAgainstSchema, verifyCompactSignature, verifyLicenseToken, verifyRevocationList, withProtectedSpans };
package/dist/index.js CHANGED
@@ -1,21 +1,21 @@
1
- var Kr=0;function bt(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++Kr,o=Date.now?Date.now():0;for(let s=0;s<16;s++)e[s]=(s<6?r>>>s*8:o>>>(s-6)*8)&255;}e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=[];for(let r=0;r<16;r++)n.push(e[r].toString(16).padStart(2,"0"));return `${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}-${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}function Ns(t){return {v:1,task:t.task,goal:t.goal,rules:t.rules??[],facts:t.facts??[],refs:t.refs??[],...t.delta?{delta:t.delta}:{},outputContract:t.outputContract}}var xt=class{id;exact=false;constructor(e="heuristic"){this.id=e;}count(e){if(e.length===0)return 0;let n=e.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],r=0;for(let o of n){let s=o[0];if(/\s/.test(s)){let i=(o.match(/\n/g)??[]).length;r+=i+Math.floor(Math.max(0,o.length-1)/2);}else /[A-Za-z]/.test(s)?r+=Math.max(1,Math.ceil(o.length/4)):/\d/.test(s)?r+=Math.max(1,Math.ceil(o.length/2)):r+=1;}return Math.max(r,Math.ceil(e.length/4))}},me=new xt;var yt=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=me){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){return this.modelToTokenizer.set(e,n),this}resolve(e){let n=e.tokenizer?this.estimators.get(e.tokenizer):void 0;if(n)return n;if(e.model){let r=this.modelToTokenizer.get(e.model);if(r){let o=this.estimators.get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},pn=new yt;var vt=class{constructor(e,n){this.codificador=n;this.id=e;}codificador;id;exact=true;count(e){return e.length===0?0:this.codificador.encode(e).length}},qr={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","o1","o1-mini","o3","o3-mini","o4-mini"],cl100k_base:["gpt-4","gpt-4-turbo","gpt-3.5-turbo","text-embedding-3-small","text-embedding-3-large"]};async function Zs(t,e={}){let n=e.codificaciones??["o200k_base","cl100k_base"],r=false;for(let o of n){let s;try{s=await import(`gpt-tokenizer/encoding/${o}`);}catch{continue}if(typeof s.encode=="function"){t.register(new vt(o,s)),r=true;for(let i of qr[o]??[])t.mapModel(i,o),t.mapModel(`openai/${i}`,o);}}return r}var he=class{avoidedLlm=0;baselineLlm=1;actualLlm=0;baselineRetrieval=0;actualRetrieval=0;baselineTools=0;actualTools=0;retries=0;baselineInput=0;actualInput=0;eliminatedInput=0;compressedInput=0;baselineOutput=0;actualOutput=0;eliminatedOutput=0;providerCachedInput=0;sentInputLocal=0;removedInputLocal=0;estimatorExact=false;repairOutput=0;repairInput=0;compressionReport=void 0;eliminate(e){this.eliminatedInput+=Math.max(0,e);}compress(e,n){this.compressedInput+=Math.max(0,e-n);}providerCached(e){this.providerCachedInput+=Math.max(0,e);}avoidCall(e,n){this.avoidedLlm+=1,this.actualLlm=0,this.baselineInput=e,this.baselineOutput=n;}get publishedBaselineOutput(){return this.avoidedLlm===0?Math.max(0,this.actualOutput-this.repairOutput):this.baselineOutput}estimateCost(e){let n=this.avoidedLlm===0,r="estimated";if(n)if(this.actualInput>0&&this.sentInputLocal>0){let f=this.actualInput/this.sentInputLocal,p=Math.max(0,this.actualInput-this.repairInput);this.baselineInput=p+Math.round(f*this.removedInputLocal),r=this.removedInputLocal===0?"measured":"estimated";}else this.actualInput>0?(this.baselineInput=this.actualInput,r="measured"):(this.baselineInput=0,r="unmeasured");let o=n?Math.max(0,this.actualOutput-this.repairOutput):this.baselineOutput,s=e.cachedInputPer1k??e.inputPer1k,i=Math.min(this.providerCachedInput,this.actualInput),c=f=>Math.max(0,f-i)/1e3*e.inputPer1k+i/1e3*s,l=c(this.baselineInput)+o/1e3*e.outputPer1k,a=c(this.actualInput)+this.actualOutput/1e3*e.outputPer1k,u=l===0?0:1-a/l;return {baselineEstimate:mn(l),actual:mn(a),netSavings:Gr(u),basis:r}}};function mn(t){return Math.round(t*1e10)/1e10}function Gr(t){return Math.round(t*1e6)/1e6}var Zr=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Yr=new TextEncoder;function G(t,e){return t>>>e|t<<32-e}function hn(t){let e=Yr.encode(t),n=e.length*8,r=(e.length+8>>6)+1,o=new Uint8Array(r*64);o.set(e),o[e.length]=128;let s=new DataView(o.buffer);s.setUint32(o.length-8,Math.floor(n/4294967296)),s.setUint32(o.length-4,n>>>0);let i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),c=new Uint32Array(64);for(let a=0;a<o.length;a+=64){for(let x=0;x<16;x++)c[x]=s.getUint32(a+x*4);for(let x=16;x<64;x++){let y=c[x-15],R=c[x-2],E=G(y,7)^G(y,18)^y>>>3,_=G(R,17)^G(R,19)^R>>>10;c[x]=c[x-16]+E+c[x-7]+_|0;}let u=i[0],f=i[1],p=i[2],d=i[3],m=i[4],g=i[5],h=i[6],b=i[7];for(let x=0;x<64;x++){let y=G(m,6)^G(m,11)^G(m,25),R=m&g^~m&h,E=b+y+R+Zr[x]+c[x]|0,_=G(u,2)^G(u,13)^G(u,22),I=u&f^u&p^f&p,w=_+I|0;b=h,h=g,g=m,m=d+E|0,d=p,p=f,f=u,u=E+w|0;}i[0]=i[0]+u|0,i[1]=i[1]+f|0,i[2]=i[2]+p|0,i[3]=i[3]+d|0,i[4]=i[4]+m|0,i[5]=i[5]+g|0,i[6]=i[6]+h|0,i[7]=i[7]+b|0;}let l="";for(let a=0;a<8;a++)l+=(i[a]>>>0).toString(16).padStart(8,"0");return l}var Jr=/\s+/g;function Wr(t){return t.trim().replace(Jr," ").toLowerCase()}function ge(t){return hn(t)}function Ee(t){return JSON.stringify(wt(t))}function wt(t){if(Array.isArray(t))return t.map(wt);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=wt(t[n]);return e}return t}function Xr(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function St(t){let e=t.context??{},n=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(`
2
- `),r=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${Wr(s.content)}`).join(`
3
- `),o=(t.tools??[]).map(s=>({id:s.id,risk:s.risk,parameters:s.parameters??null})).sort((s,i)=>s.id.localeCompare(i.id));return {model:t.model,modelFamily:Xr(t.model),messages:t.messages,normalizedText:r,systemPromptHash:ge(n),toolsetHash:ge(Ee(o)),structuredDataHash:t.structuredData!==void 0?ge(Ee(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.contractId??"none",contractId:t.response?.contractId??null,temperature:t.temperature??null,seed:t.seed??null,tenantId:e.tenantId??"anonymous",authorizationScope:e.authorizationScope??"default",principal:e.sessionId??null,locale:e.locale??"und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}function gn(t){let e=Ee({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,modelFamily:t.modelFamily,model:t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,data:t.structuredDataHash,locale:t.locale,temperature:t.temperature,seed:t.seed,knowledgeEpoch:t.knowledgeEpoch,freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${ge(e)}`}function bn(t){let e=Ee({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,model:t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,data:t.structuredDataHash,temperature:t.temperature,seed:t.seed});return `bvsala:inflight:${ge(e)}`}var Qr=new RegExp("\\b("+["now|today|current|currently|latest|live|price|prices|stock|availability|weather|score|breaking","ahora|hoy|actual|actualmente|ultimo|\xFAltimo|precio|precios|disponibilidad|cotizacion|cotizaci\xF3n","ara|avui|preu|preus|disponibilitat|darrer","maintenant|aujourd'hui|actuel|actuelle|dernier|prix|disponibilite|disponibilit\xE9|meteo|m\xE9t\xE9o","jetzt|heute|aktuell|aktuelle|neueste|preis|preise|verfugbarkeit|verf\xFCgbarkeit|wetter|kurs","adesso|oggi|attuale|ultimo|prezzo|prezzi|disponibilita|disponibilit\xE0|meteo","agora|hoje|atual|ultimo|\xFAltimo|preco|pre\xE7o|precos|pre\xE7os|disponibilidade|cotacao|cota\xE7\xE3o","nu|vandaag|huidige|laatste|prijs|prijzen|beschikbaarheid|weer|koers","teraz|dzisiaj|dzis|dzi\u015B|aktualny|aktualna|najnowszy|cena|ceny|dostepnosc|dost\u0119pno\u015B\u0107|pogoda","simdi|\u015Fimdi|bugun|bug\xFCn|guncel|g\xFCncel|son|fiyat|fiyatlar|stok|hava","sekarang|hari ini|terkini|terbaru|harga|ketersediaan|cuaca","bay gio|b\xE2y gi\u1EDD|hom nay|h\xF4m nay|hien tai|hi\u1EC7n t\u1EA1i|moi nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),eo=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nuestro|nuestra|cuenta|factura|pedido|saldo|suscripcion|suscripci\xF3n|perfil","meu|meva|nostre|compte|factura|comanda|saldo|subscripcio|subscripci\xF3|perfil","mon|ma|mes|notre|nos|compte|solde|facture|commande|abonnement|profil","mein|meine|meinem|unser|unsere|konto|kontostand|saldo|rechnung|bestellung|abo|abonnement|profil","mio|mia|miei|nostro|nostra|conto|saldo|fattura|ordine|abbonamento|profilo","meu|minha|meus|nosso|nossa|conta|saldo|fatura|pedido|assinatura|perfil","mijn|onze|ons|rekening|saldo|factuur|bestelling|abonnement|profiel","moj|m\xF3j|moja|moje|nasz|nasza|konto|saldo|faktura|zamowienie|zam\xF3wienie|subskrypcja|profil","benim|bizim|hesap|hesabim|hesab\u0131m|bakiye|fatura|siparis|sipari\u015F|abonelik|profil","saya|kami|akun|saldo|tagihan|pesanan|langganan|profil","cua toi|c\u1EE7a t\xF4i|tai khoan|t\xE0i kho\u1EA3n|so du|s\u1ED1 d\u01B0|hoa don|h\xF3a \u0111\u01A1n|don hang|\u0111\u01A1n h\xE0ng|thue bao|thu\xEA bao"].join("|")+")\\b","i");function kt(t){let e=[],n=t.normalizedText,r=(t.original.tools??[]).some(p=>p.risk==="write"||p.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||Qr.test(n),s=eo.test(n),i=(t.temperature??0)>.3&&t.seed==null;r&&e.push("write/destructive tools present"),o&&e.push("freshness-sensitive request"),s&&e.push("personalized/account-scoped request"),i&&e.push("stochastic sampling (temp>0.3, no seed)");let c=o&&(t.freshnessBucket==null||t.freshnessBucket==="any"),l=t.freshnessBucket==="live",a=s&&t.principal==null,u=!i&&!c&&!l&&!a&&!r;r&&e.push("write/destructive tools \u2192 exact cache off (side effects must execute)"),l&&e.push("freshnessBucket=live \u2192 exact cache off (answer must be current)"),c&&e.push("freshness-sensitive without a freshness bucket \u2192 exact cache off"),a&&e.push("personalized request with no principal (context.sessionId) \u2192 exact cache off");let f=!r&&!o&&!s&&!i&&t.freshnessBucket!=="day";return {allowExactCache:u,allowSemanticCache:f,allowSingleflight:!r&&!a,allowCompression:true,requiresFreshData:o,hasSideEffects:r,isPersonalized:s,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var ze=class{store=new Map;maxEntries;now;constructor(e={}){this.maxEntries=e.maxEntries??1e4,this.now=e.now??(()=>Date.now());}async get(e){let n=this.store.get(e);return n?n.expiresAtMs!==null&&this.now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),n.value):null}async set(e,n,r){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let o=this.store.keys().next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:n,expiresAtMs:r!=null?this.now()+r:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};var Ne=class{inflight=new Map;waiters=new Map;async run(e,n){let r=this.inflight.get(e);if(r)return this.waiters.set(e,(this.waiters.get(e)??1)+1),{value:await r,coalesced:true};let o=(async()=>n())();this.inflight.set(e,o),this.waiters.set(e,1);try{return {value:await o,coalesced:!1}}finally{this.inflight.delete(e),this.waiters.delete(e);}}get activeKeys(){return this.inflight.size}};function to(t,e){let n=Math.min(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i++){let c=t[i],l=e[i];r+=c*l,o+=c*c,s+=l*l;}return o===0||s===0?0:r/(Math.sqrt(o)*Math.sqrt(s))}var no=new Set(["no","not","never","none","cannot","cant","without","nor","nt","isnt","arent","wasnt","werent","dont","doesnt","didnt","wont","cant","shouldnt"]),ro=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what","whats","which","who","whom","how","when","where","me","my","i","you","please","tell","give","show","find","do","does","did","be","that","this","it","with","as","at","by","from","about","into","over","than","then","s"]);function xn(t){return (t.match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function oo(t,e){if(t.length!==e.length)return false;let n=new Map;for(let r of t)n.set(r,(n.get(r)??0)+1);for(let r of e){let o=n.get(r);if(!o)return false;n.set(r,o-1);}return true}function yn(t){return t.split(/\s+/).filter(Boolean)}function vn(t){return t.filter(e=>no.has(e.replace(/'/g,""))||e.endsWith("n't")).length}function so(t,e){if(!oo(xn(t),xn(e)))return false;let n=yn(t),r=yn(e);if(vn(n)!==vn(r))return false;let o=a=>a.length>1&&!ro.has(a)&&!/^\d/.test(a),s=new Set(n.filter(o)),i=new Set(r.filter(o));if(s.size===0&&i.size===0)return true;let c=0;for(let a of s)i.has(a)&&c++;let l=s.size+i.size-c;return l===0?true:c/l>=.75}var wn=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;constructor(e){this.embed=e.embed,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??.9,this.acceptThreshold=e.acceptThreshold??.85,this.ttlMs=e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now());}async find(e){if(this.records.length===0)return null;let n=await this.embed(e.normalizedText),r=null;for(let o of this.records){if(o.tenantId!==e.tenantId||o.authorizationScope!==e.authorizationScope||o.principal!==e.principal||o.knowledgeEpoch!==e.knowledgeEpoch||o.contractId!==e.contractId||o.model!==e.model||o.systemPromptHash!==e.systemPromptHash||o.structuredDataHash!==e.structuredDataHash||o.locale!==e.locale||o.schemaVersion!==e.schemaVersion||o.safetyPolicyVersion!==e.safetyPolicyVersion||this.ttlMs!=null&&this.now()-o.storedAtMs>this.ttlMs)continue;let s=to(n,o.embedding);if(s<this.similarityThreshold||!so(e.normalizedText,o.query))continue;let i=this.verify?await this.verify(e.normalizedText,o.query):s,c=Math.min(s,i);c<this.acceptThreshold||(!r||c>r.confidence)&&(r={record:o,similarity:s,verifierScore:i,confidence:c,ageMs:this.now()-o.storedAtMs});}return r}async store(e,n){let r=await this.embed(e.normalizedText);this.records.length>=this.maxRecords&&this.records.shift(),this.records.push({embedding:r,query:e.normalizedText,answer:n,tenantId:e.tenantId,authorizationScope:e.authorizationScope,principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.structuredDataHash,locale:e.locale,schemaVersion:e.schemaVersion,safetyPolicyVersion:e.safetyPolicyVersion,storedAtMs:this.now()});}invalidateEpoch(e){let n=0;for(let r=this.records.length-1;r>=0;r--)this.records[r].knowledgeEpoch===e&&(this.records.splice(r,1),n++);return n}get size(){return this.records.length}};var Et=class{resolvers=[];register(e){return this.resolvers.push(e),this}try(e){for(let n of this.resolvers)try{let r=n.try(e);if(r)return r}catch{}return null}get size(){return this.resolvers.length}},io={name:"arithmetic",try(t){let n=(t.normalizedText.match(/(?:what\s+is|calculate|compute|how\s+much\s+is|cu[aá]nto\s+es)\s+([0-9+\-*/%.()\s]+)\??$/i)?.[1]??ao(t.normalizedText))?.trim();if(!n)return null;let r=lo(n);return r===null||!Number.isFinite(r)?null:{text:co(r),data:{value:r},resolver:"arithmetic"}}};function ao(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function co(t){return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function lo(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],r=[],o={"+":1,"-":1,"*":2,"/":2,"%":2},s=c=>{let l=n.pop(),a=n.pop();if(a===void 0||l===void 0)return false;switch(c){case "+":return n.push(a+l),true;case "-":return n.push(a-l),true;case "*":return n.push(a*l),true;case "/":return l===0?false:(n.push(a/l),true);case "%":return l===0?false:(n.push(a%l),true);default:return false}},i=true;for(let c of e)if(/^\d/.test(c))n.push(Number(c)),i=false;else if(c==="(")r.push(c),i=true;else if(c===")"){for(;r.length&&r[r.length-1]!=="(";)if(!s(r.pop()))return null;if(r.pop()!=="(")return null;i=false;}else {if(i)return null;for(;r.length&&r[r.length-1]!=="("&&o[r[r.length-1]]>=o[c];)if(!s(r.pop()))return null;r.push(c),i=true;}for(;r.length;){let c=r.pop();if(c==="("||!s(c))return null}return n.length===1?n[0]:null}function Sn(){return new Et().register(io)}var uo=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,kn=/\b(who|what|when|where|which|how many|how much|define|definition|qui[eé]n|qu[eé]|cu[aá]ndo|d[oó]nde|cu[aá]nto)\b/i,fo=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,$e=class{classifier;maxRounds;constructor(e={}){this.classifier=e.classifier,this.maxRounds=e.maxRounds??2;}classify(e){let n=e.original.retrieval?.mode,r=e.normalizedText;if((e.original.tools??[]).some(i=>i.risk==="write"||i.risk==="destructive")&&/\b(create|update|delete|send|pay|book|cancel|crea|actualiza|elimina|env[ií]a|paga)\b/i.test(r))return J("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return J("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(fo.test(r)&&!kn.test(r))return J("NO_RETRIEVAL",.8,"self-contained transformation",0);let s=this.classifier?.classify(r);return s&&s.confidence>=.75?J(s.executionClass,s.confidence,"local classifier",po(s.executionClass,this.maxRounds)):n==="single"?J("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?J("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):uo.test(r)?J("MULTI_HOP_RETRIEVAL",.7,"comparison/compound question",Math.min(this.maxRounds,2)):kn.test(r)?J("SINGLE_RETRIEVAL",.65,"single factual lookup",1):J("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function po(t,e){return t==="SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function J(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var Ve=class{maxTools;scoreIntentMatch;constructor(e={}){this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??mo;}passthrough(e){if(!e||e.length===0)return {tools:[],droppedIds:[],reason:"no tools provided"};let n=e.slice(0,this.maxTools),r=e.slice(this.maxTools).map(o=>o.id);return {tools:n,droppedIds:r,reason:`router off: caller tools passed through unfiltered (${n.length}/${e.length}, capped at maxTools=${this.maxTools}; risk gating is the caller's responsibility while routing is off)`}}select(e,n,r){if(!n||n.length===0)return {tools:[],droppedIds:[],reason:"no tools provided"};let o=r==="TOOL_ACTION",c=n.filter(u=>o||u.risk==="read").map(u=>({tool:u,score:this.scoreIntentMatch(e,u)})).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,this.maxTools).map(u=>u.tool),l=new Set(c.map(u=>u.id)),a=n.filter(u=>!l.has(u.id)).map(u=>u.id);return {tools:c,droppedIds:a,reason:`selected ${c.length}/${n.length} by intent match (writes ${o?"allowed":"blocked"})`}}};function mo(t,e){let n=t.toLowerCase(),r=0;for(let o of e.intents){let s=o.toLowerCase();n.includes(s)?r+=2:s.split(/\s+/).some(i=>i.length>3&&n.includes(i))&&(r+=1);}return r}function ho(t){let e=new Set,n=[];for(let r of t){let o=r.hash??bo(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function go(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((i,c)=>(c.score??0)-(i.score??0));if(r.length<=n)return r;let o=r[0]?.score??0;if(o<=0)return r.slice(0,e.maxDocuments);let s=[];for(let i of r){let c=(i.score??0)/o;if(s.length<n||c>=.4&&s.length<e.maxDocuments)s.push(i);else break}return s}async function En(t,e){if(t.execution==="NO_RETRIEVAL"||t.execution==="TOOL_ACTION"||t.execution==="NON_CACHEABLE"||!e.retriever)return {docs:[],rounds:0,retrievedCount:0,keptCount:0};let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,r=[];for(let i=0;i<n;i++){let c=await e.retriever.retrieve(t.query,t.maxDocuments*2);r.push(...c);}let o=r.length;r=ho(r),e.reranker&&(r=await e.reranker.rerank(t.query,r));let s=go(r,{maxDocuments:t.maxDocuments});return {docs:s,rounds:n,retrievedCount:o,keptCount:s.length}}function bo(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function Ai(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function Li(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&wo(o)?Object.assign(n.userPreferences,o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let s=yo(n,r);s?s.push(...o.map(String)):n.confirmedFacts[r]=o;}for(let r of e.remove??[])delete n.confirmedFacts[r],delete n.userPreferences[r],vo(n,r);return n}function Bi(t){let e=t.rawTurns??3,n=[],r=xo(t.state);r&&n.push({role:"system",content:`Conversation state:
4
- ${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function xo(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`facts: ${JSON.stringify(t.confirmedFacts)}`),Object.keys(t.userPreferences).length&&e.push(`preferences: ${JSON.stringify(t.userPreferences)}`),t.decisions.length&&e.push(`decisions: ${t.decisions.join("; ")}`),t.openItems.length&&e.push(`open: ${t.openItems.join("; ")}`),e.join(`
5
- `)}function yo(t,e){switch(e){case "goals":return t.goals;case "decisions":return t.decisions;case "openItems":return t.openItems;case "evidenceRefs":return t.evidenceRefs;default:return null}}function vo(t,e){for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function wo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Tn={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function Rn(t,e={}){let n=e.delimiter??",",r=e.indent??" ",s=t.split(`
6
- `).filter(l=>l.trim().length>0).map(l=>({indent:So(l,r),content:l.slice(In(l,r))}));if(s.length===0)return {};let i=s[0];if(i.indent===0){let l=i.content.match(/^\[(\d+)\]\{(.*)\}:\s*$/);if(l){let u=be(l[2],n),f=Number(l[1]),p=[];for(let d=0,m=1;d<f&&m<s.length;d++,m++){let g=s[m];if(g.indent!==1)break;let h=be(g.content,n),b={};u.forEach((x,y)=>{b[x]=Te(h[y]??"null");}),p.push(b);}return p}let a=i.content.match(/^\[(\d+)\]:\s*(.*)$/);if(a){let u=a[2];return Number(a[1])===0||u.trim()===""?[]:be(u,n).map(Te)}}let[c]=On(s,0,0,n);return c}function In(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}function So(t,e){return In(t,e)/e.length}function On(t,e,n,r){let o={},s=e;for(;s<t.length;){let i=t[s];if(i.indent<n)break;if(i.indent>n){s++;continue}let c=ko(i.content,r);if(!c){s++;continue}let{key:l,kind:a}=c;if(a.type==="scalar")o[l]=a.value,s++;else if(a.type==="inlineArray")o[l]=a.values,s++;else if(a.type==="emptyArray")o[l]=[],s++;else if(a.type==="table"){let u=[];s++;for(let f=0;f<a.count&&s<t.length;f++,s++){let p=t[s];if(p.indent!==n+1)break;let d=be(p.content,r),m={};a.columns.forEach((g,h)=>{m[g]=Te(d[h]??"null");}),u.push(m);}o[l]=u;}else {let[u,f]=On(t,s+1,n+1,r);o[l]=u,s=f;}}return [o,s]}function ko(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:Ue(n[1]),kind:{type:"table",count:Number(n[2]),columns:be(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){let s=Number(r[2]),i=r[3];return s===0||i.trim()===""?{key:Ue(r[1]),kind:{type:"emptyArray"}}:{key:Ue(r[1]),kind:{type:"inlineArray",values:be(i,e).map(Te)}}}let o=t.match(/^([^:]+):\s*(.*)$/);if(o){let s=Ue(o[1]),i=o[2];return i===""?{key:s,kind:{type:"object"}}:{key:s,kind:{type:"scalar",value:Te(i)}}}return null}function be(t,e){let n=[],r="",o=false;for(let s=0;s<t.length;s++){let i=t[s];o?i==='"'?t[s+1]==='"'?(r+='"',s++):o=false:r+=i:i==='"'?o=true:i===e?(n.push(r),r=""):r+=i;}return n.push(r),n.map(s=>s.trim())}function Te(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,'"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function Ue(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,'"'):e}function Eo(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return It(null,t,0,o,n,r),o.join(`
7
- `)}function It(t,e,n,r,o,s){let i=s.repeat(n),c=t===null?"":`${Ro(t)}`;if(Array.isArray(e)){To(c,e,n,r,o,s);return}if(Rt(e)){t!==null&&r.push(`${i}${c}:`);let l=t===null?n:n+1;for(let[a,u]of Object.entries(e))It(a,u,l,r,o,s);return}r.push(`${i}${c}: ${He(e,o)}`);}function To(t,e,n,r,o,s){let i=s.repeat(n),c=t===""?"":t;if(e.length===0){r.push(`${i}${c}[0]:`);return}if(e.every(Tt)){let f=e.map(p=>He(p,o)).join(o);r.push(`${i}${c}[${e.length}]: ${f}`);return}let l=Ke(e);if(l){r.push(`${i}${c}[${e.length}]{${l.join(o)}}:`);let f=s.repeat(n+1);for(let p of e){let d=l.map(m=>He(p[m],o)).join(o);r.push(`${f}${d}`);}return}r.push(`${i}${c}[${e.length}]:`);let a=n+1,u=s.repeat(a);for(let f of e)if(Tt(f))r.push(`${u}- ${He(f,o)}`);else {let p=[];It(null,f,0,p,o,s);let[d,...m]=p;r.push(`${u}- ${d??""}`);for(let g of m)r.push(`${u}${s}${g}`);}}function Ke(t){if(t.length===0)return null;let e=t[0];if(!Rt(e))return null;let n=Object.keys(e);if(n.length===0)return null;let r=n.slice().sort().join("\0");for(let o of t){if(!Rt(o))return null;let s=Object.keys(o);if(s.slice().sort().join("\0")!==r)return null;for(let i of s)if(!Tt(o[i]))return null}return n}function Ro(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:_n(t)}function He(t,e){if(t==null)return "null";if(typeof t=="number")return Number.isFinite(t)?String(t):"null";if(typeof t=="boolean")return t?"true":"false";let n=String(t);return n===""||n.includes(e)||n.includes(`
8
- `)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?_n(n):n}function _n(t){return `"${t.replace(/"/g,'""')}"`}function Tt(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function Rt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Io="Data is TOON: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; each following indented line is one row of delimiter-separated values. `key[N]: a,b` is an inline list. Quoted values use CSV-style escaping.";function Oo(t={}){return {format:"toon",supports(){return true},encode(e){return Eo(e,t)},instruction(){return Io},decode(e){return Rn(e,t)}}}var Cn=Oo();var Ln={format:"csv",supports(t){return Array.isArray(t)&&Ke(t)!==null},encode(t){let e=t,n=Ke(e),r=n.map(An).join(","),o=e.map(s=>n.map(i=>An(s[i])).join(","));return [r,...o].join(`
9
- `)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function An(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}var qe=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[Tn,Cn,Ln],this.minSavingsTokens=e.minimumSavingsTokens??64,this.minSavingsRatio=e.minimumSavingsRatio??.08,this.qualityPenalty=e.qualityPenalty??(()=>0);}choose(e,n){let r={model:n.model,tokenizer:n.tokenizer},o=[];for(let a of this.serializers){if(!a.supports(e))continue;let u=a.encode(e);if(a.format!=="json-compact"&&!_o(a,u,e))continue;let f=a.instruction(e),p=this.tokenizer.count(u,r),d=f?this.tokenizer.count(f,r):0,m=this.qualityPenalty(n.model??"",a.format);o.push({format:a.format,encoded:u,instruction:f,payloadTokens:p,instructionTokens:d,penalty:m,total:p+d+m});}let s=o.find(a=>a.format==="json-compact"),i={};for(let a of o)i[a.format]=a.total;if(!s){let a=o[0];return a?Bn(a,i,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:i,instructionOverheadTokens:0,reason:"no serializer supported payload; defaulted to JSON"}}let c=s,l="json baseline (no challenger cleared thresholds)";for(let a of o){if(a.format==="json-compact")continue;let u=s.total-a.total,f=s.total===0?0:u/s.total;u>=this.minSavingsTokens&&f>=this.minSavingsRatio&&a.total<c.total&&(c=a,l=`${a.format} saved ${u} tokens (${(f*100).toFixed(1)}%) vs json`);}return Bn(c,i,l)}};function _o(t,e,n){if(!t.decode)return false;try{return Ot(t.decode(e),n)}catch{return false}}function Ot(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.isArray(t),r=Array.isArray(e);if(n||r){if(!n||!r||t.length!==e.length)return false;for(let i=0;i<t.length;i++)if(!Ot(t[i],e[i]))return false;return true}let o=Object.keys(t),s=Object.keys(e);if(o.length!==s.length)return false;for(let i of o)if(!Object.prototype.hasOwnProperty.call(e,i)||!Ot(t[i],e[i]))return false;return true}function Bn(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function Re(t,e,n="$"){let r=[];return _t(t,e,n,r),{valid:r.length===0,errors:r}}function Co(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function _t(t,e,n,r){switch(e.enum&&!e.enum.some(s=>Do(s,t))&&r.push({path:n,message:"value not in enum"}),e.type??Co(t)){case "object":Ao(t,e,n,r);break;case "array":Lo(t,e,n,r);break;case "string":Bo(t,e,n,r);break;case "number":case "integer":Mo(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function Ao(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,message:"expected object"});return}let o=t;for(let s of e.required??[])s in o||r.push({path:`${n}.${s}`,message:"missing required property"});if(e.additionalProperties===false&&e.properties){let s=new Set(Object.keys(e.properties));for(let i of Object.keys(o))s.has(i)||r.push({path:`${n}.${i}`,message:"additional property not allowed"});}if(e.properties)for(let[s,i]of Object.entries(e.properties))s in o&&_t(o[s],i,`${n}.${s}`,r);}function Lo(t,e,n,r){if(!Array.isArray(t)){r.push({path:n,message:"expected array"});return}e.maxItems!=null&&t.length>e.maxItems&&r.push({path:n,message:`array exceeds maxItems ${e.maxItems}`}),e.minItems!=null&&t.length<e.minItems&&r.push({path:n,message:`array below minItems ${e.minItems}`}),e.items&&t.forEach((o,s)=>_t(o,e.items,`${n}[${s}]`,r));}function Bo(t,e,n,r){if(typeof t!="string"){r.push({path:n,message:"expected string"});return}if(e.maxLength!=null&&t.length>e.maxLength&&r.push({path:n,message:`string exceeds maxLength ${e.maxLength}`}),e.minLength!=null&&t.length<e.minLength&&r.push({path:n,message:`string below minLength ${e.minLength}`}),e.pattern){let o=null;try{o=new RegExp(e.pattern);}catch{r.push({path:n,message:`schema pattern is not a valid regular expression: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function Mo(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}e.type==="integer"&&!Number.isInteger(t)&&r.push({path:n,message:"expected integer"}),e.maximum!=null&&t>e.maximum&&r.push({path:n,message:`number exceeds maximum ${e.maximum}`}),e.minimum!=null&&t<e.minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function Do(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var Ge=class{contracts=new Map;register(e){return this.contracts.set(e.contractId,e),this}resolve(e){return this.contracts.get(e)}has(e){return this.contracts.has(e)}static lint(e,n="$"){let r=[];return Ct(e,n,r),r}};function Ct(t,e,n){if(t.type==="object"){t.additionalProperties!==false&&n.push(`${e}: object should set additionalProperties:false`);for(let[r,o]of Object.entries(t.properties??{}))Ct(o,`${e}.${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&Ct(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: string should set maxLength or use an enum`);}function Mn(t,e,n){for(let r of n)if(r.supports(t,e))return {backend:r.id,reason:`first supporting backend: ${r.id}`};return {backend:"none",reason:"no constrained-decoding backend available; will validate + repair"}}function na(t=()=>true){return {id:"provider-native",supports:t}}function ca(t){let e=t.minimumContextTokens??2e3,n=t.minimumNetTokens??200;if(t.contextTokens<e)return {compress:false,reason:`context ${t.contextTokens} < ${e} min`};let r=t.projectedEliminable-t.compressorCostTokens;return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function la(t){return {async compress(e){let n=e.protectedSpans??[],r=e.text,o=[];n.forEach((l,a)=>{let u=`\0PROTECT_${a}\0`;o.push({token:u,span:l}),r=r.split(l.text).join(u);});let s=await t.compress({text:r,...e.targetRatio!=null?{targetRatio:e.targetRatio}:{}}),i=s.compressed,c=true;for(let{token:l,span:a}of o){if(!i.includes(l)){c=false;break}i=i.split(l).join(a.text);}return c?{...s,compressed:i,protectedSpans:n.length,fidelityPassed:true}:{compressed:e.text,originalTokens:s.originalTokens,compressedTokens:s.originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var ua={async compress(t){return {compressed:t.text,originalTokens:0,compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};var Dn=new WeakSet;function jn(t){Dn.add(t);}var At=class{id="mock";options;constructor(e={}){this.options=e,jn(this);}async generate(e){let n=e.messages.map(c=>c.content).join(`
10
- `),r=me.count(n);if(e.tools&&e.tools.length>0){let c=JSON.stringify(e.tools.map(l=>({name:l.id,description:l.description,parameters:l.parameters??{}})));r+=me.count(c);}let o,s=false;if(e.schema){let c=this.options.data??Ze(e.schema);o=JSON.stringify(c),s=true;}else o=this.options.answer??`mock-response(${e.model})`;let i=Math.min(e.maxOutputTokens??Number.MAX_SAFE_INTEGER,me.count(o));return {text:o,usage:{inputTokens:r,outputTokens:i,...this.options.cachedInputTokens!=null?{cachedInputTokens:this.options.cachedInputTokens}:{}},structuredNatively:s}}};function Ze(t){if(t.enum&&t.enum.length>0)return t.enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?Ze(r):null;}for(let[n,r]of Object.entries(t.properties??{}))n in e||(e[n]=Ze(r));return e}case "array":return t.items?[Ze(t.items)]:[];case "string":return "mock";case "number":case "integer":return t.minimum??0;case "boolean":return true;case "null":return null;default:return null}}function ba(t){return new At(t)}var Fn=new Set;function Ie(t,e){Fn.has(t)||(Fn.add(t),console.warn(e));}function Oe(t){if(t==null||typeof t!="object")return true;let e=t,n=e.properties;if(n&&typeof n=="object"){if(e.additionalProperties!==false)return false;let o=Object.keys(n),s=Array.isArray(e.required)?e.required.map(String):[];if(o.some(i=>!s.includes(i)))return false;for(let i of Object.values(n))if(!Oe(i))return false}if(e.items!==void 0&&!Oe(e.items))return false;for(let o of ["anyOf","oneOf","allOf"]){let s=e[o];if(Array.isArray(s)&&s.some(i=>!Oe(i)))return false}let r=e.$defs??e.definitions;return !(r&&typeof r=="object"&&Object.values(r).some(o=>!Oe(o)))}var zn=class{id;opts;fetchImpl;constructor(e){this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch;}async generate(e){let r={model:this.opts.stripProviderPrefix?e.model.replace(/^[^/]+\//,""):e.model,messages:e.messages.map(g=>({role:g.role,content:g.content}))};if(e.maxOutputTokens!=null&&(r.max_tokens=e.maxOutputTokens),e.temperature!=null&&(r.temperature=e.temperature),e.seed!=null&&(r.seed=e.seed),e.schema){let g=Oe(e.schema);g||Ie("strict-incompatible","[bvsala] El contrato de respuesta no cumple el modo `strict` de OpenAI (en strict, `required` debe listar TODAS las claves de `properties`, y todo objeto necesita `additionalProperties: false`). Se env\xEDa el esquema con `strict: false`: el modelo sigue guiado y el layer sigue validando, pero la garant\xEDa la da el layer, no el proveedor. Para recuperarla, haz obligatorias todas las claves del contrato."),r.response_format={type:"json_schema",json_schema:{name:"bvsala_contract",schema:e.schema,strict:g}};}e.tools&&e.tools.length>0&&(r.tools=e.tools.map(g=>({type:"function",function:{name:g.id,...g.description?{description:g.description}:{},parameters:g.parameters??{type:"object",properties:{}}}})));let o=await this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.headers},body:JSON.stringify(r)});if(!o.ok){let g=await jo(o);throw new Error(`provider ${o.status}: ${g}`)}let s=await o.json(),i=s.choices?.[0]?.message,c=i?.content??"",l=(i?.tool_calls??[]).map(g=>({...g.id?{id:g.id}:{},name:g.function?.name??"",arguments:g.function?.arguments??""})).filter(g=>g.name!==""),a=s.usage??{},u=a.prompt_tokens??0,f=a.completion_tokens??0,p=typeof a.prompt_tokens!="number",d=typeof a.completion_tokens!="number";if(this.opts.requireUsage&&(p||d))throw new Error(`provider returned incomplete usage (prompt=${a.prompt_tokens??"absent"}, completion=${a.completion_tokens??"absent"}); cannot measure cost. For gateways/streaming, ensure usage reporting is enabled.`);let m=s.choices?.[0]?.finish_reason;return {text:c,...l.length>0?{toolCalls:l}:{},...m?{finishReason:m}:{},usage:{inputTokens:u,outputTokens:f,...a.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:a.prompt_tokens_details.cached_tokens}:{}},structuredNatively:e.schema!=null,raw:s}}};async function jo(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}var _e=class{events=[];start;now;constructor(e=()=>Date.now()){this.now=e,this.start=e();}record(e,n,r){this.events.push({stage:e,outcome:n,...r?{detail:r}:{},atMs:this.now()-this.start});}elapsed(){return this.now()-this.start}all(){return this.events}};var le=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function Lt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Ye(t,e=""){if(typeof t!="number"){let n=e&&`"${e}" `;throw new TypeError(`${n}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let n=e&&`"${e}" `;throw new RangeError(`${n}expected integer >= 0, got ${t}`)}}function K(t,e,n=""){let r=Lt(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){let i=n&&`"${n}" `,c=s?` of length ${e}`:"",l=r?`length=${o}`:`type=${typeof t}`,a=i+"expected Uint8Array"+c+", got "+l;throw r?new RangeError(a):new TypeError(a)}return t}function Bt(t,e=true){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function $n(t,e){K(t,void 0,"digestInto() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function Ce(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function Je(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Vn=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Po=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function We(t){if(K(t),Vn)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Po[t[n]];return e}var W={_0:48,_9:57,A:65,F:70,a:97,f:102};function Nn(t){if(t>=W._0&&t<=W._9)return t-W._0;if(t>=W.A&&t<=W.F)return t-(W.A-10);if(t>=W.a&&t<=W.f)return t-(W.a-10)}function Ae(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Vn)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){let i=Nn(t.charCodeAt(s)),c=Nn(t.charCodeAt(s+1));if(i===void 0||c===void 0){let l=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+l+'" at index '+s)}r[o]=i*16+c;}return r}function Mt(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];K(o),e+=o.length;}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let s=t[r];n.set(s,o),o+=s.length;}return n}function Un(t,e={}){let n=(o,s)=>t(s).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function Hn(t=32){Ye(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var Kn=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var Xe=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(e,n,r,o){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Je(this.buffer);}update(e){Bt(this),K(e);let{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let c=Math.min(o-this.pos,s-i);if(c===o){let l=Je(e);for(;o<=s-i;i+=o)this.process(l,i);continue}r.set(e.subarray(i,i+c),this.pos),this.pos+=c,i+=c,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){Bt(this),$n(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;n[i++]=128,Ce(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let f=i;f<o;f++)n[f]=0;r.setBigUint64(o-8,BigInt(this.length*8),s),this.process(r,0);let c=Je(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let a=l/4,u=this.get();if(a>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<a;f++)c.setUint32(4*f,u[f],s);}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:c}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=c,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};var $=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Qe=BigInt(4294967295),qn=BigInt(32);function Fo(t,e=false){return e?{h:Number(t&Qe),l:Number(t>>qn&Qe)}:{h:Number(t>>qn&Qe)|0,l:Number(t&Qe)|0}}function Gn(t,e=false){let n=t.length,r=new Uint32Array(n),o=new Uint32Array(n);for(let s=0;s<n;s++){let{h:i,l:c}=Fo(t[s],e);[r[s],o[s]]=[i,c];}return [r,o]}var Dt=(t,e,n)=>t>>>n,jt=(t,e,n)=>t<<32-n|e>>>n,ue=(t,e,n)=>t>>>n|e<<32-n,fe=(t,e,n)=>t<<32-n|e>>>n,Le=(t,e,n)=>t<<64-n|e>>>n-32,Be=(t,e,n)=>t>>>n-32|e<<64-n;function Z(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var Zn=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Yn=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Jn=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Wn=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,Xn=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Qn=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0;var er=Gn(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),No=er[0],$o=er[1],re=new Uint32Array(80),oe=new Uint32Array(80),Pt=class extends Xe{constructor(e){super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:c,Dl:l,Eh:a,El:u,Fh:f,Fl:p,Gh:d,Gl:m,Hh:g,Hl:h}=this;return [e,n,r,o,s,i,c,l,a,u,f,p,d,m,g,h]}set(e,n,r,o,s,i,c,l,a,u,f,p,d,m,g,h){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=c|0,this.Dl=l|0,this.Eh=a|0,this.El=u|0,this.Fh=f|0,this.Fl=p|0,this.Gh=d|0,this.Gl=m|0,this.Hh=g|0,this.Hl=h|0;}process(e,n){for(let y=0;y<16;y++,n+=4)re[y]=e.getUint32(n),oe[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){let R=re[y-15]|0,E=oe[y-15]|0,_=ue(R,E,1)^ue(R,E,8)^Dt(R,E,7),I=fe(R,E,1)^fe(R,E,8)^jt(R,E,7),w=re[y-2]|0,C=oe[y-2]|0,L=ue(w,C,19)^Le(w,C,61)^Dt(w,C,6),M=fe(w,C,19)^Be(w,C,61)^jt(w,C,6),v=Jn(I,M,oe[y-7],oe[y-16]),S=Wn(v,_,L,re[y-7],re[y-16]);re[y]=S|0,oe[y]=v|0;}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:c,Cl:l,Dh:a,Dl:u,Eh:f,El:p,Fh:d,Fl:m,Gh:g,Gl:h,Hh:b,Hl:x}=this;for(let y=0;y<80;y++){let R=ue(f,p,14)^ue(f,p,18)^Le(f,p,41),E=fe(f,p,14)^fe(f,p,18)^Be(f,p,41),_=f&d^~f&g,I=p&m^~p&h,w=Xn(x,E,I,$o[y],oe[y]),C=Qn(w,b,R,_,No[y],re[y]),L=w|0,M=ue(r,o,28)^Le(r,o,34)^Le(r,o,39),v=fe(r,o,28)^Be(r,o,34)^Be(r,o,39),S=r&s^r&c^s&c,O=o&i^o&l^i&l;b=g|0,x=h|0,g=d|0,h=m|0,d=f|0,m=p|0,{h:f,l:p}=Z(a|0,u|0,C|0,L|0),a=c|0,u=l|0,c=s|0,l=i|0,s=r|0,i=o|0;let A=Zn(L,v,O);r=Yn(A,C,M,S),o=A|0;}(({h:r,l:o}=Z(this.Ah|0,this.Al|0,r|0,o|0))),{h:s,l:i}=Z(this.Bh|0,this.Bl|0,s|0,i|0),{h:c,l}=Z(this.Ch|0,this.Cl|0,c|0,l|0),{h:a,l:u}=Z(this.Dh|0,this.Dl|0,a|0,u|0),{h:f,l:p}=Z(this.Eh|0,this.El|0,f|0,p|0),{h:d,l:m}=Z(this.Fh|0,this.Fl|0,d|0,m|0),{h:g,l:h}=Z(this.Gh|0,this.Gl|0,g|0,h|0),{h:b,l:x}=Z(this.Hh|0,this.Hl|0,b|0,x|0),this.set(r,o,s,i,c,l,a,u,f,p,d,m,g,h,b,x);}roundClean(){Ce(re,oe);}destroy(){this.destroyed=true,Ce(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},Ft=class extends Pt{Ah=$[0]|0;Al=$[1]|0;Bh=$[2]|0;Bl=$[3]|0;Ch=$[4]|0;Cl=$[5]|0;Dh=$[6]|0;Dl=$[7]|0;Eh=$[8]|0;El=$[9]|0;Fh=$[10]|0;Fl=$[11]|0;Gh=$[12]|0;Gl=$[13]|0;Hh=$[14]|0;Hl=$[15]|0;constructor(){super(64);}};var et=Un(()=>new Ft,Kn(3));var j=(t,e,n)=>K(t,e,n),Nt=Ye,$t=We,Y=(...t)=>Mt(...t),tr=t=>Ae(t),rt=Lt,nr=t=>Hn(t),nt=BigInt(0),zt=BigInt(1);function xe(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"expected boolean, got type="+typeof t)}return t}function Vo(t){if(typeof t=="bigint"){if(!tt(t))throw new RangeError("positive bigint expected, got "+t)}else Nt(t);return t}function X(t,e=""){if(typeof t!="number"){let n=e&&`"${e}" `;throw new TypeError(n+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let n=e&&`"${e}" `;throw new RangeError(n+"expected safe integer, got "+t)}}function rr(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?nt:BigInt("0x"+t)}function Vt(t){return rr(We(t))}function Q(t){return rr(We(Me(K(t)).reverse()))}function Ut(t,e){if(Ye(e),e===0)throw new RangeError("zero length");t=Vo(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return Ae(n.padStart(e*2,"0"))}function or(t,e){return Ut(t,e).reverse()}function sr(t,e){if(t=j(t),e=j(e),t.length!==e.length)return false;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function Me(t){return Uint8Array.from(j(t))}var tt=t=>typeof t=="bigint"&&nt<=t;function Uo(t,e,n){return tt(t)&&tt(e)&&tt(n)&&e<=t&&t<n}function Ht(t,e,n,r){if(!Uo(e,n,r))throw new RangeError("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Kt(t){if(t<nt)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>nt;t>>=zt,e+=1);return e}var ir=t=>(zt<<BigInt(t))-zt;function de(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function r(s,i,c){if(!c&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let l=t[s];if(c&&l===void 0)return;let a=typeof l;if(a!==i||l===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${a}`)}let o=(s,i)=>Object.entries(s).forEach(([c,l])=>r(c,l,i));o(e,false),o(n,true);}var qt=()=>{throw new Error("not implemented")};var V=BigInt(0),P=BigInt(1),pe=BigInt(2),ur=BigInt(3),fr=BigInt(4),dr=BigInt(5),Ho=BigInt(7),pr=BigInt(8),Ko=BigInt(9),mr=BigInt(16);function D(t,e){if(e<=V)throw new Error("mod: expected positive modulus, got "+e);let n=t%e;return n>=V?n:e+n}function q(t,e,n){if(e<V)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >V;)r*=r,r%=n;return r}function ar(t,e){if(t===V)throw new Error("invert: expected non-zero number");if(e<=V)throw new Error("invert: expected positive modulus, got "+e);let n=D(t,e),r=e,o=V,i=P;for(;n!==V;){let a=r/n,u=r-n*a,f=o-i*a;r=n,n=u,o=i,i=f;}if(r!==P)throw new Error("invert: does not exist");return D(o,e)}function Gt(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function hr(t,e){let n=t,r=(n.ORDER+P)/fr,o=n.pow(e,r);return Gt(n,o,e),o}function qo(t,e){let n=t,r=(n.ORDER-dr)/pr,o=n.mul(e,pe),s=n.pow(o,r),i=n.mul(e,s),c=n.mul(n.mul(i,pe),s),l=n.mul(i,n.sub(c,n.ONE));return Gt(n,l,e),l}function Go(t){let e=at(t),n=gr(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+Ho)/mr;return((c,l)=>{let a=c,u=a.pow(l,i),f=a.mul(u,r),p=a.mul(u,o),d=a.mul(u,s),m=a.eql(a.sqr(f),l),g=a.eql(a.sqr(p),l);u=a.cmov(u,f,m),f=a.cmov(d,p,g);let h=a.eql(a.sqr(f),l),b=a.cmov(u,f,h);return Gt(a,b,l),b})}function gr(t){if(t<ur)throw new Error("sqrt is not defined for small field");let e=t-P,n=0;for(;e%pe===V;)e/=pe,n++;let r=pe,o=at(t);for(;cr(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return hr;let s=o.pow(r,e),i=(e+P)/pe;return function(l,a){let u=l;if(u.is0(a))return a;if(cr(u,a)!==1)throw new Error("Cannot find square root");let f=n,p=u.mul(u.ONE,s),d=u.pow(a,e),m=u.pow(a,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))return u.ZERO;let g=1,h=u.sqr(d);for(;!u.eql(h,u.ONE);)if(g++,h=u.sqr(h),g===f)throw new Error("Cannot find square root");let b=P<<BigInt(f-g-1),x=u.pow(p,b);f=g,p=u.sqr(x),d=u.mul(d,p),m=u.mul(m,x);}return m}}function Zo(t){return t%fr===ur?hr:t%pr===dr?qo:t%mr===Ko?Go(t):gr(t)}var ee=(t,e)=>(D(t,e)&P)===P,Yo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function br(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=Yo.reduce((r,o)=>(r[o]="function",r),e);if(de(t,n),X(t.BYTES,"BYTES"),X(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=P)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Jo(t,e,n){let r=t;if(n<V)throw new Error("invalid exponent, negatives unsupported");if(n===V)return r.ONE;if(n===P)return e;let o=r.ONE,s=e;for(;n>V;)n&P&&(o=r.mul(o,s)),s=r.sqr(s),n>>=P;return o}function it(t,e,n=false){let r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),s=e.reduce((c,l,a)=>r.is0(l)?c:(o[a]=c,r.mul(c,l)),r.ONE),i=r.inv(s);return e.reduceRight((c,l,a)=>r.is0(l)?c:(o[a]=r.mul(c,o[a]),r.mul(c,l)),i),o}function cr(t,e){let n=t,r=(n.ORDER-P)/pe,o=n.pow(e,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),c=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!c)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Wo(t,e){if(e!==void 0&&Nt(e),t<=V)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let n=Kt(t);if(e!==void 0&&e<n)throw new Error(`invalid n length: expected bit length (${n}) >= n.length (${e})`);let r=e!==void 0?e:n,o=Math.ceil(r/8);return {nBitLength:r,nByteLength:o}}var lr=new WeakMap,st=class{ORDER;BITS;BYTES;isLE;ZERO=V;ONE=P;_lengths;_mod;constructor(e,n={}){if(e<=P)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:true}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:s}=Wo(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this);}create(e){return D(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return V<=e&&e<this.ORDER}is0(e){return e===V}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&P)===P}neg(e){return D(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return D(e*e,this.ORDER)}add(e,n){return D(e+n,this.ORDER)}sub(e,n){return D(e-n,this.ORDER)}mul(e,n){return D(e*n,this.ORDER)}pow(e,n){return Jo(this,e,n)}div(e,n){return D(e*ar(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return ar(e,this.ORDER)}sqrt(e){let n=lr.get(this);return n||lr.set(this,n=Zo(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?or(e,this.BYTES):Ut(e,this.BYTES)}fromBytes(e,n=false){j(e);let{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:c}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let a=new Uint8Array(o);a.set(e,s?0:a.length-e.length),e=a;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let l=s?Q(e):Vt(e);if(c&&(l=D(l,i)),!n&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return it(this,e)}cmov(e,n,r){return xe(r,"condition"),r?n:e}};Object.freeze(st.prototype);function at(t,e={}){return new st(t,e)}var ct=BigInt(0),Wt=BigInt(1);function xr(t,e){let n=e.negate();return t?n:e}function ut(t,e){let n=it(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function Sr(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Zt(t,e){Sr(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=ir(t),i=BigInt(t);return {windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function yr(t,e,n){let{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n,c=Number(t&o),l=t>>i;c>r&&(c-=s,l+=Wt);let a=e*r,u=a+Math.abs(c)-1,f=c===0,p=c<0,d=e%2!==0;return {nextN:l,offset:u,isZero:f,isNeg:p,isNegF:d,offsetF:a}}var Yt=new WeakMap,kr=new WeakMap;function Jt(t){return kr.get(t)||1}function vr(t){if(t!==ct)throw new Error("invalid wNAF")}var lt=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>ct;)n&Wt&&(r=r.add(o)),o=o.double(),n>>=Wt;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Zt(n,this.bits),s=[],i=e,c=i;for(let l=0;l<r;l++){c=i,s.push(c);for(let a=1;a<o;a++)c=c.add(i),s.push(c);i=c.double();}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Zt(e,this.bits);for(let c=0;c<i.windows;c++){let{nextN:l,offset:a,isZero:u,isNeg:f,isNegF:p,offsetF:d}=yr(r,c,i);r=l,u?s=s.add(xr(p,n[d])):o=o.add(xr(f,n[a]));}return vr(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.ZERO){let s=Zt(e,this.bits);for(let i=0;i<s.windows&&r!==ct;i++){let{nextN:c,offset:l,isZero:a,isNeg:u}=yr(r,i,s);if(r=c,!a){let f=n[l];o=o.add(u?f.negate():f);}}return vr(r),o}getPrecomputes(e,n,r){let o=Yt.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Yt.set(n,o))),o}cached(e,n,r){let o=Jt(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let s=Jt(e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){Sr(n,this.bits),kr.set(e,n),Yt.delete(e);}hasCache(e){return Jt(e)!==1}};function wr(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return br(e),e}else return at(t,{isLE:n})}function Er(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let l of ["p","n","h"]){let a=e[l];if(!(typeof a=="bigint"&&a>ct))throw new Error(`CURVE.${l} must be positive bigint`)}let o=wr(e.p,n.Fp,r),s=wr(e.n,n.Fn,r),c=["Gx","Gy","a","d"];for(let l of c)if(!o.isValid(e[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Tr(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var se=BigInt(0),F=BigInt(1),Xt=BigInt(2),Xo=BigInt(8);function Qo(t,e,n,r){let o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),c=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,c)}function Rr(t,e={}){let n=e,r=Er("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r,i=r.CURVE,{h:c}=i;de(n,{},{uvRatio:"function"});let l=Xt<<BigInt(s.BYTES*8)-F,a=g=>o.create(g),u=n.uvRatio===void 0?(g,h)=>{try{return {isValid:!0,value:o.sqrt(o.div(g,h))}}catch{return {isValid:false,value:se}}}:n.uvRatio;if(!Qo(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(g,h,b=false){let x=b?F:se;return Ht("coordinate "+g,h,x,l),h}function p(g){if(!(g instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,F,a(i.Gx*i.Gy));static ZERO=new d(se,F,F,se);static Fp=o;static Fn=s;X;Y;Z;T;constructor(h,b,x,y){this.X=f("x",h),this.Y=f("y",b),this.Z=f("z",x,true),this.T=f("t",y),Object.freeze(this);}static CURVE(){return i}static fromAffine(h){if(h instanceof d)throw new Error("extended point not allowed");let{x:b,y:x}=h||{};return f("x",b),f("y",x),new d(b,x,F,a(b*x))}static fromBytes(h,b=false){let x=o.BYTES,{a:y,d:R}=i;h=Me(j(h,x,"point")),xe(b,"zip215");let E=Me(h),_=h[x-1];E[x-1]=_&-129;let I=Q(E),w=b?l:o.ORDER;Ht("point.y",I,se,w);let C=a(I*I),L=a(C-F),M=a(R*C-y),{isValid:v,value:S}=u(L,M);if(!v)throw new Error("bad point: invalid y coordinate");let O=(S&F)===F,A=(_&128)!==0;if(!b&&S===se&&A)throw new Error("bad point: x=0 and x_0=1");return A!==O&&(S=a(-S)),d.fromAffine({x:S,y:I})}static fromHex(h,b=false){return d.fromBytes(tr(h),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,b=true){return m.createCache(this,h),b||this.multiply(Xt),this}assertValidity(){let h=this,{a:b,d:x}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:y,Y:R,Z:E,T:_}=h,I=a(y*y),w=a(R*R),C=a(E*E),L=a(C*C),M=a(I*b),v=a(C*a(M+w)),S=a(L+a(x*a(I*w)));if(v!==S)throw new Error("bad point: equation left != right (1)");let O=a(y*R),A=a(E*_);if(O!==A)throw new Error("bad point: equation left != right (2)")}equals(h){p(h);let{X:b,Y:x,Z:y}=this,{X:R,Y:E,Z:_}=h,I=a(b*_),w=a(R*y),C=a(x*_),L=a(E*y);return I===w&&C===L}is0(){return this.equals(d.ZERO)}negate(){return new d(a(-this.X),this.Y,this.Z,a(-this.T))}double(){let{a:h}=i,{X:b,Y:x,Z:y}=this,R=a(b*b),E=a(x*x),_=a(Xt*a(y*y)),I=a(h*R),w=b+x,C=a(a(w*w)-R-E),L=I+E,M=L-_,v=I-E,S=a(C*M),O=a(L*v),A=a(C*v),k=a(M*L);return new d(S,O,k,A)}add(h){p(h);let{a:b,d:x}=i,{X:y,Y:R,Z:E,T:_}=this,{X:I,Y:w,Z:C,T:L}=h,M=a(y*I),v=a(R*w),S=a(_*x*L),O=a(E*C),A=a((y+R)*(I+w)-M-v),k=O-S,T=O+S,B=a(v-b*M),U=a(A*k),z=a(T*B),H=a(A*B),N=a(k*T);return new d(U,z,N,H)}subtract(h){return p(h),this.add(h.negate())}multiply(h){if(!s.isValidNot0(h))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:x}=m.cached(this,h,y=>ut(d,y));return ut(d,[b,x])[0]}multiplyUnsafe(h){if(!s.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===se?d.ZERO:this.is0()||h===F?this:m.unsafe(this,h,b=>ut(d,b))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return m.unsafe(this,i.n).is0()}toAffine(h){let b=this,x=h,{X:y,Y:R,Z:E}=b,_=b.is0();x==null&&(x=_?Xo:o.inv(E));let I=a(y*x),w=a(R*x),C=o.mul(E,x);if(_)return {x:se,y:F};if(C!==F)throw new Error("invZ was invalid");return {x:I,y:w}}clearCofactor(){return c===F?this:this.multiplyUnsafe(c)}toBytes(){let{x:h,y:b}=this.toAffine(),x=o.toBytes(b);return x[x.length-1]|=h&F?128:0,x}toHex(){return $t(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=new lt(d,s.BITS);return s.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var ft=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e;}static fromBytes(e){qt();}static fromHex(e){qt();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){return this.ep.toAffine(e)}toHex(){return $t(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return true}isSmallOrder(){return false}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function Ir(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');let r=e,o=n;de(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:c,Fn:l}=t,a=r.outputLen,u=2*c.BYTES;if(a!==void 0&&(X(a,"hash.outputLen"),a!==u))throw new Error(`hash.outputLen must be ${u}, got ${a}`);let f=o.randomBytes===void 0?nr:o.randomBytes,p=o.adjustScalarBytes===void 0?v=>v:o.adjustScalarBytes,d=o.domain===void 0?(v,S,O)=>{if(xe(O,"phflag"),S.length||O)throw new Error("Contexts/pre-hash are not supported");return v}:o.domain;function m(v){return l.create(Q(v))}function g(v){let S=I.secretKey;j(v,I.secretKey,"secretKey");let O=j(r(v),2*S,"hashedSecretKey"),A=p(O.slice(0,S)),k=O.slice(S,2*S),T=m(A);return {head:A,prefix:k,scalar:T}}function h(v){let{head:S,prefix:O,scalar:A}=g(v),k=i.multiply(A),T=k.toBytes();return {head:S,prefix:O,scalar:A,point:k,pointBytes:T}}function b(v){return h(v).pointBytes}function x(v=Uint8Array.of(),...S){let O=Y(...S);return m(r(d(O,j(v,void 0,"context"),!!s)))}function y(v,S,O={}){v=j(v,void 0,"message"),s&&(v=s(v));let{prefix:A,scalar:k,pointBytes:T}=h(S),B=x(O.context,A,v),U=i.multiply(B).toBytes(),z=x(O.context,U,T,v),H=l.create(B+z*k);if(!l.isValid(H))throw new Error("sign failed: invalid s");let N=Y(U,l.toBytes(H));return j(N,I.signature,"result")}let R={zip215:o.zip215};function E(v,S,O,A=R){let{context:k}=A,T=A.zip215===void 0?!!R.zip215:A.zip215,B=I.signature;v=j(v,B,"signature"),S=j(S,void 0,"message"),O=j(O,I.publicKey,"publicKey"),T!==void 0&&xe(T,"zip215"),s&&(S=s(S));let U=B/2,z=v.subarray(0,U),H=Q(v.subarray(U,B)),N,ne,ke;try{N=t.fromBytes(O,T),ne=t.fromBytes(z,T),ke=i.multiplyUnsafe(H);}catch{return false}if(!T&&N.isSmallOrder())return false;let Hr=x(k,z,O,S);return ne.add(N.multiplyUnsafe(Hr)).subtract(ke).clearCofactor().is0()}let _=c.BYTES,I={secretKey:_,publicKey:_,signature:2*_,seed:_};function w(v){return v=v===void 0?f(I.seed):v,j(v,I.seed,"seed")}function C(v){return rt(v)&&v.length===I.secretKey}function L(v,S){try{return !!t.fromBytes(v,S===void 0?R.zip215:S)}catch{return false}}let M={getExtendedPublicKey:h,randomSecretKey:w,isValidSecretKey:C,isValidPublicKey:L,toMontgomery(v){let{y:S}=t.fromBytes(v),O=I.publicKey,A=O===32;if(!A&&O!==57)throw new Error("only defined for 25519 and 448");let k=A?c.div(F+S,F-S):c.div(S-F,S+F);return c.toBytes(k)},toMontgomerySecret(v){let S=I.secretKey;j(v,S);let O=r(v.subarray(0,S));return p(O).subarray(0,S)}};return Object.freeze(I),Object.freeze(M),Object.freeze({keygen:Tr(w,b),getPublicKey:b,sign:y,verify:E,utils:M,Point:t,lengths:I})}var ns=BigInt(0),te=BigInt(1),_r=BigInt(2);var rs=BigInt(5),os=BigInt(8),ye=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),rn={p:ye,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:os,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ss(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=ye,c=t*t%s*t%s,l=q(c,_r,s)*c%s,a=q(l,te,s)*t%s,u=q(a,rs,s)*a%s,f=q(u,e,s)*u%s,p=q(f,n,s)*f%s,d=q(p,r,s)*p%s,m=q(d,o,s)*d%s,g=q(m,o,s)*d%s,h=q(g,e,s)*u%s;return {pow_p_5_8:q(h,_r,s)*t%s,b2:c}}function is(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var en=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function on(t,e){let n=ye,r=D(e*e*e,n),o=D(r*r*e,n),s=ss(t*o).pow_p_5_8,i=D(t*r*s,n),c=D(e*i*i,n),l=i,a=D(i*en,n),u=c===t,f=c===D(-t,n),p=c===D(-t*en,n);return u&&(i=l),(f||p)&&(i=a),ee(i,n)&&(i=D(-i,n)),{isValid:u||f,value:i}}var ae=Rr(rn,{uvRatio:on}),ie=ae.Fp,Lr=ae.Fn;function as(t){return Ir(ae,et,Object.assign({adjustScalarBytes:is,zip215:true},t))}var Br=as({});var tn=en;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var ls=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var Cr=t=>on(te,t),ds=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),nn=t=>ie.create(Q(t)&ds);var ce=class t extends ft{static BASE=new t(ae.BASE);static ZERO=new t(ae.ZERO);static Fp=ie;static Fn=Lr;constructor(e){super(e);}static fromAffine(e){return new t(ae.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoPoint expected")}init(e){return new t(e)}static fromBytes(e){K(e,32);let{a:n,d:r}=rn,o=ye,s=R=>ie.create(R),i=nn(e);if(!sr(ie.toBytes(i),e)||ee(i,o))throw new Error("invalid ristretto255 encoding 1");let c=s(i*i),l=s(te+n*c),a=s(te-n*c),u=s(l*l),f=s(a*a),p=s(n*r*u-f),{isValid:d,value:m}=Cr(s(p*f)),g=s(m*a),h=s(m*g*p),b=s((i+i)*g);ee(b,o)&&(b=s(-b));let x=s(l*h),y=s(b*x);if(!d||ee(y,o)||x===ns)throw new Error("invalid ristretto255 encoding 2");return new t(new ae(b,x,te,y))}static fromHex(e){return t.fromBytes(Ae(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,s=ye,i=h=>ie.create(h),c=i(i(r+n)*i(r-n)),l=i(e*n),a=i(l*l),{value:u}=Cr(i(c*a)),f=i(u*c),p=i(u*l),d=i(f*p*o),m;if(ee(o*d,s)){let h=i(n*tn),b=i(e*tn);e=h,n=b,m=i(f*ls);}else m=p;ee(e*d,s)&&(n=i(-n));let g=i((r-n)*m);return ee(g,s)&&(g=i(-g)),ie.toBytes(g)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:s}=e.ep,i=a=>ie.create(a),c=i(n*s)===i(r*o),l=i(r*s)===i(n*o);return c||l}is0(){return this.equals(t.ZERO)}};Object.freeze(ce.BASE);Object.freeze(ce.ZERO);Object.freeze(ce.prototype);Object.freeze(ce);var Mr=`-----BEGIN PUBLIC KEY-----
1
+ var Gr=0;function bt(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++Gr,o=Date.now?Date.now():0;for(let s=0;s<16;s++)e[s]=(s<6?r>>>s*8:o>>>(s-6)*8)&255;}e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=[];for(let r=0;r<16;r++)n.push(e[r].toString(16).padStart(2,"0"));return `${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}-${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}function Hs(t){return {v:1,task:t.task,goal:t.goal,rules:t.rules??[],facts:t.facts??[],refs:t.refs??[],...t.delta?{delta:t.delta}:{},outputContract:t.outputContract}}var xt=class{id;exact=false;constructor(e="heuristic"){this.id=e;}count(e){if(e.length===0)return 0;let n=e.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],r=0;for(let o of n){let s=o[0];if(/\s/.test(s)){let i=(o.match(/\n/g)??[]).length;r+=i+Math.floor(Math.max(0,o.length-1)/2);}else /[A-Za-z]/.test(s)?r+=Math.max(1,Math.ceil(o.length/4)):/\d/.test(s)?r+=Math.max(1,Math.ceil(o.length/2)):r+=1;}return Math.max(r,Math.ceil(e.length/4))}},he=new xt;var yt=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=he){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){return this.modelToTokenizer.set(e,n),this}resolve(e){let n=e.tokenizer?this.estimators.get(e.tokenizer):void 0;if(n)return n;if(e.model){let r=this.modelToTokenizer.get(e.model);if(r){let o=this.estimators.get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},pn=new yt;var vt=class{constructor(e,n){this.encoder=n;this.id=e;}encoder;id;exact=true;count(e){return e.length===0?0:this.encoder.encode(e).length}},mn={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","o1","o1-mini","o3","o3-mini","o4-mini"],cl100k_base:["gpt-4","gpt-4-turbo","gpt-3.5-turbo","text-embedding-3-small","text-embedding-3-large"]};async function Zr(t,e={}){let n=e.codificaciones??["o200k_base","cl100k_base"],r=false;for(let o of n){let s;try{s=await import(`gpt-tokenizer/encoding/${o}`);}catch{continue}if(typeof s.encode=="function"){t.register(new vt(o,s)),r=true;for(let i of mn[o]??[])t.mapModel(i,o),t.mapModel(`openai/${i}`,o);}}return r}var Xs=mn,Qs=Zr;var ge=class{avoidedLlm=0;baselineLlm=1;actualLlm=0;baselineRetrieval=0;actualRetrieval=0;baselineTools=0;actualTools=0;retries=0;baselineInput=0;actualInput=0;eliminatedInput=0;compressedInput=0;baselineOutput=0;actualOutput=0;eliminatedOutput=0;providerCachedInput=0;sentInputLocal=0;removedInputLocal=0;estimatorExact=false;repairOutput=0;repairInput=0;compressionReport=void 0;eliminate(e){this.eliminatedInput+=Math.max(0,e);}compress(e,n){this.compressedInput+=Math.max(0,e-n);}providerCached(e){this.providerCachedInput+=Math.max(0,e);}avoidCall(e,n){this.avoidedLlm+=1,this.actualLlm=0,this.baselineInput=e,this.baselineOutput=n;}get publishedBaselineOutput(){return this.avoidedLlm===0?Math.max(0,this.actualOutput-this.repairOutput):this.baselineOutput}estimateCost(e){let n=this.avoidedLlm===0,r="estimated";if(n)if(this.actualInput>0&&this.sentInputLocal>0){let f=this.actualInput/this.sentInputLocal,p=Math.max(0,this.actualInput-this.repairInput);this.baselineInput=p+Math.round(f*this.removedInputLocal),r=this.removedInputLocal===0?"measured":"estimated";}else this.actualInput>0?(this.baselineInput=this.actualInput,r="measured"):(this.baselineInput=0,r="unmeasured");let o=n?Math.max(0,this.actualOutput-this.repairOutput):this.baselineOutput,s=e.cachedInputPer1k??e.inputPer1k,i=Math.min(this.providerCachedInput,this.actualInput),c=f=>Math.max(0,f-i)/1e3*e.inputPer1k+i/1e3*s,l=c(this.baselineInput)+o/1e3*e.outputPer1k,a=c(this.actualInput)+this.actualOutput/1e3*e.outputPer1k,u=l===0?0:1-a/l;return {baselineEstimate:hn(l),actual:hn(a),netSavings:Yr(u),basis:r}}};function hn(t){return Math.round(t*1e10)/1e10}function Yr(t){return Math.round(t*1e6)/1e6}var Wr=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Jr=new TextEncoder;function G(t,e){return t>>>e|t<<32-e}function gn(t){let e=Jr.encode(t),n=e.length*8,r=(e.length+8>>6)+1,o=new Uint8Array(r*64);o.set(e),o[e.length]=128;let s=new DataView(o.buffer);s.setUint32(o.length-8,Math.floor(n/4294967296)),s.setUint32(o.length-4,n>>>0);let i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),c=new Uint32Array(64);for(let a=0;a<o.length;a+=64){for(let x=0;x<16;x++)c[x]=s.getUint32(a+x*4);for(let x=16;x<64;x++){let y=c[x-15],R=c[x-2],E=G(y,7)^G(y,18)^y>>>3,_=G(R,17)^G(R,19)^R>>>10;c[x]=c[x-16]+E+c[x-7]+_|0;}let u=i[0],f=i[1],p=i[2],d=i[3],m=i[4],g=i[5],h=i[6],b=i[7];for(let x=0;x<64;x++){let y=G(m,6)^G(m,11)^G(m,25),R=m&g^~m&h,E=b+y+R+Wr[x]+c[x]|0,_=G(u,2)^G(u,13)^G(u,22),I=u&f^u&p^f&p,w=_+I|0;b=h,h=g,g=m,m=d+E|0,d=p,p=f,f=u,u=E+w|0;}i[0]=i[0]+u|0,i[1]=i[1]+f|0,i[2]=i[2]+p|0,i[3]=i[3]+d|0,i[4]=i[4]+m|0,i[5]=i[5]+g|0,i[6]=i[6]+h|0,i[7]=i[7]+b|0;}let l="";for(let a=0;a<8;a++)l+=(i[a]>>>0).toString(16).padStart(8,"0");return l}var Xr=/\s+/g;function Qr(t){return t.trim().replace(Xr," ").toLowerCase()}function be(t){return gn(t)}function Te(t){return JSON.stringify(wt(t))}function wt(t){if(Array.isArray(t))return t.map(wt);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=wt(t[n]);return e}return t}function eo(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function St(t){let e=t.context??{},n=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(`
2
+ `),r=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${Qr(s.content)}`).join(`
3
+ `),o=(t.tools??[]).map(s=>({id:s.id,risk:s.risk,parameters:s.parameters??null})).sort((s,i)=>s.id.localeCompare(i.id));return {model:t.model,modelFamily:eo(t.model),messages:t.messages,normalizedText:r,systemPromptHash:be(n),toolsetHash:be(Te(o)),structuredDataHash:t.structuredData!==void 0?be(Te(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.contractId??"none",contractId:t.response?.contractId??null,temperature:t.temperature??null,seed:t.seed??null,tenantId:e.tenantId??"anonymous",authorizationScope:e.authorizationScope??"default",principal:e.sessionId??null,locale:e.locale??"und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}function bn(t){let e=Te({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,modelFamily:t.modelFamily,model:t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,data:t.structuredDataHash,locale:t.locale,temperature:t.temperature,seed:t.seed,knowledgeEpoch:t.knowledgeEpoch,freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${be(e)}`}function xn(t){let e=Te({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,model:t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,data:t.structuredDataHash,temperature:t.temperature,seed:t.seed});return `bvsala:inflight:${be(e)}`}var to=new RegExp("\\b("+["now|today|current|currently|latest|live|price|prices|stock|availability|weather|score|breaking","ahora|hoy|actual|actualmente|ultimo|\xFAltimo|precio|precios|disponibilidad|cotizacion|cotizaci\xF3n","ara|avui|preu|preus|disponibilitat|darrer","maintenant|aujourd'hui|actuel|actuelle|dernier|prix|disponibilite|disponibilit\xE9|meteo|m\xE9t\xE9o","jetzt|heute|aktuell|aktuelle|neueste|preis|preise|verfugbarkeit|verf\xFCgbarkeit|wetter|kurs","adesso|oggi|attuale|ultimo|prezzo|prezzi|disponibilita|disponibilit\xE0|meteo","agora|hoje|atual|ultimo|\xFAltimo|preco|pre\xE7o|precos|pre\xE7os|disponibilidade|cotacao|cota\xE7\xE3o","nu|vandaag|huidige|laatste|prijs|prijzen|beschikbaarheid|weer|koers","teraz|dzisiaj|dzis|dzi\u015B|aktualny|aktualna|najnowszy|cena|ceny|dostepnosc|dost\u0119pno\u015B\u0107|pogoda","simdi|\u015Fimdi|bugun|bug\xFCn|guncel|g\xFCncel|son|fiyat|fiyatlar|stok|hava","sekarang|hari ini|terkini|terbaru|harga|ketersediaan|cuaca","bay gio|b\xE2y gi\u1EDD|hom nay|h\xF4m nay|hien tai|hi\u1EC7n t\u1EA1i|moi nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),no=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nuestro|nuestra|cuenta|factura|pedido|saldo|suscripcion|suscripci\xF3n|perfil","meu|meva|nostre|compte|factura|comanda|saldo|subscripcio|subscripci\xF3|perfil","mon|ma|mes|notre|nos|compte|solde|facture|commande|abonnement|profil","mein|meine|meinem|unser|unsere|konto|kontostand|saldo|rechnung|bestellung|abo|abonnement|profil","mio|mia|miei|nostro|nostra|conto|saldo|fattura|ordine|abbonamento|profilo","meu|minha|meus|nosso|nossa|conta|saldo|fatura|pedido|assinatura|perfil","mijn|onze|ons|rekening|saldo|factuur|bestelling|abonnement|profiel","moj|m\xF3j|moja|moje|nasz|nasza|konto|saldo|faktura|zamowienie|zam\xF3wienie|subskrypcja|profil","benim|bizim|hesap|hesabim|hesab\u0131m|bakiye|fatura|siparis|sipari\u015F|abonelik|profil","saya|kami|akun|saldo|tagihan|pesanan|langganan|profil","cua toi|c\u1EE7a t\xF4i|tai khoan|t\xE0i kho\u1EA3n|so du|s\u1ED1 d\u01B0|hoa don|h\xF3a \u0111\u01A1n|don hang|\u0111\u01A1n h\xE0ng|thue bao|thu\xEA bao"].join("|")+")\\b","i");function kt(t){let e=[],n=t.normalizedText,r=(t.original.tools??[]).some(p=>p.risk==="write"||p.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||to.test(n),s=no.test(n),i=(t.temperature??0)>.3&&t.seed==null;r&&e.push("write/destructive tools present"),o&&e.push("freshness-sensitive request"),s&&e.push("personalized/account-scoped request"),i&&e.push("stochastic sampling (temp>0.3, no seed)");let c=o&&(t.freshnessBucket==null||t.freshnessBucket==="any"),l=t.freshnessBucket==="live",a=s&&t.principal==null,u=!i&&!c&&!l&&!a&&!r;r&&e.push("write/destructive tools \u2192 exact cache off (side effects must execute)"),l&&e.push("freshnessBucket=live \u2192 exact cache off (answer must be current)"),c&&e.push("freshness-sensitive without a freshness bucket \u2192 exact cache off"),a&&e.push("personalized request with no principal (context.sessionId) \u2192 exact cache off");let f=!r&&!o&&!s&&!i&&t.freshnessBucket!=="day";return {allowExactCache:u,allowSemanticCache:f,allowSingleflight:!r&&!a,allowCompression:true,requiresFreshData:o,hasSideEffects:r,isPersonalized:s,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var ze=class{store=new Map;maxEntries;now;constructor(e={}){this.maxEntries=e.maxEntries??1e4,this.now=e.now??(()=>Date.now());}async get(e){let n=this.store.get(e);return n?n.expiresAtMs!==null&&this.now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),n.value):null}async set(e,n,r){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let o=this.store.keys().next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:n,expiresAtMs:r!=null?this.now()+r:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};var Ne=class{inflight=new Map;waiters=new Map;async run(e,n){let r=this.inflight.get(e);if(r)return this.waiters.set(e,(this.waiters.get(e)??1)+1),{value:await r,coalesced:true};let o=(async()=>n())();this.inflight.set(e,o),this.waiters.set(e,1);try{return {value:await o,coalesced:!1}}finally{this.inflight.delete(e),this.waiters.delete(e);}}get activeKeys(){return this.inflight.size}};function ro(t,e){let n=Math.min(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i++){let c=t[i],l=e[i];r+=c*l,o+=c*c,s+=l*l;}return o===0||s===0?0:r/(Math.sqrt(o)*Math.sqrt(s))}var oo=new Set(["no","not","never","none","cannot","cant","without","nor","nt","isnt","arent","wasnt","werent","dont","doesnt","didnt","wont","cant","shouldnt"]),so=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what","whats","which","who","whom","how","when","where","me","my","i","you","please","tell","give","show","find","do","does","did","be","that","this","it","with","as","at","by","from","about","into","over","than","then","s"]);function yn(t){return (t.match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function io(t,e){if(t.length!==e.length)return false;let n=new Map;for(let r of t)n.set(r,(n.get(r)??0)+1);for(let r of e){let o=n.get(r);if(!o)return false;n.set(r,o-1);}return true}function vn(t){return t.split(/\s+/).filter(Boolean)}function wn(t){return t.filter(e=>oo.has(e.replace(/'/g,""))||e.endsWith("n't")).length}function ao(t,e){if(!io(yn(t),yn(e)))return false;let n=vn(t),r=vn(e);if(wn(n)!==wn(r))return false;let o=a=>a.length>1&&!so.has(a)&&!/^\d/.test(a),s=new Set(n.filter(o)),i=new Set(r.filter(o));if(s.size===0&&i.size===0)return true;let c=0;for(let a of s)i.has(a)&&c++;let l=s.size+i.size-c;return l===0?true:c/l>=.75}var Sn=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;constructor(e){this.embed=e.embed,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??.9,this.acceptThreshold=e.acceptThreshold??.85,this.ttlMs=e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now());}async find(e){if(this.records.length===0)return null;let n=await this.embed(e.normalizedText),r=null;for(let o of this.records){if(o.tenantId!==e.tenantId||o.authorizationScope!==e.authorizationScope||o.principal!==e.principal||o.knowledgeEpoch!==e.knowledgeEpoch||o.contractId!==e.contractId||o.model!==e.model||o.systemPromptHash!==e.systemPromptHash||o.structuredDataHash!==e.structuredDataHash||o.locale!==e.locale||o.schemaVersion!==e.schemaVersion||o.safetyPolicyVersion!==e.safetyPolicyVersion||this.ttlMs!=null&&this.now()-o.storedAtMs>this.ttlMs)continue;let s=ro(n,o.embedding);if(s<this.similarityThreshold||!ao(e.normalizedText,o.query))continue;let i=this.verify?await this.verify(e.normalizedText,o.query):s,c=Math.min(s,i);c<this.acceptThreshold||(!r||c>r.confidence)&&(r={record:o,similarity:s,verifierScore:i,confidence:c,ageMs:this.now()-o.storedAtMs});}return r}async store(e,n){let r=await this.embed(e.normalizedText);this.records.length>=this.maxRecords&&this.records.shift(),this.records.push({embedding:r,query:e.normalizedText,answer:n,tenantId:e.tenantId,authorizationScope:e.authorizationScope,principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.structuredDataHash,locale:e.locale,schemaVersion:e.schemaVersion,safetyPolicyVersion:e.safetyPolicyVersion,storedAtMs:this.now()});}invalidateEpoch(e){let n=0;for(let r=this.records.length-1;r>=0;r--)this.records[r].knowledgeEpoch===e&&(this.records.splice(r,1),n++);return n}get size(){return this.records.length}};var Et=class{resolvers=[];register(e){return this.resolvers.push(e),this}try(e){for(let n of this.resolvers)try{let r=n.try(e);if(r)return r}catch{}return null}get size(){return this.resolvers.length}},co={name:"arithmetic",try(t){let n=(t.normalizedText.match(/(?:what\s+is|calculate|compute|how\s+much\s+is|cu[aá]nto\s+es)\s+([0-9+\-*/%.()\s]+)\??$/i)?.[1]??lo(t.normalizedText))?.trim();if(!n)return null;let r=fo(n);return r===null||!Number.isFinite(r)?null:{text:uo(r),data:{value:r},resolver:"arithmetic"}}};function lo(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function uo(t){return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function fo(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],r=[],o={"+":1,"-":1,"*":2,"/":2,"%":2},s=c=>{let l=n.pop(),a=n.pop();if(a===void 0||l===void 0)return false;switch(c){case "+":return n.push(a+l),true;case "-":return n.push(a-l),true;case "*":return n.push(a*l),true;case "/":return l===0?false:(n.push(a/l),true);case "%":return l===0?false:(n.push(a%l),true);default:return false}},i=true;for(let c of e)if(/^\d/.test(c))n.push(Number(c)),i=false;else if(c==="(")r.push(c),i=true;else if(c===")"){for(;r.length&&r[r.length-1]!=="(";)if(!s(r.pop()))return null;if(r.pop()!=="(")return null;i=false;}else {if(i)return null;for(;r.length&&r[r.length-1]!=="("&&o[r[r.length-1]]>=o[c];)if(!s(r.pop()))return null;r.push(c),i=true;}for(;r.length;){let c=r.pop();if(c==="("||!s(c))return null}return n.length===1?n[0]:null}function kn(){return new Et().register(co)}var po=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,En=/\b(who|what|when|where|which|how many|how much|define|definition|qui[eé]n|qu[eé]|cu[aá]ndo|d[oó]nde|cu[aá]nto)\b/i,mo=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,$e=class{classifier;maxRounds;constructor(e={}){this.classifier=e.classifier,this.maxRounds=e.maxRounds??2;}classify(e){let n=e.original.retrieval?.mode,r=e.normalizedText;if((e.original.tools??[]).some(i=>i.risk==="write"||i.risk==="destructive")&&/\b(create|update|delete|send|pay|book|cancel|crea|actualiza|elimina|env[ií]a|paga)\b/i.test(r))return W("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return W("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(mo.test(r)&&!En.test(r))return W("NO_RETRIEVAL",.8,"self-contained transformation",0);let s=this.classifier?.classify(r);return s&&s.confidence>=.75?W(s.executionClass,s.confidence,"local classifier",ho(s.executionClass,this.maxRounds)):n==="single"?W("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?W("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):po.test(r)?W("MULTI_HOP_RETRIEVAL",.7,"comparison/compound question",Math.min(this.maxRounds,2)):En.test(r)?W("SINGLE_RETRIEVAL",.65,"single factual lookup",1):W("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function ho(t,e){return t==="SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function W(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var Ve=class{maxTools;scoreIntentMatch;constructor(e={}){this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??go;}passthrough(e){if(!e||e.length===0)return {tools:[],droppedIds:[],reason:"no tools provided"};let n=e.slice(0,this.maxTools),r=e.slice(this.maxTools).map(o=>o.id);return {tools:n,droppedIds:r,reason:`router off: caller tools passed through unfiltered (${n.length}/${e.length}, capped at maxTools=${this.maxTools}; risk gating is the caller's responsibility while routing is off)`}}select(e,n,r){if(!n||n.length===0)return {tools:[],droppedIds:[],reason:"no tools provided"};let o=r==="TOOL_ACTION",c=n.filter(u=>o||u.risk==="read").map(u=>({tool:u,score:this.scoreIntentMatch(e,u)})).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,this.maxTools).map(u=>u.tool),l=new Set(c.map(u=>u.id)),a=n.filter(u=>!l.has(u.id)).map(u=>u.id);return {tools:c,droppedIds:a,reason:`selected ${c.length}/${n.length} by intent match (writes ${o?"allowed":"blocked"})`}}};function go(t,e){let n=t.toLowerCase(),r=0;for(let o of e.intents){let s=o.toLowerCase();n.includes(s)?r+=2:s.split(/\s+/).some(i=>i.length>3&&n.includes(i))&&(r+=1);}return r}function bo(t){let e=new Set,n=[];for(let r of t){let o=r.hash??yo(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function xo(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((i,c)=>(c.score??0)-(i.score??0));if(r.length<=n)return r;let o=r[0]?.score??0;if(o<=0)return r.slice(0,e.maxDocuments);let s=[];for(let i of r){let c=(i.score??0)/o;if(s.length<n||c>=.4&&s.length<e.maxDocuments)s.push(i);else break}return s}async function Tn(t,e){if(t.execution==="NO_RETRIEVAL"||t.execution==="TOOL_ACTION"||t.execution==="NON_CACHEABLE"||!e.retriever)return {docs:[],rounds:0,retrievedCount:0,keptCount:0};let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,r=[];for(let i=0;i<n;i++){let c=await e.retriever.retrieve(t.query,t.maxDocuments*2);r.push(...c);}let o=r.length;r=bo(r),e.reranker&&(r=await e.reranker.rerank(t.query,r));let s=xo(r,{maxDocuments:t.maxDocuments});return {docs:s,rounds:n,retrievedCount:o,keptCount:s.length}}function yo(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function ji(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function Pi(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&ko(o)?Object.assign(n.userPreferences,o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let s=wo(n,r);s?s.push(...o.map(String)):n.confirmedFacts[r]=o;}for(let r of e.remove??[])delete n.confirmedFacts[r],delete n.userPreferences[r],So(n,r);return n}function Fi(t){let e=t.rawTurns??3,n=[],r=vo(t.state);r&&n.push({role:"system",content:`Conversation state:
4
+ ${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function vo(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`facts: ${JSON.stringify(t.confirmedFacts)}`),Object.keys(t.userPreferences).length&&e.push(`preferences: ${JSON.stringify(t.userPreferences)}`),t.decisions.length&&e.push(`decisions: ${t.decisions.join("; ")}`),t.openItems.length&&e.push(`open: ${t.openItems.join("; ")}`),e.join(`
5
+ `)}function wo(t,e){switch(e){case "goals":return t.goals;case "decisions":return t.decisions;case "openItems":return t.openItems;case "evidenceRefs":return t.evidenceRefs;default:return null}}function So(t,e){for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function ko(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Rn={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function In(t,e={}){let n=e.delimiter??",",r=e.indent??" ",s=t.split(`
6
+ `).filter(l=>l.trim().length>0).map(l=>({indent:Eo(l,r),content:l.slice(On(l,r))}));if(s.length===0)return {};let i=s[0];if(i.indent===0){let l=i.content.match(/^\[(\d+)\]\{(.*)\}:\s*$/);if(l){let u=xe(l[2],n),f=Number(l[1]),p=[];for(let d=0,m=1;d<f&&m<s.length;d++,m++){let g=s[m];if(g.indent!==1)break;let h=xe(g.content,n),b={};u.forEach((x,y)=>{b[x]=Re(h[y]??"null");}),p.push(b);}return p}let a=i.content.match(/^\[(\d+)\]:\s*(.*)$/);if(a){let u=a[2];return Number(a[1])===0||u.trim()===""?[]:xe(u,n).map(Re)}}let[c]=_n(s,0,0,n);return c}function On(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}function Eo(t,e){return On(t,e)/e.length}function _n(t,e,n,r){let o={},s=e;for(;s<t.length;){let i=t[s];if(i.indent<n)break;if(i.indent>n){s++;continue}let c=To(i.content,r);if(!c){s++;continue}let{key:l,kind:a}=c;if(a.type==="scalar")o[l]=a.value,s++;else if(a.type==="inlineArray")o[l]=a.values,s++;else if(a.type==="emptyArray")o[l]=[],s++;else if(a.type==="table"){let u=[];s++;for(let f=0;f<a.count&&s<t.length;f++,s++){let p=t[s];if(p.indent!==n+1)break;let d=xe(p.content,r),m={};a.columns.forEach((g,h)=>{m[g]=Re(d[h]??"null");}),u.push(m);}o[l]=u;}else {let[u,f]=_n(t,s+1,n+1,r);o[l]=u,s=f;}}return [o,s]}function To(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:Ue(n[1]),kind:{type:"table",count:Number(n[2]),columns:xe(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){let s=Number(r[2]),i=r[3];return s===0||i.trim()===""?{key:Ue(r[1]),kind:{type:"emptyArray"}}:{key:Ue(r[1]),kind:{type:"inlineArray",values:xe(i,e).map(Re)}}}let o=t.match(/^([^:]+):\s*(.*)$/);if(o){let s=Ue(o[1]),i=o[2];return i===""?{key:s,kind:{type:"object"}}:{key:s,kind:{type:"scalar",value:Re(i)}}}return null}function xe(t,e){let n=[],r="",o=false;for(let s=0;s<t.length;s++){let i=t[s];o?i==='"'?t[s+1]==='"'?(r+='"',s++):o=false:r+=i:i==='"'?o=true:i===e?(n.push(r),r=""):r+=i;}return n.push(r),n.map(s=>s.trim())}function Re(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,'"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function Ue(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,'"'):e}function Ro(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return It(null,t,0,o,n,r),o.join(`
7
+ `)}function It(t,e,n,r,o,s){let i=s.repeat(n),c=t===null?"":`${Oo(t)}`;if(Array.isArray(e)){Io(c,e,n,r,o,s);return}if(Rt(e)){t!==null&&r.push(`${i}${c}:`);let l=t===null?n:n+1;for(let[a,u]of Object.entries(e))It(a,u,l,r,o,s);return}r.push(`${i}${c}: ${He(e,o)}`);}function Io(t,e,n,r,o,s){let i=s.repeat(n),c=t===""?"":t;if(e.length===0){r.push(`${i}${c}[0]:`);return}if(e.every(Tt)){let f=e.map(p=>He(p,o)).join(o);r.push(`${i}${c}[${e.length}]: ${f}`);return}let l=Ke(e);if(l){r.push(`${i}${c}[${e.length}]{${l.join(o)}}:`);let f=s.repeat(n+1);for(let p of e){let d=l.map(m=>He(p[m],o)).join(o);r.push(`${f}${d}`);}return}r.push(`${i}${c}[${e.length}]:`);let a=n+1,u=s.repeat(a);for(let f of e)if(Tt(f))r.push(`${u}- ${He(f,o)}`);else {let p=[];It(null,f,0,p,o,s);let[d,...m]=p;r.push(`${u}- ${d??""}`);for(let g of m)r.push(`${u}${s}${g}`);}}function Ke(t){if(t.length===0)return null;let e=t[0];if(!Rt(e))return null;let n=Object.keys(e);if(n.length===0)return null;let r=n.slice().sort().join("\0");for(let o of t){if(!Rt(o))return null;let s=Object.keys(o);if(s.slice().sort().join("\0")!==r)return null;for(let i of s)if(!Tt(o[i]))return null}return n}function Oo(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:An(t)}function He(t,e){if(t==null)return "null";if(typeof t=="number")return Number.isFinite(t)?String(t):"null";if(typeof t=="boolean")return t?"true":"false";let n=String(t);return n===""||n.includes(e)||n.includes(`
8
+ `)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?An(n):n}function An(t){return `"${t.replace(/"/g,'""')}"`}function Tt(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function Rt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var _o="Data is TOON: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; each following indented line is one row of delimiter-separated values. `key[N]: a,b` is an inline list. Quoted values use CSV-style escaping.";function Ao(t={}){return {format:"toon",supports(){return true},encode(e){return Ro(e,t)},instruction(){return _o},decode(e){return In(e,t)}}}var Cn=Ao();var Bn={format:"csv",supports(t){return Array.isArray(t)&&Ke(t)!==null},encode(t){let e=t,n=Ke(e),r=n.map(Ln).join(","),o=e.map(s=>n.map(i=>Ln(s[i])).join(","));return [r,...o].join(`
9
+ `)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function Ln(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}var qe=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[Rn,Cn,Bn],this.minSavingsTokens=e.minimumSavingsTokens??64,this.minSavingsRatio=e.minimumSavingsRatio??.08,this.qualityPenalty=e.qualityPenalty??(()=>0);}choose(e,n){let r={model:n.model,tokenizer:n.tokenizer},o=[];for(let a of this.serializers){if(!a.supports(e))continue;let u=a.encode(e);if(a.format!=="json-compact"&&!Co(a,u,e))continue;let f=a.instruction(e),p=this.tokenizer.count(u,r),d=f?this.tokenizer.count(f,r):0,m=this.qualityPenalty(n.model??"",a.format);o.push({format:a.format,encoded:u,instruction:f,payloadTokens:p,instructionTokens:d,penalty:m,total:p+d+m});}let s=o.find(a=>a.format==="json-compact"),i={};for(let a of o)i[a.format]=a.total;if(!s){let a=o[0];return a?Mn(a,i,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:i,instructionOverheadTokens:0,reason:"no serializer supported payload; defaulted to JSON"}}let c=s,l="json baseline (no challenger cleared thresholds)";for(let a of o){if(a.format==="json-compact")continue;let u=s.total-a.total,f=s.total===0?0:u/s.total;u>=this.minSavingsTokens&&f>=this.minSavingsRatio&&a.total<c.total&&(c=a,l=`${a.format} saved ${u} tokens (${(f*100).toFixed(1)}%) vs json`);}return Mn(c,i,l)}};function Co(t,e,n){if(!t.decode)return false;try{return Ot(t.decode(e),n)}catch{return false}}function Ot(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.isArray(t),r=Array.isArray(e);if(n||r){if(!n||!r||t.length!==e.length)return false;for(let i=0;i<t.length;i++)if(!Ot(t[i],e[i]))return false;return true}let o=Object.keys(t),s=Object.keys(e);if(o.length!==s.length)return false;for(let i of o)if(!Object.prototype.hasOwnProperty.call(e,i)||!Ot(t[i],e[i]))return false;return true}function Mn(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function Ie(t,e,n="$"){let r=[];return _t(t,e,n,r),{valid:r.length===0,errors:r}}function Lo(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function _t(t,e,n,r){switch(e.enum&&!e.enum.some(s=>Po(s,t))&&r.push({path:n,message:"value not in enum"}),e.type??Lo(t)){case "object":Bo(t,e,n,r);break;case "array":Mo(t,e,n,r);break;case "string":Do(t,e,n,r);break;case "number":case "integer":jo(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function Bo(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,message:"expected object"});return}let o=t;for(let s of e.required??[])s in o||r.push({path:`${n}.${s}`,message:"missing required property"});if(e.additionalProperties===false&&e.properties){let s=new Set(Object.keys(e.properties));for(let i of Object.keys(o))s.has(i)||r.push({path:`${n}.${i}`,message:"additional property not allowed"});}if(e.properties)for(let[s,i]of Object.entries(e.properties))s in o&&_t(o[s],i,`${n}.${s}`,r);}function Mo(t,e,n,r){if(!Array.isArray(t)){r.push({path:n,message:"expected array"});return}e.maxItems!=null&&t.length>e.maxItems&&r.push({path:n,message:`array exceeds maxItems ${e.maxItems}`}),e.minItems!=null&&t.length<e.minItems&&r.push({path:n,message:`array below minItems ${e.minItems}`}),e.items&&t.forEach((o,s)=>_t(o,e.items,`${n}[${s}]`,r));}function Do(t,e,n,r){if(typeof t!="string"){r.push({path:n,message:"expected string"});return}if(e.maxLength!=null&&t.length>e.maxLength&&r.push({path:n,message:`string exceeds maxLength ${e.maxLength}`}),e.minLength!=null&&t.length<e.minLength&&r.push({path:n,message:`string below minLength ${e.minLength}`}),e.pattern){let o=null;try{o=new RegExp(e.pattern);}catch{r.push({path:n,message:`schema pattern is not a valid regular expression: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function jo(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}e.type==="integer"&&!Number.isInteger(t)&&r.push({path:n,message:"expected integer"}),e.maximum!=null&&t>e.maximum&&r.push({path:n,message:`number exceeds maximum ${e.maximum}`}),e.minimum!=null&&t<e.minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function Po(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var Ge=class{contracts=new Map;register(e){return this.contracts.set(e.contractId,e),this}resolve(e){return this.contracts.get(e)}has(e){return this.contracts.has(e)}static lint(e,n="$"){let r=[];return At(e,n,r),r}};function At(t,e,n){if(t.type==="object"){t.additionalProperties!==false&&n.push(`${e}: object should set additionalProperties:false`);for(let[r,o]of Object.entries(t.properties??{}))At(o,`${e}.${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&At(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: string should set maxLength or use an enum`);}function Dn(t,e,n){for(let r of n)if(r.supports(t,e))return {backend:r.id,reason:`first supporting backend: ${r.id}`};return {backend:"none",reason:"no constrained-decoding backend available; will validate + repair"}}function aa(t=()=>true){return {id:"provider-native",supports:t}}function pa(t){let e=t.minimumContextTokens??2e3,n=t.minimumNetTokens??200;if(t.contextTokens<e)return {compress:false,reason:`context ${t.contextTokens} < ${e} min`};let r=t.projectedEliminable-t.compressorCostTokens;return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function ma(t){return {async compress(e){let n=e.protectedSpans??[],r=e.text,o=[];n.forEach((l,a)=>{let u=`\0PROTECT_${a}\0`;o.push({token:u,span:l}),r=r.split(l.text).join(u);});let s=await t.compress({text:r,...e.targetRatio!=null?{targetRatio:e.targetRatio}:{}}),i=s.compressed,c=true;for(let{token:l,span:a}of o){if(!i.includes(l)){c=false;break}i=i.split(l).join(a.text);}return c?{...s,compressed:i,protectedSpans:n.length,fidelityPassed:true}:{compressed:e.text,originalTokens:s.originalTokens,compressedTokens:s.originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var ha={async compress(t){return {compressed:t.text,originalTokens:0,compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};var jn=new WeakSet;function Pn(t){jn.add(t);}var Ct=class{id="mock";options;constructor(e={}){this.options=e,Pn(this);}async generate(e){let n=e.messages.map(c=>c.content).join(`
10
+ `),r=he.count(n);if(e.tools&&e.tools.length>0){let c=JSON.stringify(e.tools.map(l=>({name:l.id,description:l.description,parameters:l.parameters??{}})));r+=he.count(c);}let o,s=false;if(e.schema){let c=this.options.data??Ze(e.schema);o=JSON.stringify(c),s=true;}else o=this.options.answer??`mock-response(${e.model})`;let i=Math.min(e.maxOutputTokens??Number.MAX_SAFE_INTEGER,he.count(o));return {text:o,usage:{inputTokens:r,outputTokens:i,...this.options.cachedInputTokens!=null?{cachedInputTokens:this.options.cachedInputTokens}:{}},structuredNatively:s}}};function Ze(t){if(t.enum&&t.enum.length>0)return t.enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?Ze(r):null;}for(let[n,r]of Object.entries(t.properties??{}))n in e||(e[n]=Ze(r));return e}case "array":return t.items?[Ze(t.items)]:[];case "string":return "mock";case "number":case "integer":return t.minimum??0;case "boolean":return true;case "null":return null;default:return null}}function Sa(t){return new Ct(t)}var zn=new Set;function J(t,e){zn.has(t)||(zn.add(t),console.warn(e));}function Oe(t){if(t==null||typeof t!="object")return true;let e=t,n=e.properties;if(n&&typeof n=="object"){if(e.additionalProperties!==false)return false;let o=Object.keys(n),s=Array.isArray(e.required)?e.required.map(String):[];if(o.some(i=>!s.includes(i)))return false;for(let i of Object.values(n))if(!Oe(i))return false}if(e.items!==void 0&&!Oe(e.items))return false;for(let o of ["anyOf","oneOf","allOf"]){let s=e[o];if(Array.isArray(s)&&s.some(i=>!Oe(i)))return false}let r=e.$defs??e.definitions;return !(r&&typeof r=="object"&&Object.values(r).some(o=>!Oe(o)))}var Nn=class{id;opts;fetchImpl;constructor(e){this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch;}async generate(e){let r={model:this.opts.stripProviderPrefix?e.model.replace(/^[^/]+\//,""):e.model,messages:e.messages.map(g=>({role:g.role,content:g.content}))};if(e.maxOutputTokens!=null&&(r.max_tokens=e.maxOutputTokens),e.temperature!=null&&(r.temperature=e.temperature),e.seed!=null&&(r.seed=e.seed),e.schema){let g=Oe(e.schema);g||J("strict-incompatible","[bvsala] El contrato de respuesta no cumple el modo `strict` de OpenAI (en strict, `required` debe listar TODAS las claves de `properties`, y todo objeto necesita `additionalProperties: false`). Se env\xEDa el esquema con `strict: false`: el modelo sigue guiado y el layer sigue validando, pero la garant\xEDa la da el layer, no el proveedor. Para recuperarla, haz obligatorias todas las claves del contrato."),r.response_format={type:"json_schema",json_schema:{name:"bvsala_contract",schema:e.schema,strict:g}};}e.tools&&e.tools.length>0&&(r.tools=e.tools.map(g=>({type:"function",function:{name:g.id,...g.description?{description:g.description}:{},parameters:g.parameters??{type:"object",properties:{}}}})));let o=await this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.headers},body:JSON.stringify(r)});if(!o.ok){let g=await Fo(o);throw new Error(`provider ${o.status}: ${g}`)}let s=await o.json(),i=s.choices?.[0]?.message,c=i?.content??"",l=(i?.tool_calls??[]).map(g=>({...g.id?{id:g.id}:{},name:g.function?.name??"",arguments:g.function?.arguments??""})).filter(g=>g.name!==""),a=s.usage??{},u=a.prompt_tokens??0,f=a.completion_tokens??0,p=typeof a.prompt_tokens!="number",d=typeof a.completion_tokens!="number";if(this.opts.requireUsage&&(p||d))throw new Error(`provider returned incomplete usage (prompt=${a.prompt_tokens??"absent"}, completion=${a.completion_tokens??"absent"}); cannot measure cost. For gateways/streaming, ensure usage reporting is enabled.`);let m=s.choices?.[0]?.finish_reason;return {text:c,...l.length>0?{toolCalls:l}:{},...m?{finishReason:m}:{},usage:{inputTokens:u,outputTokens:f,...a.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:a.prompt_tokens_details.cached_tokens}:{}},structuredNatively:e.schema!=null,raw:s}}};async function Fo(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}var _e=class{events=[];start;now;constructor(e=()=>Date.now()){this.now=e,this.start=e();}record(e,n,r){this.events.push({stage:e,outcome:n,...r?{detail:r}:{},atMs:this.now()-this.start});}elapsed(){return this.now()-this.start}all(){return this.events}};var ue=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function Lt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Ye(t,e=""){if(typeof t!="number"){let n=e&&`"${e}" `;throw new TypeError(`${n}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let n=e&&`"${e}" `;throw new RangeError(`${n}expected integer >= 0, got ${t}`)}}function K(t,e,n=""){let r=Lt(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){let i=n&&`"${n}" `,c=s?` of length ${e}`:"",l=r?`length=${o}`:`type=${typeof t}`,a=i+"expected Uint8Array"+c+", got "+l;throw r?new RangeError(a):new TypeError(a)}return t}function Bt(t,e=true){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Vn(t,e){K(t,void 0,"digestInto() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function Ae(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function We(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Un=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",zo=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Je(t){if(K(t),Un)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=zo[t[n]];return e}var X={_0:48,_9:57,A:65,F:70,a:97,f:102};function $n(t){if(t>=X._0&&t<=X._9)return t-X._0;if(t>=X.A&&t<=X.F)return t-(X.A-10);if(t>=X.a&&t<=X.f)return t-(X.a-10)}function Ce(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Un)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){let i=$n(t.charCodeAt(s)),c=$n(t.charCodeAt(s+1));if(i===void 0||c===void 0){let l=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+l+'" at index '+s)}r[o]=i*16+c;}return r}function Mt(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];K(o),e+=o.length;}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let s=t[r];n.set(s,o),o+=s.length;}return n}function Hn(t,e={}){let n=(o,s)=>t(s).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function Kn(t=32){Ye(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var qn=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var Xe=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(e,n,r,o){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=We(this.buffer);}update(e){Bt(this),K(e);let{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let c=Math.min(o-this.pos,s-i);if(c===o){let l=We(e);for(;o<=s-i;i+=o)this.process(l,i);continue}r.set(e.subarray(i,i+c),this.pos),this.pos+=c,i+=c,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){Bt(this),Vn(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;n[i++]=128,Ae(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let f=i;f<o;f++)n[f]=0;r.setBigUint64(o-8,BigInt(this.length*8),s),this.process(r,0);let c=We(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let a=l/4,u=this.get();if(a>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<a;f++)c.setUint32(4*f,u[f],s);}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:c}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=c,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};var $=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Qe=BigInt(4294967295),Gn=BigInt(32);function No(t,e=false){return e?{h:Number(t&Qe),l:Number(t>>Gn&Qe)}:{h:Number(t>>Gn&Qe)|0,l:Number(t&Qe)|0}}function Zn(t,e=false){let n=t.length,r=new Uint32Array(n),o=new Uint32Array(n);for(let s=0;s<n;s++){let{h:i,l:c}=No(t[s],e);[r[s],o[s]]=[i,c];}return [r,o]}var Dt=(t,e,n)=>t>>>n,jt=(t,e,n)=>t<<32-n|e>>>n,fe=(t,e,n)=>t>>>n|e<<32-n,de=(t,e,n)=>t<<32-n|e>>>n,Le=(t,e,n)=>t<<64-n|e>>>n-32,Be=(t,e,n)=>t>>>n-32|e<<64-n;function Z(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var Yn=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Wn=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Jn=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Xn=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,Qn=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),er=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0;var tr=Zn(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Vo=tr[0],Uo=tr[1],oe=new Uint32Array(80),se=new Uint32Array(80),Pt=class extends Xe{constructor(e){super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:c,Dl:l,Eh:a,El:u,Fh:f,Fl:p,Gh:d,Gl:m,Hh:g,Hl:h}=this;return [e,n,r,o,s,i,c,l,a,u,f,p,d,m,g,h]}set(e,n,r,o,s,i,c,l,a,u,f,p,d,m,g,h){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=c|0,this.Dl=l|0,this.Eh=a|0,this.El=u|0,this.Fh=f|0,this.Fl=p|0,this.Gh=d|0,this.Gl=m|0,this.Hh=g|0,this.Hl=h|0;}process(e,n){for(let y=0;y<16;y++,n+=4)oe[y]=e.getUint32(n),se[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){let R=oe[y-15]|0,E=se[y-15]|0,_=fe(R,E,1)^fe(R,E,8)^Dt(R,E,7),I=de(R,E,1)^de(R,E,8)^jt(R,E,7),w=oe[y-2]|0,A=se[y-2]|0,L=fe(w,A,19)^Le(w,A,61)^Dt(w,A,6),M=de(w,A,19)^Be(w,A,61)^jt(w,A,6),v=Jn(I,M,se[y-7],se[y-16]),S=Xn(v,_,L,oe[y-7],oe[y-16]);oe[y]=S|0,se[y]=v|0;}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:c,Cl:l,Dh:a,Dl:u,Eh:f,El:p,Fh:d,Fl:m,Gh:g,Gl:h,Hh:b,Hl:x}=this;for(let y=0;y<80;y++){let R=fe(f,p,14)^fe(f,p,18)^Le(f,p,41),E=de(f,p,14)^de(f,p,18)^Be(f,p,41),_=f&d^~f&g,I=p&m^~p&h,w=Qn(x,E,I,Uo[y],se[y]),A=er(w,b,R,_,Vo[y],oe[y]),L=w|0,M=fe(r,o,28)^Le(r,o,34)^Le(r,o,39),v=de(r,o,28)^Be(r,o,34)^Be(r,o,39),S=r&s^r&c^s&c,O=o&i^o&l^i&l;b=g|0,x=h|0,g=d|0,h=m|0,d=f|0,m=p|0,{h:f,l:p}=Z(a|0,u|0,A|0,L|0),a=c|0,u=l|0,c=s|0,l=i|0,s=r|0,i=o|0;let C=Yn(L,v,O);r=Wn(C,A,M,S),o=C|0;}(({h:r,l:o}=Z(this.Ah|0,this.Al|0,r|0,o|0))),{h:s,l:i}=Z(this.Bh|0,this.Bl|0,s|0,i|0),{h:c,l}=Z(this.Ch|0,this.Cl|0,c|0,l|0),{h:a,l:u}=Z(this.Dh|0,this.Dl|0,a|0,u|0),{h:f,l:p}=Z(this.Eh|0,this.El|0,f|0,p|0),{h:d,l:m}=Z(this.Fh|0,this.Fl|0,d|0,m|0),{h:g,l:h}=Z(this.Gh|0,this.Gl|0,g|0,h|0),{h:b,l:x}=Z(this.Hh|0,this.Hl|0,b|0,x|0),this.set(r,o,s,i,c,l,a,u,f,p,d,m,g,h,b,x);}roundClean(){Ae(oe,se);}destroy(){this.destroyed=true,Ae(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},Ft=class extends Pt{Ah=$[0]|0;Al=$[1]|0;Bh=$[2]|0;Bl=$[3]|0;Ch=$[4]|0;Cl=$[5]|0;Dh=$[6]|0;Dl=$[7]|0;Eh=$[8]|0;El=$[9]|0;Fh=$[10]|0;Fl=$[11]|0;Gh=$[12]|0;Gl=$[13]|0;Hh=$[14]|0;Hl=$[15]|0;constructor(){super(64);}};var et=Hn(()=>new Ft,qn(3));var j=(t,e,n)=>K(t,e,n),Nt=Ye,$t=Je,Y=(...t)=>Mt(...t),nr=t=>Ce(t),rt=Lt,rr=t=>Kn(t),nt=BigInt(0),zt=BigInt(1);function ye(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"expected boolean, got type="+typeof t)}return t}function Ho(t){if(typeof t=="bigint"){if(!tt(t))throw new RangeError("positive bigint expected, got "+t)}else Nt(t);return t}function Q(t,e=""){if(typeof t!="number"){let n=e&&`"${e}" `;throw new TypeError(n+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let n=e&&`"${e}" `;throw new RangeError(n+"expected safe integer, got "+t)}}function or(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?nt:BigInt("0x"+t)}function Vt(t){return or(Je(t))}function ee(t){return or(Je(Me(K(t)).reverse()))}function Ut(t,e){if(Ye(e),e===0)throw new RangeError("zero length");t=Ho(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return Ce(n.padStart(e*2,"0"))}function sr(t,e){return Ut(t,e).reverse()}function ir(t,e){if(t=j(t),e=j(e),t.length!==e.length)return false;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function Me(t){return Uint8Array.from(j(t))}var tt=t=>typeof t=="bigint"&&nt<=t;function Ko(t,e,n){return tt(t)&&tt(e)&&tt(n)&&e<=t&&t<n}function Ht(t,e,n,r){if(!Ko(e,n,r))throw new RangeError("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Kt(t){if(t<nt)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>nt;t>>=zt,e+=1);return e}var ar=t=>(zt<<BigInt(t))-zt;function pe(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function r(s,i,c){if(!c&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let l=t[s];if(c&&l===void 0)return;let a=typeof l;if(a!==i||l===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${a}`)}let o=(s,i)=>Object.entries(s).forEach(([c,l])=>r(c,l,i));o(e,false),o(n,true);}var qt=()=>{throw new Error("not implemented")};var V=BigInt(0),P=BigInt(1),me=BigInt(2),fr=BigInt(3),dr=BigInt(4),pr=BigInt(5),qo=BigInt(7),mr=BigInt(8),Go=BigInt(9),hr=BigInt(16);function D(t,e){if(e<=V)throw new Error("mod: expected positive modulus, got "+e);let n=t%e;return n>=V?n:e+n}function q(t,e,n){if(e<V)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >V;)r*=r,r%=n;return r}function cr(t,e){if(t===V)throw new Error("invert: expected non-zero number");if(e<=V)throw new Error("invert: expected positive modulus, got "+e);let n=D(t,e),r=e,o=V,i=P;for(;n!==V;){let a=r/n,u=r-n*a,f=o-i*a;r=n,n=u,o=i,i=f;}if(r!==P)throw new Error("invert: does not exist");return D(o,e)}function Gt(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function gr(t,e){let n=t,r=(n.ORDER+P)/dr,o=n.pow(e,r);return Gt(n,o,e),o}function Zo(t,e){let n=t,r=(n.ORDER-pr)/mr,o=n.mul(e,me),s=n.pow(o,r),i=n.mul(e,s),c=n.mul(n.mul(i,me),s),l=n.mul(i,n.sub(c,n.ONE));return Gt(n,l,e),l}function Yo(t){let e=at(t),n=br(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+qo)/hr;return((c,l)=>{let a=c,u=a.pow(l,i),f=a.mul(u,r),p=a.mul(u,o),d=a.mul(u,s),m=a.eql(a.sqr(f),l),g=a.eql(a.sqr(p),l);u=a.cmov(u,f,m),f=a.cmov(d,p,g);let h=a.eql(a.sqr(f),l),b=a.cmov(u,f,h);return Gt(a,b,l),b})}function br(t){if(t<fr)throw new Error("sqrt is not defined for small field");let e=t-P,n=0;for(;e%me===V;)e/=me,n++;let r=me,o=at(t);for(;lr(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return gr;let s=o.pow(r,e),i=(e+P)/me;return function(l,a){let u=l;if(u.is0(a))return a;if(lr(u,a)!==1)throw new Error("Cannot find square root");let f=n,p=u.mul(u.ONE,s),d=u.pow(a,e),m=u.pow(a,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))return u.ZERO;let g=1,h=u.sqr(d);for(;!u.eql(h,u.ONE);)if(g++,h=u.sqr(h),g===f)throw new Error("Cannot find square root");let b=P<<BigInt(f-g-1),x=u.pow(p,b);f=g,p=u.sqr(x),d=u.mul(d,p),m=u.mul(m,x);}return m}}function Wo(t){return t%dr===fr?gr:t%mr===pr?Zo:t%hr===Go?Yo(t):br(t)}var te=(t,e)=>(D(t,e)&P)===P,Jo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function xr(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=Jo.reduce((r,o)=>(r[o]="function",r),e);if(pe(t,n),Q(t.BYTES,"BYTES"),Q(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=P)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Xo(t,e,n){let r=t;if(n<V)throw new Error("invalid exponent, negatives unsupported");if(n===V)return r.ONE;if(n===P)return e;let o=r.ONE,s=e;for(;n>V;)n&P&&(o=r.mul(o,s)),s=r.sqr(s),n>>=P;return o}function it(t,e,n=false){let r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),s=e.reduce((c,l,a)=>r.is0(l)?c:(o[a]=c,r.mul(c,l)),r.ONE),i=r.inv(s);return e.reduceRight((c,l,a)=>r.is0(l)?c:(o[a]=r.mul(c,o[a]),r.mul(c,l)),i),o}function lr(t,e){let n=t,r=(n.ORDER-P)/me,o=n.pow(e,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),c=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!c)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Qo(t,e){if(e!==void 0&&Nt(e),t<=V)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let n=Kt(t);if(e!==void 0&&e<n)throw new Error(`invalid n length: expected bit length (${n}) >= n.length (${e})`);let r=e!==void 0?e:n,o=Math.ceil(r/8);return {nBitLength:r,nByteLength:o}}var ur=new WeakMap,st=class{ORDER;BITS;BYTES;isLE;ZERO=V;ONE=P;_lengths;_mod;constructor(e,n={}){if(e<=P)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:true}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:s}=Qo(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this);}create(e){return D(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return V<=e&&e<this.ORDER}is0(e){return e===V}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&P)===P}neg(e){return D(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return D(e*e,this.ORDER)}add(e,n){return D(e+n,this.ORDER)}sub(e,n){return D(e-n,this.ORDER)}mul(e,n){return D(e*n,this.ORDER)}pow(e,n){return Xo(this,e,n)}div(e,n){return D(e*cr(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return cr(e,this.ORDER)}sqrt(e){let n=ur.get(this);return n||ur.set(this,n=Wo(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?sr(e,this.BYTES):Ut(e,this.BYTES)}fromBytes(e,n=false){j(e);let{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:c}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let a=new Uint8Array(o);a.set(e,s?0:a.length-e.length),e=a;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let l=s?ee(e):Vt(e);if(c&&(l=D(l,i)),!n&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return it(this,e)}cmov(e,n,r){return ye(r,"condition"),r?n:e}};Object.freeze(st.prototype);function at(t,e={}){return new st(t,e)}var ct=BigInt(0),Jt=BigInt(1);function yr(t,e){let n=e.negate();return t?n:e}function ut(t,e){let n=it(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function kr(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Zt(t,e){kr(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=ar(t),i=BigInt(t);return {windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function vr(t,e,n){let{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n,c=Number(t&o),l=t>>i;c>r&&(c-=s,l+=Jt);let a=e*r,u=a+Math.abs(c)-1,f=c===0,p=c<0,d=e%2!==0;return {nextN:l,offset:u,isZero:f,isNeg:p,isNegF:d,offsetF:a}}var Yt=new WeakMap,Er=new WeakMap;function Wt(t){return Er.get(t)||1}function wr(t){if(t!==ct)throw new Error("invalid wNAF")}var lt=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>ct;)n&Jt&&(r=r.add(o)),o=o.double(),n>>=Jt;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Zt(n,this.bits),s=[],i=e,c=i;for(let l=0;l<r;l++){c=i,s.push(c);for(let a=1;a<o;a++)c=c.add(i),s.push(c);i=c.double();}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Zt(e,this.bits);for(let c=0;c<i.windows;c++){let{nextN:l,offset:a,isZero:u,isNeg:f,isNegF:p,offsetF:d}=vr(r,c,i);r=l,u?s=s.add(yr(p,n[d])):o=o.add(yr(f,n[a]));}return wr(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.ZERO){let s=Zt(e,this.bits);for(let i=0;i<s.windows&&r!==ct;i++){let{nextN:c,offset:l,isZero:a,isNeg:u}=vr(r,i,s);if(r=c,!a){let f=n[l];o=o.add(u?f.negate():f);}}return wr(r),o}getPrecomputes(e,n,r){let o=Yt.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Yt.set(n,o))),o}cached(e,n,r){let o=Wt(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let s=Wt(e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){kr(n,this.bits),Er.set(e,n),Yt.delete(e);}hasCache(e){return Wt(e)!==1}};function Sr(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return xr(e),e}else return at(t,{isLE:n})}function Tr(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let l of ["p","n","h"]){let a=e[l];if(!(typeof a=="bigint"&&a>ct))throw new Error(`CURVE.${l} must be positive bigint`)}let o=Sr(e.p,n.Fp,r),s=Sr(e.n,n.Fn,r),c=["Gx","Gy","a","d"];for(let l of c)if(!o.isValid(e[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Rr(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var ie=BigInt(0),F=BigInt(1),Xt=BigInt(2),es=BigInt(8);function ts(t,e,n,r){let o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),c=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,c)}function Ir(t,e={}){let n=e,r=Tr("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r,i=r.CURVE,{h:c}=i;pe(n,{},{uvRatio:"function"});let l=Xt<<BigInt(s.BYTES*8)-F,a=g=>o.create(g),u=n.uvRatio===void 0?(g,h)=>{try{return {isValid:!0,value:o.sqrt(o.div(g,h))}}catch{return {isValid:false,value:ie}}}:n.uvRatio;if(!ts(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(g,h,b=false){let x=b?F:ie;return Ht("coordinate "+g,h,x,l),h}function p(g){if(!(g instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,F,a(i.Gx*i.Gy));static ZERO=new d(ie,F,F,ie);static Fp=o;static Fn=s;X;Y;Z;T;constructor(h,b,x,y){this.X=f("x",h),this.Y=f("y",b),this.Z=f("z",x,true),this.T=f("t",y),Object.freeze(this);}static CURVE(){return i}static fromAffine(h){if(h instanceof d)throw new Error("extended point not allowed");let{x:b,y:x}=h||{};return f("x",b),f("y",x),new d(b,x,F,a(b*x))}static fromBytes(h,b=false){let x=o.BYTES,{a:y,d:R}=i;h=Me(j(h,x,"point")),ye(b,"zip215");let E=Me(h),_=h[x-1];E[x-1]=_&-129;let I=ee(E),w=b?l:o.ORDER;Ht("point.y",I,ie,w);let A=a(I*I),L=a(A-F),M=a(R*A-y),{isValid:v,value:S}=u(L,M);if(!v)throw new Error("bad point: invalid y coordinate");let O=(S&F)===F,C=(_&128)!==0;if(!b&&S===ie&&C)throw new Error("bad point: x=0 and x_0=1");return C!==O&&(S=a(-S)),d.fromAffine({x:S,y:I})}static fromHex(h,b=false){return d.fromBytes(nr(h),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,b=true){return m.createCache(this,h),b||this.multiply(Xt),this}assertValidity(){let h=this,{a:b,d:x}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:y,Y:R,Z:E,T:_}=h,I=a(y*y),w=a(R*R),A=a(E*E),L=a(A*A),M=a(I*b),v=a(A*a(M+w)),S=a(L+a(x*a(I*w)));if(v!==S)throw new Error("bad point: equation left != right (1)");let O=a(y*R),C=a(E*_);if(O!==C)throw new Error("bad point: equation left != right (2)")}equals(h){p(h);let{X:b,Y:x,Z:y}=this,{X:R,Y:E,Z:_}=h,I=a(b*_),w=a(R*y),A=a(x*_),L=a(E*y);return I===w&&A===L}is0(){return this.equals(d.ZERO)}negate(){return new d(a(-this.X),this.Y,this.Z,a(-this.T))}double(){let{a:h}=i,{X:b,Y:x,Z:y}=this,R=a(b*b),E=a(x*x),_=a(Xt*a(y*y)),I=a(h*R),w=b+x,A=a(a(w*w)-R-E),L=I+E,M=L-_,v=I-E,S=a(A*M),O=a(L*v),C=a(A*v),k=a(M*L);return new d(S,O,k,C)}add(h){p(h);let{a:b,d:x}=i,{X:y,Y:R,Z:E,T:_}=this,{X:I,Y:w,Z:A,T:L}=h,M=a(y*I),v=a(R*w),S=a(_*x*L),O=a(E*A),C=a((y+R)*(I+w)-M-v),k=O-S,T=O+S,B=a(v-b*M),U=a(C*k),z=a(T*B),H=a(C*B),N=a(k*T);return new d(U,z,N,H)}subtract(h){return p(h),this.add(h.negate())}multiply(h){if(!s.isValidNot0(h))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:x}=m.cached(this,h,y=>ut(d,y));return ut(d,[b,x])[0]}multiplyUnsafe(h){if(!s.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===ie?d.ZERO:this.is0()||h===F?this:m.unsafe(this,h,b=>ut(d,b))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return m.unsafe(this,i.n).is0()}toAffine(h){let b=this,x=h,{X:y,Y:R,Z:E}=b,_=b.is0();x==null&&(x=_?es:o.inv(E));let I=a(y*x),w=a(R*x),A=o.mul(E,x);if(_)return {x:ie,y:F};if(A!==F)throw new Error("invZ was invalid");return {x:I,y:w}}clearCofactor(){return c===F?this:this.multiplyUnsafe(c)}toBytes(){let{x:h,y:b}=this.toAffine(),x=o.toBytes(b);return x[x.length-1]|=h&F?128:0,x}toHex(){return $t(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=new lt(d,s.BITS);return s.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var ft=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e;}static fromBytes(e){qt();}static fromHex(e){qt();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){return this.ep.toAffine(e)}toHex(){return $t(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return true}isSmallOrder(){return false}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function Or(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');let r=e,o=n;pe(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:c,Fn:l}=t,a=r.outputLen,u=2*c.BYTES;if(a!==void 0&&(Q(a,"hash.outputLen"),a!==u))throw new Error(`hash.outputLen must be ${u}, got ${a}`);let f=o.randomBytes===void 0?rr:o.randomBytes,p=o.adjustScalarBytes===void 0?v=>v:o.adjustScalarBytes,d=o.domain===void 0?(v,S,O)=>{if(ye(O,"phflag"),S.length||O)throw new Error("Contexts/pre-hash are not supported");return v}:o.domain;function m(v){return l.create(ee(v))}function g(v){let S=I.secretKey;j(v,I.secretKey,"secretKey");let O=j(r(v),2*S,"hashedSecretKey"),C=p(O.slice(0,S)),k=O.slice(S,2*S),T=m(C);return {head:C,prefix:k,scalar:T}}function h(v){let{head:S,prefix:O,scalar:C}=g(v),k=i.multiply(C),T=k.toBytes();return {head:S,prefix:O,scalar:C,point:k,pointBytes:T}}function b(v){return h(v).pointBytes}function x(v=Uint8Array.of(),...S){let O=Y(...S);return m(r(d(O,j(v,void 0,"context"),!!s)))}function y(v,S,O={}){v=j(v,void 0,"message"),s&&(v=s(v));let{prefix:C,scalar:k,pointBytes:T}=h(S),B=x(O.context,C,v),U=i.multiply(B).toBytes(),z=x(O.context,U,T,v),H=l.create(B+z*k);if(!l.isValid(H))throw new Error("sign failed: invalid s");let N=Y(U,l.toBytes(H));return j(N,I.signature,"result")}let R={zip215:o.zip215};function E(v,S,O,C=R){let{context:k}=C,T=C.zip215===void 0?!!R.zip215:C.zip215,B=I.signature;v=j(v,B,"signature"),S=j(S,void 0,"message"),O=j(O,I.publicKey,"publicKey"),T!==void 0&&ye(T,"zip215"),s&&(S=s(S));let U=B/2,z=v.subarray(0,U),H=ee(v.subarray(U,B)),N,re,Ee;try{N=t.fromBytes(O,T),re=t.fromBytes(z,T),Ee=i.multiplyUnsafe(H);}catch{return false}if(!T&&N.isSmallOrder())return false;let qr=x(k,z,O,S);return re.add(N.multiplyUnsafe(qr)).subtract(Ee).clearCofactor().is0()}let _=c.BYTES,I={secretKey:_,publicKey:_,signature:2*_,seed:_};function w(v){return v=v===void 0?f(I.seed):v,j(v,I.seed,"seed")}function A(v){return rt(v)&&v.length===I.secretKey}function L(v,S){try{return !!t.fromBytes(v,S===void 0?R.zip215:S)}catch{return false}}let M={getExtendedPublicKey:h,randomSecretKey:w,isValidSecretKey:A,isValidPublicKey:L,toMontgomery(v){let{y:S}=t.fromBytes(v),O=I.publicKey,C=O===32;if(!C&&O!==57)throw new Error("only defined for 25519 and 448");let k=C?c.div(F+S,F-S):c.div(S-F,S+F);return c.toBytes(k)},toMontgomerySecret(v){let S=I.secretKey;j(v,S);let O=r(v.subarray(0,S));return p(O).subarray(0,S)}};return Object.freeze(I),Object.freeze(M),Object.freeze({keygen:Rr(w,b),getPublicKey:b,sign:y,verify:E,utils:M,Point:t,lengths:I})}var os=BigInt(0),ne=BigInt(1),Ar=BigInt(2);var ss=BigInt(5),is=BigInt(8),ve=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),rn={p:ve,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:is,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function as(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=ve,c=t*t%s*t%s,l=q(c,Ar,s)*c%s,a=q(l,ne,s)*t%s,u=q(a,ss,s)*a%s,f=q(u,e,s)*u%s,p=q(f,n,s)*f%s,d=q(p,r,s)*p%s,m=q(d,o,s)*d%s,g=q(m,o,s)*d%s,h=q(g,e,s)*u%s;return {pow_p_5_8:q(h,Ar,s)*t%s,b2:c}}function cs(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var en=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function on(t,e){let n=ve,r=D(e*e*e,n),o=D(r*r*e,n),s=as(t*o).pow_p_5_8,i=D(t*r*s,n),c=D(e*i*i,n),l=i,a=D(i*en,n),u=c===t,f=c===D(-t,n),p=c===D(-t*en,n);return u&&(i=l),(f||p)&&(i=a),te(i,n)&&(i=D(-i,n)),{isValid:u||f,value:i}}var ce=Ir(rn,{uvRatio:on}),ae=ce.Fp,Br=ce.Fn;function ls(t){return Or(ce,et,Object.assign({adjustScalarBytes:cs,zip215:true},t))}var Mr=ls({});var tn=en;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var fs=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var Cr=t=>on(ne,t),ms=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),nn=t=>ae.create(ee(t)&ms);var le=class t extends ft{static BASE=new t(ce.BASE);static ZERO=new t(ce.ZERO);static Fp=ae;static Fn=Br;constructor(e){super(e);}static fromAffine(e){return new t(ce.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoPoint expected")}init(e){return new t(e)}static fromBytes(e){K(e,32);let{a:n,d:r}=rn,o=ve,s=R=>ae.create(R),i=nn(e);if(!ir(ae.toBytes(i),e)||te(i,o))throw new Error("invalid ristretto255 encoding 1");let c=s(i*i),l=s(ne+n*c),a=s(ne-n*c),u=s(l*l),f=s(a*a),p=s(n*r*u-f),{isValid:d,value:m}=Cr(s(p*f)),g=s(m*a),h=s(m*g*p),b=s((i+i)*g);te(b,o)&&(b=s(-b));let x=s(l*h),y=s(b*x);if(!d||te(y,o)||x===os)throw new Error("invalid ristretto255 encoding 2");return new t(new ce(b,x,ne,y))}static fromHex(e){return t.fromBytes(Ce(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,s=ve,i=h=>ae.create(h),c=i(i(r+n)*i(r-n)),l=i(e*n),a=i(l*l),{value:u}=Cr(i(c*a)),f=i(u*c),p=i(u*l),d=i(f*p*o),m;if(te(o*d,s)){let h=i(n*tn),b=i(e*tn);e=h,n=b,m=i(f*fs);}else m=p;te(e*d,s)&&(n=i(-n));let g=i((r-n)*m);return te(g,s)&&(g=i(-g)),ae.toBytes(g)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:s}=e.ep,i=a=>ae.create(a),c=i(n*s)===i(r*o),l=i(r*s)===i(n*o);return c||l}is0(){return this.equals(t.ZERO)}};Object.freeze(le.BASE);Object.freeze(le.ZERO);Object.freeze(le.prototype);Object.freeze(le);var Dr=`-----BEGIN PUBLIC KEY-----
11
11
  MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
12
- -----END PUBLIC KEY-----`;function Dr(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function sn(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4?"=".repeat(4-e.length%4):"";return Dr(e+n)}function ms(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Dr(e);return n.subarray(n.length-32)}var hs=new TextEncoder,jr=new TextDecoder;function gs(t){return typeof t=="object"&&t!==null&&"keys"in t}function an(t,e){let n=t.split(".");if(n.length!==3)return {ok:false,reason:"malformed token"};let r=n[0],o=n[1],s=n[2],i;try{i=JSON.parse(jr.decode(sn(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let c;if(gs(e)){let u=typeof i.kid=="string"?i.kid:e.defaultKid,f=e.keys[u];if(!f)return {ok:false,reason:`unknown key id "${u}"`};c=f;}else {if(!e)return {ok:false,reason:"no verification key"};c=e;}let l;try{if(l=ms(c),l.length!==32)return {ok:!1,reason:"invalid public key"}}catch{return {ok:false,reason:"invalid public key"}}let a=false;try{a=Br.verify(sn(s),hs.encode(`${r}.${o}`),l);}catch{return {ok:false,reason:"signature verification error"}}return a?{ok:true,header:i,payloadBytes:sn(o)}:{ok:false,reason:"bad signature"}}function ve(t,e){let n=an(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(jr.decode(n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function cn(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"active":e<=r?"grace":"expired"}function uc(t,e,n={}){let r=ve(t,e);if(!r.signatureValid||!r.payload)return {status:"invalid",...r.reason?{reason:r.reason}:{}};let o=r.payload,s=n.nowSeconds??Math.floor(Date.now()/1e3),i=cn(o,s,n.revoked);return i==="revoked"?{status:i,payload:o,reason:"license revoked"}:{status:i,payload:o}}var Pr="BVSALA-REVOC",bs=300,xs=new TextDecoder;function Fr(t,e,n={}){let r=a=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:a}),o=an(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");if(o.header?.typ!==Pr)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${Pr})`);let s;try{s=JSON.parse(xs.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof s.seq!="number"||typeof s.asOf!="number"||!Array.isArray(s.revoked))return r("malformed revocation payload");let i=n.minSeq??0;if(s.seq<i)return r(`stale/rolled-back list (seq ${s.seq} < ${i})`);let c=n.nowSeconds??Math.floor(Date.now()/1e3),l=n.maxSkewSeconds??bs;return s.asOf>c+l?r(`asOf too far in the future (${s.asOf} > ${c+l})`):{ok:true,seq:s.seq,asOf:s.asOf,revoked:new Set(s.revoked)}}var we=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){return this._seq}get asOf(){return this._asOf}get lastContactAt(){return this._lastContactAt}markContact(e){e>this._lastContactAt&&(this._lastContactAt=e);}has(e){return this.set.has(e)}snapshot(){return this.set}apply(e){if(e.seq<this._seq)return false;let n=this.set.size;for(let s of e.revoked)this.set.add(s);let r=this.set.size>n,o=e.seq>this._seq;return e.seq>this._seq&&(this._seq=e.seq),e.asOf>this._asOf&&(this._asOf=e.asOf),r||o}};function dt(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),s=ve(t,e),i=s.signatureValid?s.payload:void 0,c=new Set(i?.features??[]),l=()=>{if(!i)return "invalid";let u=cn(i,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(u==="active"||u==="grace")){let f=i.expires_at+i.grace_days*86400,p=Math.min(o,f),d=Math.max(n.revocation.lastContactAt,p);if(r()-d>n.maxStalenessSeconds)return "expired"}return u},a=()=>{let u=l();return u==="active"||u==="grace"};return {isEntitled:u=>a()&&c.has(u),isActive:()=>a(),status:l,refreshAfter:()=>{if(i)return Math.min(i.expires_at,r()+86400)}}}function zr(t,e,n){return dt(t,e,{revocation:new we,...n?{now:n}:{}})}var Se={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4};function ys(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>0){let o=Math.pow(2,Math.min(t.consecutiveFailures,4));n=Math.min(t.maxIntervalSeconds,t.floorSeconds*o);}else {let o=t.refreshAfter!=null?t.refreshAfter-t.nowSeconds:t.pollIntervalSeconds,s=o<0?t.pollIntervalSeconds:o;n=Math.min(t.pollIntervalSeconds,Math.max(t.floorSeconds,s));}let r=1+(e()*2-1)*t.jitterRatio;return Math.max(t.floorSeconds,n*r)}var vs=10,pt=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;warnedNoFetch=false;lastEtag=null;consecutive304=0;now(){return this.opts.nowSeconds?this.opts.nowSeconds():Math.floor(Date.now()/1e3)}resolveFetch(){return this.opts.fetchImpl?this.opts.fetchImpl:typeof fetch<"u"?fetch:void 0}async pollOnce(){let e=this.resolveFetch();if(!e){this.warnedNoFetch||(this.warnedNoFetch=true,console.warn("[bv-sala] no global fetch available; revocation call-home disabled (offline). License expiry is still enforced from the token.")),this.opts.onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??Se.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let s={accept:"application/json"};this.lastEtag&&(s["if-none-match"]=this.lastEtag);try{let i=await e(this.opts.url,{signal:n.signal,headers:s});if(i.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=vs&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!i.ok)throw new Error(`revocations HTTP ${i.status}`);let c=i.headers.get("etag");c&&(this.lastEtag=c);let l=await i.json();if(!l.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let a=Fr(l.list,this.opts.publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??Se.maxSkewSeconds});if(!a.ok){this.opts.onEvent?.({type:"rejected",reason:a.reason??"rejected"});return}this.opts.snapshot.markContact(this.now());let u=this.opts.snapshot.apply(a);this.opts.onEvent?.(u?{type:"applied",seq:a.seq,size:this.opts.snapshot.snapshot().size}:{type:"unchanged",seq:a.seq});}catch(i){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:i});}finally{clearTimeout(o),this.controller=null;}}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)return;let e=ys({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??Se.floorSeconds,pollIntervalSeconds:this.opts.pollIntervalSeconds??Se.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??Se.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??Se.jitterRatio,...this.opts.random?{random:this.opts.random}:{}});this.timer=setTimeout(()=>{this.pollOnce().finally(()=>this.schedule());},e*1e3),this.timer.unref?.();}stop(){this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.controller?.abort();}};var je=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;flushing=false;constructor(e){this.options=e,this.now=e.now??(()=>Date.now()),this.flushIntervalMs=e.flushIntervalMs??15e3,this.maxBatch=e.maxBatch??50,this.maxBuffer=e.maxBuffer??1e3,this.ci=e.ci??false;}setSeat(e,n){e&&(this.seatId=e),this.ci=n;}record(e){this.buffer.push({report:e,at:this.now()}),this.buffer.length>this.maxBuffer&&this.buffer.splice(0,this.buffer.length-this.maxBuffer),this.buffer.length>=this.maxBatch&&this.flush();}start(){this.timer||(this.timer=setInterval(()=>{this.flush();},this.flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async flush(){if(this.flushing||this.buffer.length===0)return;let e=this.options.fetchImpl??globalThis.fetch;if(!e)return;this.flushing=true;let n=this.buffer.splice(0,this.maxBatch);try{let r=n.map(s=>this.toWire(s)),o=await e(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.options.serviceAccountKey}`},body:JSON.stringify(r)});!o.ok&&o.status>=500&&this.requeue(n);}catch{this.requeue(n);}finally{this.flushing=false;}}requeue(e){this.buffer=[...e,...this.buffer],this.buffer.length>this.maxBuffer&&(this.buffer.length=this.maxBuffer);}toWire(e){let n=e.report;return {orgId:this.options.orgId??"self",...this.seatId?{seatId:this.seatId}:{},...this.ci?{ci:true}:{},requestId:n.requestId,model:n.model,at:e.at,avoidedLlm:n.calls.avoidedLlm,actualLlm:n.calls.actualLlm,baselineInputTokens:n.tokens.baselineInput,actualInputTokens:n.tokens.actualInput,eliminatedInputTokens:n.tokens.eliminatedInput,compressedInputTokens:n.tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutputTokens:n.tokens.actualOutput,providerCachedInputTokens:n.tokens.providerCachedInput??0,cacheResult:n.cache.result,baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{}}}};function mt(){return globalThis.process}function ws(t){if(/^[0-9a-f]{12}$/.test(t)||/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||/^ip-\d{1,3}(-\d{1,3}){3}$/i.test(t))return true;let e="[bcdfghjklmnpqrstvwxz2456789]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function Ss(t){return !!(t.AWS_LAMBDA_FUNCTION_NAME??t.LAMBDA_TASK_ROOT??t.VERCEL??t.VERCEL_ENV??t.K_SERVICE??t.FUNCTION_TARGET??t.FUNCTIONS_WORKER_RUNTIME??t.NETLIFY)}async function ks(){if(mt()?.execPath)try{let e=await import(["node","os"].join(":")),n=typeof e.hostname=="function"?e.hostname():"";return n.length>0?n:void 0}catch{return}}async function Es(t,e=ks){if(t.KUBERNETES_SERVICE_HOST||Ss(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||ws(n)))return n}async function Ts(){let t=mt();if(!t||!t.env)return;let e=t.env,n=await Es(e),r=[t.platform,t.arch,t.execPath,n,e.USER??e.USERNAME??e.LOGNAME,e.HOME??e.USERPROFILE].filter(o=>typeof o=="string"&&o.length>0);return r.length?r.join("|"):void 0}var Rs=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function ln(){let t=mt()?.env;if(!t)return false;for(let e of Rs){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function Is(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let i=await n.subtle.importKey("raw",r.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),c=await n.subtle.sign("HMAC",i,r.encode(e));return [...new Uint8Array(c)].map(l=>l.toString(16).padStart(2,"0")).join("")}catch{}let o=2166136261,s=`${t}|${e}`;for(let i=0;i<s.length;i++)o^=s.charCodeAt(i),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function un(t){let n=mt()?.env?.BVSALA_SEAT_ID;if(n&&Os.test(n))return n;let r=await Ts();if(!r)return;let o=await Is(t,r);if(o)return `m-${o.slice(0,32)}`}var Os=/^[A-Za-z0-9._:/-]{1,128}$/;var Nr={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function $r(t){return {exactCache:t.exactCache??new ze,semanticCache:t.semanticCache,singleflight:t.singleflight??new Ne,resolvers:t.resolvers??Sn(),router:t.router??new $e,toolSelector:t.toolSelector??new Ve,formatSelector:t.formatSelector??new qe({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new Ge,constraintBackends:t.constraintBackends??[]}}var _s=36e5,Cs=7*86400,As=3e4,ht=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;avisadoDeCredencial=false;currentExpiresAt;currentOrg;constructor(e){this.opts=e,this.pollIntervalMs=e.pollIntervalMs??_s,this.refreshLeadSeconds=e.refreshLeadSeconds??Cs;let n=ve(e.initialToken,e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.expires_at:0,this.currentOrg=n.signatureValid?n.payload?.org_id:void 0;}start(){this.timer||(this.checkNow(),this.timer=setInterval(()=>{this.checkNow();},this.pollIntervalMs),this.timer.unref?.());}stop(){this.parado=true,this.timer&&clearInterval(this.timer),this.timer=null,this.controller?.abort(),this.controller=null;}nowSeconds(){return Math.floor((this.opts.now?this.opts.now():Date.now())/1e3)}async checkNow(){if(this.enVuelo||this.parado||this.currentExpiresAt-this.nowSeconds()>this.refreshLeadSeconds)return false;this.enVuelo=true;let e=new AbortController;this.controller=e;let n=setTimeout(()=>e.abort(),this.opts.requestTimeoutMs??As);n.unref?.();try{let o=await(this.opts.fetchImpl??globalThis.fetch.bind(globalThis))(this.opts.url,{signal:e.signal,headers:{authorization:`Bearer ${this.opts.serviceAccountKey}`,accept:"application/json"}});if(!o.ok)return (o.status===401||o.status===403||o.status===404)&&!this.avisadoDeCredencial&&(this.avisadoDeCredencial=!0,console.warn(`[bv-sala] la recogida autom\xE1tica de la licencia renovada falla con HTTP ${o.status} en ${this.opts.url}. Revisa 'serviceAccountKey' (\xBFrotada? \xBFde otra organizaci\xF3n?) y 'licenseServerUrl': mientras no funcione, el token NO se renovar\xE1 solo y el SDK dejar\xE1 de operar al terminar el periodo de gracia.`)),!1;let s=await o.json();if(typeof s.token!="string")return !1;let i=ve(s.token,this.opts.publicKey);return !i.signatureValid||!i.payload||i.payload.expires_at<=this.currentExpiresAt||this.currentOrg&&i.payload.org_id!==this.currentOrg||this.opts.revocados?.snapshot().has(i.payload.jti)||this.parado?!1:(this.currentExpiresAt=i.payload.expires_at,this.currentOrg=i.payload.org_id,this.opts.onNewToken(s.token),!0)}catch{return false}finally{clearTimeout(n),this.controller===e&&(this.controller=null),this.enVuelo=false;}}};var gt=class{deps;config;now;generateId;illustrativePriceWarned=false;contratosQueIncumplen;constructor(e){this.config=e,this.deps=$r(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>bt()),this.contratosQueIncumplen=e.constraintMemory??new Set;}async generate(e){this.assertLicensed();let n={llamadas:0,falloDelProveedor:false};try{return await this.generateOptimized(e,n)}catch(r){if(r instanceof le||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0)throw r;return await this.failOpenDirect(e,r)}}async llamarProveedor(e,n){n.llamadas+=1;try{return await this.config.provider.generate(e)}catch(r){throw n.falloDelProveedor=true,r}}devOpen(){return false}assertLicensed(){if(this.devOpen())return;let e=this.config.licenseGate;if(e&&typeof e.isActive=="function"){if(e.isActive())return;let n=typeof e.status=="function"?e.status():void 0;throw new le(`BiVelio license is not active${n?` (${n})`:""}. Renew your subscription at https://savings.bivelio.com`,n)}throw e?new le("licenseGate must implement isActive(). A gate without it cannot prove the licence is live, so the pipeline refuses to run. Pass { licenseKey } for enforced licensing, or { devUnlicensed: true } for local development.","invalid"):new le("No BiVelio license configured. Pass { licenseKey } from your subscription (or { devUnlicensed: true } for local dev). Get a key at https://savings.bivelio.com")}async generateOptimized(e,n={llamadas:0,falloDelProveedor:false}){this.assertLicensed();let r=new _e(this.now),o=new he,s=St(e),i=kt(s),c=e.savings??{},l=this.costModelFor(e.model);r.record("canonicalize","done",{tenant:s.tenantId,contract:s.contractId}),r.record("policy",i.reasons.join("; ")||"no restrictions",{allowExactCache:i.allowExactCache,allowSemanticCache:i.allowSemanticCache});let a=this.tokensFor(this.assembleBaselinePrompt(e),e),u=e.response?.maxOutputTokens??256;if(o.baselineInput=a,o.baselineOutput=u,o.baselineTools=e.tools?.length??0,c.deterministicResolvers!==false){let m=this.deps.resolvers.try(s);if(m)return o.avoidCall(a,this.tokensFor(m.text,e)),r.record("resolver",m.resolver,{avoided:true}),this.finish(e,s,{text:m.text,data:m.data,storedAtMs:this.now()},"deterministic",o,l,r,Pe(),Fe())}let f=gn(s);if(i.allowExactCache&&c.exactCache!==false){let m=await this.deps.exactCache.get(f);if(m)return o.avoidCall(a,this.tokensFor(m.text,e)),r.record("exact-cache","hit",{ageMs:this.now()-m.storedAtMs}),this.finish(e,s,m,"exact",o,l,r,Pe(),Fe(),this.now()-m.storedAtMs);r.record("exact-cache","miss");}let p=bn(s),d=()=>this.expensivePath(n,e,s,i,c,o,l,r,f,a);if(i.allowSingleflight&&c.singleflight!==false){let{value:m,coalesced:g}=await this.deps.singleflight.run(p,d);return g?(r.record("singleflight","coalesced",{key:p}),this.asCoalescedFollower(m,a,this.tokensFor(m.text??"",e),l)):m}return d()}async expensivePath(e,n,r,o,s,i,c,l,a,u){let f=this.entitled("semantic_cache");if(o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&!f&&l.record("semantic-cache","degraded: feature not licensed (free tier)"),o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&f){let k=await this.deps.semanticCache.find(r);if(k)return i.avoidCall(u,this.tokensFor(k.record.answer.text,n)),l.record("semantic-cache","hit",{confidence:k.confidence,similarity:k.similarity}),this.finish(n,r,k.record.answer,"semantic",i,c,l,Pe(),Fe(),k.ageMs,k.confidence);l.record("semantic-cache","miss");}let p=s.router===false,d=p?Pe():this.deps.router.classify(r);l.record("router",d.executionClass,{confidence:d.confidence,reason:d.reason});let m=p?this.deps.toolSelector.passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,d.executionClass);i.actualTools=m.tools.length,m.droppedIds.length&&l.record("tool-selector",m.reason,{dropped:m.droppedIds}),i.baselineRetrieval=d.rounds;let g=await En({execution:d.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.maxRounds??d.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});i.actualRetrieval=g.rounds,g.retrievedCount>0&&l.record("retrieval",`kept ${g.keptCount}/${g.retrievedCount}`,{rounds:g.rounds});let h=Fe(),b=[...n.messages];if(g.docs.length>0){let k=g.docs.map((T,B)=>`[${T.source??T.id??`doc${B+1}`}]
12
+ -----END PUBLIC KEY-----`;function jr(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function sn(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4?"=".repeat(4-e.length%4):"";return jr(e+n)}function gs(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=jr(e);return n.subarray(n.length-32)}var bs=new TextEncoder,Pr=new TextDecoder;function xs(t){return typeof t=="object"&&t!==null&&"keys"in t}function an(t,e){let n=t.split(".");if(n.length!==3)return {ok:false,reason:"malformed token"};let r=n[0],o=n[1],s=n[2],i;try{i=JSON.parse(Pr.decode(sn(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let c;if(xs(e)){let u=typeof i.kid=="string"?i.kid:e.defaultKid,f=e.keys[u];if(!f)return {ok:false,reason:`unknown key id "${u}"`};c=f;}else {if(!e)return {ok:false,reason:"no verification key"};c=e;}let l;try{if(l=gs(c),l.length!==32)return {ok:!1,reason:"invalid public key"}}catch{return {ok:false,reason:"invalid public key"}}let a=false;try{a=Mr.verify(sn(s),bs.encode(`${r}.${o}`),l);}catch{return {ok:false,reason:"signature verification error"}}return a?{ok:true,header:i,payloadBytes:sn(o)}:{ok:false,reason:"bad signature"}}function we(t,e){let n=an(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(Pr.decode(n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function cn(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"active":e<=r?"grace":"expired"}function hc(t,e,n={}){let r=we(t,e);if(!r.signatureValid||!r.payload)return {status:"invalid",...r.reason?{reason:r.reason}:{}};let o=r.payload,s=n.nowSeconds??Math.floor(Date.now()/1e3),i=cn(o,s,n.revoked);return i==="revoked"?{status:i,payload:o,reason:"license revoked"}:{status:i,payload:o}}var Fr="BVSALA-REVOC",ys=300,vs=new TextDecoder;function zr(t,e,n={}){let r=a=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:a}),o=an(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");if(o.header?.typ!==Fr)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${Fr})`);let s;try{s=JSON.parse(vs.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof s.seq!="number"||typeof s.asOf!="number"||!Array.isArray(s.revoked))return r("malformed revocation payload");let i=n.minSeq??0;if(s.seq<i)return r(`stale/rolled-back list (seq ${s.seq} < ${i})`);let c=n.nowSeconds??Math.floor(Date.now()/1e3),l=n.maxSkewSeconds??ys;return s.asOf>c+l?r(`asOf too far in the future (${s.asOf} > ${c+l})`):{ok:true,seq:s.seq,asOf:s.asOf,revoked:new Set(s.revoked)}}var Se=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){return this._seq}get asOf(){return this._asOf}get lastContactAt(){return this._lastContactAt}markContact(e){e>this._lastContactAt&&(this._lastContactAt=e);}has(e){return this.set.has(e)}snapshot(){return this.set}apply(e){if(e.seq<this._seq)return false;let n=this.set.size;for(let s of e.revoked)this.set.add(s);let r=this.set.size>n,o=e.seq>this._seq;return e.seq>this._seq&&(this._seq=e.seq),e.asOf>this._asOf&&(this._asOf=e.asOf),r||o}};function dt(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),s=we(t,e),i=s.signatureValid?s.payload:void 0,c=new Set(i?.features??[]),l=()=>{if(!i)return "invalid";let u=cn(i,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(u==="active"||u==="grace")){let f=i.expires_at+i.grace_days*86400,p=Math.min(o,f),d=Math.max(n.revocation.lastContactAt,p);if(r()-d>n.maxStalenessSeconds)return "stale"}return u},a=()=>{let u=l();return u==="active"||u==="grace"};return {isEntitled:u=>a()&&c.has(u),isActive:()=>a(),status:l,refreshAfter:()=>{if(i)return Math.min(i.expires_at,r()+86400)}}}function Nr(t,e,n){return dt(t,e,{revocation:new Se,...n?{now:n}:{}})}var ke={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},$r=3,ws=12;function Ss(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>0){let o=Math.pow(2,Math.min(t.consecutiveFailures,4));n=Math.min(t.maxIntervalSeconds,t.floorSeconds*o);}else {let o=t.refreshAfter!=null?t.refreshAfter-t.nowSeconds:t.pollIntervalSeconds,s=o<0?t.pollIntervalSeconds:o;n=Math.min(t.pollIntervalSeconds,Math.max(t.floorSeconds,s));}let r=1+(e()*2-1)*t.jitterRatio;return Math.max(t.floorSeconds,n*r)}var ks=10,pt=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;warnedNoFetch=false;lastEtag=null;consecutive304=0;now(){return this.opts.nowSeconds?this.opts.nowSeconds():Math.floor(Date.now()/1e3)}resolveFetch(){return this.opts.fetchImpl?this.opts.fetchImpl:typeof fetch<"u"?fetch:void 0}async pollOnce(){let e=this.resolveFetch();if(!e){this.warnedNoFetch||(this.warnedNoFetch=true,console.warn("[bv-sala] no global fetch available; revocation call-home disabled (offline). License expiry is still enforced from the token.")),this.opts.onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??ke.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let s={accept:"application/json"};this.lastEtag&&(s["if-none-match"]=this.lastEtag);try{let i=await e(this.opts.url,{signal:n.signal,headers:s});if(i.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=ks&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!i.ok)throw new Error(`revocations HTTP ${i.status}`);let c=i.headers.get("etag"),l=await i.json();if(!l.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let a=zr(l.list,this.opts.publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??ke.maxSkewSeconds});if(!a.ok){let f=a.reason??"rejected";this.opts.onEvent?.({type:"rejected",reason:f}),this.avisar(`rechazada:${f}`,`[bv-sala] la lista de revocaciones NO verifica (${f}). Se mantiene la \xFAltima buena conocida, as\xED que las revocaciones YA conocidas se siguen aplicando, pero las nuevas no llegan. Revise ${this.opts.url}.`);return}c&&(this.lastEtag=c),this.opts.snapshot.markContact(this.now());let u=this.opts.snapshot.apply(a);this.opts.onEvent?.(u?{type:"applied",seq:a.seq,size:this.opts.snapshot.snapshot().size}:{type:"unchanged",seq:a.seq});}catch(i){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:i}),this.avisarFalloDeRed(i);}finally{clearTimeout(o),this.controller=null;}}callado(){return !!(this.opts.silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||J(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;let n=this.consecutiveFailures;if(n<$r||(n-$r)%ws!==0)return;let r=e instanceof Error?e.message:String(e);console.warn(`[bv-sala] no se ha podido contactar con el servidor de revocaciones ${n} veces seguidas (${r}). La licencia SIGUE funcionando y las revocaciones ya conocidas se siguen aplicando, pero las NUEVAS no est\xE1n llegando. Compruebe la salida hacia ${this.opts.url}.`);}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)return;let e=Ss({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??ke.floorSeconds,pollIntervalSeconds:this.opts.pollIntervalSeconds??ke.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??ke.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??ke.jitterRatio,...this.opts.random?{random:this.opts.random}:{}});this.timer=setTimeout(()=>{this.pollOnce().finally(()=>this.schedule());},e*1e3),this.timer.unref?.();}stop(){this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.controller?.abort();}};var je=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;flushing=false;constructor(e){this.options=e,this.now=e.now??(()=>Date.now()),this.flushIntervalMs=e.flushIntervalMs??15e3,this.maxBatch=e.maxBatch??50,this.maxBuffer=e.maxBuffer??1e3,this.ci=e.ci??false;}setSeat(e,n){e&&(this.seatId=e),this.ci=n;}record(e){this.buffer.push({report:e,at:this.now()}),this.buffer.length>this.maxBuffer&&this.buffer.splice(0,this.buffer.length-this.maxBuffer),this.buffer.length>=this.maxBatch&&this.flush();}start(){this.timer||(this.timer=setInterval(()=>{this.flush();},this.flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async flush(){if(this.flushing||this.buffer.length===0)return;let e=this.options.fetchImpl??globalThis.fetch;if(!e)return;this.flushing=true;let n=this.buffer.splice(0,this.maxBatch);try{let r=n.map(s=>this.toWire(s)),o=await e(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.options.serviceAccountKey}`},body:JSON.stringify(r)});!o.ok&&o.status>=500?this.requeue(n):(o.status===401||o.status===403)&&(J(`metering-auth-${o.status}`,`[bv-sala] el env\xEDo de uso est\xE1 siendo rechazado con HTTP ${o.status} en ${this.options.url}. Revisa 'serviceAccountKey' (\xBFrotada? \xBFrevocada? \xBFde otra organizaci\xF3n?). Mientras no funcione NO se reporta uso: el panel dir\xE1 que no ve tr\xE1fico y los asientos facturables saldr\xE1n a cero.`),this.options.onAuthError?.(o.status));}catch{this.requeue(n);}finally{this.flushing=false;}}requeue(e){this.buffer=[...e,...this.buffer],this.buffer.length>this.maxBuffer&&(this.buffer.length=this.maxBuffer);}toWire(e){let n=e.report;return {orgId:this.options.orgId??"self",...this.seatId?{seatId:this.seatId}:{},...this.ci?{ci:true}:{},requestId:n.requestId,model:n.model,at:e.at,avoidedLlm:n.calls.avoidedLlm,actualLlm:n.calls.actualLlm,baselineInputTokens:n.tokens.baselineInput,actualInputTokens:n.tokens.actualInput,eliminatedInputTokens:n.tokens.eliminatedInput,compressedInputTokens:n.tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutputTokens:n.tokens.actualOutput,providerCachedInputTokens:n.tokens.providerCachedInput??0,cacheResult:n.cache.result,baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{}}}};function mt(){return globalThis.process}function Es(t){if(/^[0-9a-f]{12}$/.test(t)||/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||/^ip-\d{1,3}(-\d{1,3}){3}$/i.test(t))return true;let e="[bcdfghjklmnpqrstvwxz2456789]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function Ts(t){return !!(t.AWS_LAMBDA_FUNCTION_NAME??t.LAMBDA_TASK_ROOT??t.VERCEL??t.VERCEL_ENV??t.K_SERVICE??t.FUNCTION_TARGET??t.FUNCTIONS_WORKER_RUNTIME??t.NETLIFY)}async function Rs(){if(mt()?.execPath)try{let e=await import(["node","os"].join(":")),n=typeof e.hostname=="function"?e.hostname():"";return n.length>0?n:void 0}catch{return}}async function Is(t,e=Rs){if(t.KUBERNETES_SERVICE_HOST||Ts(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||Es(n)))return n}async function Os(){let t=mt();if(!t||!t.env)return;let e=t.env,n=await Is(e),r=[t.platform,t.arch,t.execPath,n,e.USER??e.USERNAME??e.LOGNAME,e.HOME??e.USERPROFILE].filter(o=>typeof o=="string"&&o.length>0);return r.length?r.join("|"):void 0}var _s=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function ln(){let t=mt()?.env;if(!t)return false;for(let e of _s){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function As(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let i=await n.subtle.importKey("raw",r.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),c=await n.subtle.sign("HMAC",i,r.encode(e));return [...new Uint8Array(c)].map(l=>l.toString(16).padStart(2,"0")).join("")}catch{}let o=2166136261,s=`${t}|${e}`;for(let i=0;i<s.length;i++)o^=s.charCodeAt(i),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function un(t){let n=mt()?.env?.BVSALA_SEAT_ID;if(n&&Cs.test(n))return n;let r=await Os();if(!r)return;let o=await As(t,r);if(o)return `m-${o.slice(0,32)}`}var Cs=/^[A-Za-z0-9._:/-]{1,128}$/;var Vr={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function Ur(t){return {exactCache:t.exactCache??new ze,semanticCache:t.semanticCache,singleflight:t.singleflight??new Ne,resolvers:t.resolvers??kn(),router:t.router??new $e,toolSelector:t.toolSelector??new Ve,formatSelector:t.formatSelector??new qe({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new Ge,constraintBackends:t.constraintBackends??[]}}var Ls=36e5,Bs=7*86400,Ms=3e4,ht=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;avisadoDeCredencial=false;currentExpiresAt;currentOrg;constructor(e){this.opts=e,this.pollIntervalMs=e.pollIntervalMs??Ls,this.refreshLeadSeconds=e.refreshLeadSeconds??Bs;let n=we(e.initialToken,e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.expires_at:0,this.currentOrg=n.signatureValid?n.payload?.org_id:void 0;}start(){this.timer||(this.checkNow(),this.timer=setInterval(()=>{this.checkNow();},this.pollIntervalMs),this.timer.unref?.());}stop(){this.parado=true,this.timer&&clearInterval(this.timer),this.timer=null,this.controller?.abort(),this.controller=null;}nowSeconds(){return Math.floor((this.opts.now?this.opts.now():Date.now())/1e3)}async checkNow(){if(this.enVuelo||this.parado||this.currentExpiresAt-this.nowSeconds()>this.refreshLeadSeconds)return false;this.enVuelo=true;let e=new AbortController;this.controller=e;let n=setTimeout(()=>e.abort(),this.opts.requestTimeoutMs??Ms);n.unref?.();try{let o=await(this.opts.fetchImpl??globalThis.fetch.bind(globalThis))(this.opts.url,{signal:e.signal,headers:{authorization:`Bearer ${this.opts.serviceAccountKey}`,accept:"application/json"}});if(!o.ok)return (o.status===401||o.status===403||o.status===404)&&!this.avisadoDeCredencial&&(this.avisadoDeCredencial=!0,console.warn(`[bv-sala] la recogida autom\xE1tica de la licencia renovada falla con HTTP ${o.status} en ${this.opts.url}. Revisa 'serviceAccountKey' (\xBFrotada? \xBFde otra organizaci\xF3n?) y 'licenseServerUrl': mientras no funcione, el token NO se renovar\xE1 solo y el SDK dejar\xE1 de operar al terminar el periodo de gracia.`)),!1;let s=await o.json();if(typeof s.token!="string")return !1;let i=we(s.token,this.opts.publicKey);return !i.signatureValid||!i.payload||i.payload.expires_at<=this.currentExpiresAt||this.currentOrg&&i.payload.org_id!==this.currentOrg||this.opts.revocados?.snapshot().has(i.payload.jti)||this.parado?!1:(this.currentExpiresAt=i.payload.expires_at,this.currentOrg=i.payload.org_id,this.opts.onNewToken(s.token),!0)}catch{return false}finally{clearTimeout(n),this.controller===e&&(this.controller=null),this.enVuelo=false;}}};function Ds(t){switch(t){case "invalid":return "BiVelio license key is not valid (it does not verify). Check you pasted the WHOLE key, and that it is the license key from your dashboard \u2014 not the `bvk_` service-account key, which goes in `serviceAccountKey`. Keys: https://savings.bivelio.com/dashboard/install";case "revoked":return "BiVelio license has been revoked. If this is unexpected, check your billing status at https://savings.bivelio.com/dashboard/account or write to support@bivelio.com";case "stale":return "BiVelio could not confirm your license with the control plane in time \u2014 this is a connectivity problem, not a billing one: your license is still valid. Allow outbound HTTPS to your `licenseServerUrl` (https://savings.bivelio.com by default) and retry.";case "expired":case "grace":return `BiVelio license is not active (${t}). Renew your subscription at https://savings.bivelio.com`;default:return `BiVelio license is not active${t?` (${t})`:""}. See https://savings.bivelio.com/dashboard/account`}}var gt=class{deps;config;now;generateId;illustrativePriceWarned=false;contratosQueIncumplen;constructor(e){this.config=e,this.deps=Ur(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>bt()),this.contratosQueIncumplen=e.constraintMemory??new Set;}async generate(e){this.assertLicensed();let n={llamadas:0,falloDelProveedor:false};try{return await this.generateOptimized(e,n)}catch(r){if(r instanceof ue||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0)throw r;return await this.failOpenDirect(e,r)}}async llamarProveedor(e,n){n.llamadas+=1;try{return await this.config.provider.generate(e)}catch(r){throw n.falloDelProveedor=true,r}}devOpen(){return false}assertLicensed(){if(this.devOpen())return;let e=this.config.licenseGate;if(e&&typeof e.isActive=="function"){if(e.isActive())return;let n=typeof e.status=="function"?e.status():void 0;throw new ue(Ds(n),n)}throw e?new ue("licenseGate must implement isActive(). A gate without it cannot prove the licence is live, so the pipeline refuses to run. Pass { licenseKey } for enforced licensing, or { devUnlicensed: true } for local development.","invalid"):new ue("No BiVelio license configured. Pass { licenseKey } from your subscription (or { devUnlicensed: true } for local dev). Get a key at https://savings.bivelio.com")}async generateOptimized(e,n={llamadas:0,falloDelProveedor:false}){this.assertLicensed();let r=new _e(this.now),o=new ge,s=St(e),i=kt(s),c=e.savings??{},l=this.costModelFor(e.model);r.record("canonicalize","done",{tenant:s.tenantId,contract:s.contractId}),r.record("policy",i.reasons.join("; ")||"no restrictions",{allowExactCache:i.allowExactCache,allowSemanticCache:i.allowSemanticCache});let a=this.tokensFor(this.assembleBaselinePrompt(e),e),u=e.response?.maxOutputTokens??256;if(o.baselineInput=a,o.baselineOutput=u,o.baselineTools=e.tools?.length??0,c.deterministicResolvers!==false){let m=this.deps.resolvers.try(s);if(m)return o.avoidCall(a,this.tokensFor(m.text,e)),r.record("resolver",m.resolver,{avoided:true}),this.finish(e,s,{text:m.text,data:m.data,storedAtMs:this.now()},"deterministic",o,l,r,Pe(),Fe())}let f=bn(s);if(i.allowExactCache&&c.exactCache!==false){let m=await this.deps.exactCache.get(f);if(m)return o.avoidCall(a,this.tokensFor(m.text,e)),r.record("exact-cache","hit",{ageMs:this.now()-m.storedAtMs}),this.finish(e,s,m,"exact",o,l,r,Pe(),Fe(),this.now()-m.storedAtMs);r.record("exact-cache","miss");}let p=xn(s),d=()=>this.expensivePath(n,e,s,i,c,o,l,r,f,a);if(i.allowSingleflight&&c.singleflight!==false){let{value:m,coalesced:g}=await this.deps.singleflight.run(p,d);return g?(r.record("singleflight","coalesced",{key:p}),this.asCoalescedFollower(m,a,this.tokensFor(m.text??"",e),l)):m}return d()}async expensivePath(e,n,r,o,s,i,c,l,a,u){let f=this.entitled("semantic_cache");if(o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&!f&&l.record("semantic-cache","degraded: feature not licensed (free tier)"),o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&f){let k=await this.deps.semanticCache.find(r);if(k)return i.avoidCall(u,this.tokensFor(k.record.answer.text,n)),l.record("semantic-cache","hit",{confidence:k.confidence,similarity:k.similarity}),this.finish(n,r,k.record.answer,"semantic",i,c,l,Pe(),Fe(),k.ageMs,k.confidence);l.record("semantic-cache","miss");}let p=s.router===false,d=p?Pe():this.deps.router.classify(r);l.record("router",d.executionClass,{confidence:d.confidence,reason:d.reason});let m=p?this.deps.toolSelector.passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,d.executionClass);i.actualTools=m.tools.length,m.droppedIds.length&&l.record("tool-selector",m.reason,{dropped:m.droppedIds}),i.baselineRetrieval=d.rounds;let g=await Tn({execution:d.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.maxRounds??d.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});i.actualRetrieval=g.rounds,g.retrievedCount>0&&l.record("retrieval",`kept ${g.keptCount}/${g.retrievedCount}`,{rounds:g.rounds});let h=Fe(),b=[...n.messages];if(g.docs.length>0){let k=g.docs.map((T,B)=>`[${T.source??T.id??`doc${B+1}`}]
13
13
  ${T.text}`).join(`
14
14
 
15
15
  `);b.push({role:"system",content:`Retrieved context \u2014 answer using only this evidence and cite sources by [id]:
16
16
 
17
- ${k}`});}let x=Vr(n),y=n.response?.maxOutputTokens!=null?Math.floor(n.response.maxOutputTokens*3.2):null,R=this.contratosQueIncumplen.has(x)?dn(n.response?.schema,"",y):"";if(R&&b.push({role:"system",content:`JSON limits (not API-enforced): ${R}`}),n.structuredData!==void 0){let k=JSON.stringify(n.structuredData),T=this.tokensFor(k,n);if(s.serialization!==false){h=this.deps.formatSelector.choose(n.structuredData,{model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let B=this.tokensFor(h.encoded+h.instruction,n);i.compress(T,B),Ur(b,{role:"system",content:(h.instruction?h.instruction+`
18
- `:"")+h.encoded}),l.record("serialization",h.chosen,{reason:h.reason,jsonTokens:T,chosenTokens:B});}else Ur(b,{role:"system",content:k}),l.record("serialization","json-compact",{reason:"format selector disabled; sent compact JSON"});}if((s.compression===true||s.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let k=0,T=0,B=0,U=[];for(let z of b){if(z.role==="system"){B+=1,U.push(z);continue}let H=this.tokensFor(z.content,n),N=await this.config.compressor.compress({text:z.content}),ne=!N.skipped&&N.fidelityPassed,ke=ne?this.tokensFor(N.compressed,n):H;ne&&ke<H?(U.push({...z,content:N.compressed}),k+=H,T+=ke):U.push(z);}T<k?(b=U,i.compress(k,T),l.record("compression","applied",{before:k,after:T,protectedSystemMessages:B})):l.record("compression","skipped (no fidelity-passed net reduction)",{protectedSystemMessages:B}),i.compressionReport={originalTokens:k,compressedTokens:T,protectedSpans:B,fidelityPassed:true};}let E=n.response?.schema,_=E?Mn(n.model,E,this.deps.constraintBackends):{backend:"none",reason:"no output contract"};l.record("constraints",_.backend,{reason:_.reason});let I=this.now(),w=await this.llamarProveedor({model:n.model,messages:b,...m.tools.length?{tools:m.tools}:{},...E?{schema:E}:{},...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{},constraintBackend:_.backend},e);i.actualLlm=1,i.actualInput=w.usage.inputTokens,i.actualOutput=w.usage.outputTokens,i.sentInputLocal=this.tokensFor(this.assemblePromptText(b,m.tools),n),i.removedInputLocal=Math.max(0,u-i.sentInputLocal),i.estimatorExact=this.estimatorEsExacto(n),w.usage.cachedInputTokens&&i.providerCached(w.usage.cachedInputTokens);let C=w.text,L=true,M=(w.toolCalls?.length??0)>0;if(M&&(L=null,E&&l.record("validation","n/a: model requested tool calls (the output contract applies to the final answer)")),E&&!M){let k=fn(w.text),T=k.ok?Re(k.value,E):{valid:false,errors:[{path:"$",message:"not valid JSON"}]};!T.valid&&Bs(T.errors)&&this.contratosQueIncumplen.add(Vr(n));let B=w.finishReason==="length",U=!T.valid&&T.errors.some(z=>/not a valid regular expression/.test(z.message));if(!T.valid&&U)l.record("validation","repair-skipped",{reason:"schema defect (uncompilable pattern); no output can satisfy it, a retry is a wasted call",errors:T.errors}),Ie("esquema-roto","[bvsala] El contrato de respuesta tiene un `pattern` que no es un regex valido, asi que ninguna respuesta puede cumplirlo. NO se reintenta (seria una llamada pagada para el mismo fallo). Corrige el `pattern` del esquema.");else if(!T.valid&&B)l.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same cap would truncate again",maxOutputTokens:n.response?.maxOutputTokens??null,outputTokens:w.usage.outputTokens}),Ie("salida-truncada","[bvsala] La respuesta se cort\xF3 al agotar `maxOutputTokens`"+(n.response?.maxOutputTokens!=null?` (${n.response.maxOutputTokens})`:"")+", as\xED que no valida contra el contrato. NO se reintenta: con el mismo tope volver\xEDa a cortarse y ser\xEDa una llamada pagada para el mismo fallo. Sube `maxOutputTokens` o reduce lo que pide el contrato.");else if(!T.valid&&_.backend==="none"){i.retries=1,l.record("validation","repair-attempt",{errors:T.errors});let z=T.errors.slice(0,5).map(ne=>`- ${ne.path}: ${ne.message}`).join(`
17
+ ${k}`});}let x=Hr(n),y=n.response?.maxOutputTokens!=null?Math.floor(n.response.maxOutputTokens*3.2):null,R=this.contratosQueIncumplen.has(x)?dn(n.response?.schema,"",y):"";if(R&&b.push({role:"system",content:`JSON limits (not API-enforced): ${R}`}),n.structuredData!==void 0){let k=JSON.stringify(n.structuredData),T=this.tokensFor(k,n);if(s.serialization!==false){h=this.deps.formatSelector.choose(n.structuredData,{model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let B=this.tokensFor(h.encoded+h.instruction,n);i.compress(T,B),Kr(b,{role:"system",content:(h.instruction?h.instruction+`
18
+ `:"")+h.encoded}),l.record("serialization",h.chosen,{reason:h.reason,jsonTokens:T,chosenTokens:B});}else Kr(b,{role:"system",content:k}),l.record("serialization","json-compact",{reason:"format selector disabled; sent compact JSON"});}if((s.compression===true||s.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let k=0,T=0,B=0,U=[];for(let z of b){if(z.role==="system"){B+=1,U.push(z);continue}let H=this.tokensFor(z.content,n),N=await this.config.compressor.compress({text:z.content}),re=!N.skipped&&N.fidelityPassed,Ee=re?this.tokensFor(N.compressed,n):H;re&&Ee<H?(U.push({...z,content:N.compressed}),k+=H,T+=Ee):U.push(z);}T<k?(b=U,i.compress(k,T),l.record("compression","applied",{before:k,after:T,protectedSystemMessages:B})):l.record("compression","skipped (no fidelity-passed net reduction)",{protectedSystemMessages:B}),i.compressionReport={originalTokens:k,compressedTokens:T,protectedSpans:B,fidelityPassed:true};}let E=n.response?.schema,_=E?Dn(n.model,E,this.deps.constraintBackends):{backend:"none",reason:"no output contract"};l.record("constraints",_.backend,{reason:_.reason});let I=this.now(),w=await this.llamarProveedor({model:n.model,messages:b,...m.tools.length?{tools:m.tools}:{},...E?{schema:E}:{},...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{},constraintBackend:_.backend},e);i.actualLlm=1,i.actualInput=w.usage.inputTokens,i.actualOutput=w.usage.outputTokens,i.sentInputLocal=this.tokensFor(this.assemblePromptText(b,m.tools),n),i.removedInputLocal=Math.max(0,u-i.sentInputLocal),i.estimatorExact=this.estimatorEsExacto(n),w.usage.cachedInputTokens&&i.providerCached(w.usage.cachedInputTokens);let A=w.text,L=true,M=(w.toolCalls?.length??0)>0;if(M&&(L=null,E&&l.record("validation","n/a: model requested tool calls (the output contract applies to the final answer)")),E&&!M){let k=fn(w.text),T=k.ok?Ie(k.value,E):{valid:false,errors:[{path:"$",message:"not valid JSON"}]};!T.valid&&Ps(T.errors)&&this.contratosQueIncumplen.add(Hr(n));let B=w.finishReason==="length",U=!T.valid&&T.errors.some(z=>/not a valid regular expression/.test(z.message));if(!T.valid&&U)l.record("validation","repair-skipped",{reason:"schema defect (uncompilable pattern); no output can satisfy it, a retry is a wasted call",errors:T.errors}),J("esquema-roto","[bvsala] El contrato de respuesta tiene un `pattern` que no es un regex valido, asi que ninguna respuesta puede cumplirlo. NO se reintenta (seria una llamada pagada para el mismo fallo). Corrige el `pattern` del esquema.");else if(!T.valid&&B)l.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same cap would truncate again",maxOutputTokens:n.response?.maxOutputTokens??null,outputTokens:w.usage.outputTokens}),J("salida-truncada","[bvsala] La respuesta se cort\xF3 al agotar `maxOutputTokens`"+(n.response?.maxOutputTokens!=null?` (${n.response.maxOutputTokens})`:"")+", as\xED que no valida contra el contrato. NO se reintenta: con el mismo tope volver\xEDa a cortarse y ser\xEDa una llamada pagada para el mismo fallo. Sube `maxOutputTokens` o reduce lo que pide el contrato.");else if(!T.valid&&_.backend==="none"){i.retries=1,l.record("validation","repair-attempt",{errors:T.errors});let z=T.errors.slice(0,5).map(re=>`- ${re.path}: ${re.message}`).join(`
19
19
  `),H=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
20
20
 
21
21
  Previous reply:
@@ -24,8 +24,8 @@ ${w.text}
24
24
  Problems found:
25
25
  ${z}
26
26
 
27
- Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}];w=await this.llamarProveedor({model:n.model,messages:H,schema:E,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),i.actualLlm=2,i.actualInput+=w.usage.inputTokens,i.actualOutput+=w.usage.outputTokens,i.repairOutput+=w.usage.outputTokens,i.repairInput+=w.usage.inputTokens,i.sentInputLocal+=this.tokensFor(this.assemblePromptText(H),n);let N=fn(w.text);T=N.ok?Re(N.value,E):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},N.ok&&(C=N.value);}else k.ok&&(C=k.value);L=T.valid,l.record("validation",L?"valid":"invalid");}let v=this.now()-I,S=Ls(C),O={text:w.text,data:C,rendered:S,storedAtMs:this.now()};try{let k=L!==!1&&!M;if(k||l.record("cache-write",M?"skipped: tool-call turn (an action request must not be replayed from cache)":"skipped: response fails its output contract"),k&&o.allowExactCache&&s.exactCache!==!1){let T=this.config.exactCacheTtlMs??864e5,B=o.maxCacheAgeMs==null?T:Math.min(T,o.maxCacheAgeMs);await this.deps.exactCache.set(a,O,B);}k&&o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&await this.deps.semanticCache.store(r,O);}catch(k){l.record("cache-write","failed (non-fatal; answer already served)",{error:k instanceof Error?k.message:String(k)});}let A=this.finish(n,r,O,"miss",i,c,l,d,h,void 0,void 0,L,_.backend,v);return M&&(A.toolCalls=w.toolCalls),w.finishReason!==void 0&&(A.finishReason=w.finishReason),A}finish(e,n,r,o,s,i,c,l,a,u,f,p,d="none",m=0){let g=e.response?.schema,h=p===null?null:p??(g?Re(r.data,g).valid:true),b=this.buildReport(e,n,o,s,i,c,l,a,u,f,h,d,m);return {requestId:b.requestId,data:r.data,text:r.text,...r.rendered!==void 0?{rendered:r.rendered}:{},report:b}}buildReport(e,n,r,o,s,i,c,l,a,u,f,p,d){let m=o.estimateCost(s),g=i.elapsed();return {requestId:this.generateId(),model:e.model,calls:{baselineLlm:o.baselineLlm,actualLlm:o.actualLlm,avoidedLlm:o.avoidedLlm,baselineRetrieval:o.baselineRetrieval,actualRetrieval:o.actualRetrieval,baselineTools:o.baselineTools,actualTools:o.actualTools,retries:o.retries},tokens:{baselineInput:o.baselineInput,actualInput:o.actualInput,eliminatedInput:o.eliminatedInput,compressedInput:o.compressedInput,baselineOutput:o.publishedBaselineOutput,actualOutput:o.actualOutput,eliminatedOutput:o.eliminatedOutput,...o.providerCachedInput?{providerCachedInput:o.providerCachedInput}:{}},cache:{result:r,...u!==void 0?{confidence:u}:{},...a!==void 0?{ageMs:a}:{}},routing:{executionClass:c.executionClass,confidence:c.confidence,rounds:o.actualRetrieval,reason:c.reason},serialization:{chosen:l.chosen,candidateTokens:l.candidateTokens,instructionOverheadTokens:l.instructionOverheadTokens},...o.compressionReport?{compression:o.compressionReport}:{},constraints:{backend:p,schemaVersion:n.schemaVersion,...f===null?{}:{structurallyValid:f}},quality:{...r!=="miss"?{freshnessPassed:!kt(n).requiresFreshData}:{}},cost:m,latencyMs:{total:g,preprocessing:Math.max(0,g-d),provider:d},traces:i.all()}}async failOpenDirect(e,n){let r=new _e(this.now);r.record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",{error:n instanceof Error?n.message:String(n)});let o=new he,s=this.costModelFor(e.model),i;try{i=St(e);}catch{i={schemaVersion:e.response?.version??e.response?.contractId??"none"};}let c=e.response?.schema,l=this.now(),a=await this.config.provider.generate({model:e.model,messages:e.messages,...e.tools?.length?{tools:e.tools}:{},...c?{schema:c}:{},...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),u=this.now()-l;o.baselineLlm=1,o.actualLlm=1,o.actualInput=a.usage.inputTokens,o.actualOutput=a.usage.outputTokens,o.baselineInput=a.usage.inputTokens,o.baselineOutput=a.usage.outputTokens,a.usage.cachedInputTokens&&o.providerCached(a.usage.cachedInputTokens);let f=a.text,p=true,d=(a.toolCalls?.length??0)>0;if(d&&(p=null),c&&!d){let g=fn(a.text);p=g.ok?Re(g.value,c).valid:false,g.ok&&(f=g.value);}let m=this.buildReport(e,i,"miss",o,s,r,Pe(),Fe(),void 0,void 0,p,"none",u);return {requestId:m.requestId,data:f,text:a.text,...d?{toolCalls:a.toolCalls}:{},...a.finishReason!==void 0?{finishReason:a.finishReason}:{},report:m}}asCoalescedFollower(e,n,r,o){let s=new he;s.avoidCall(n,r);let i=s.estimateCost(o),c=this.generateId();return {...e,requestId:c,report:{...e.report,requestId:c,calls:{...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:s.baselineInput,actualInput:s.actualInput,eliminatedInput:s.eliminatedInput,compressedInput:s.compressedInput,baselineOutput:s.publishedBaselineOutput,actualOutput:s.actualOutput,eliminatedOutput:s.eliminatedOutput,...s.providerCachedInput?{providerCachedInput:s.providerCachedInput}:{}},cache:{result:"singleflight"},cost:i}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,r){let o=e.map(s=>s.content);r!==void 0&&o.push(JSON.stringify(r));for(let s of n??[])o.push(JSON.stringify({type:"function",function:{name:s.id,...s.description?{description:s.description}:{},parameters:s.parameters??{type:"object",properties:{}}}}));return o.join(`
28
- `)}tokensFor(e,n){return this.config.tokenizer.count(e,{...n.tokenizer?{tokenizer:n.tokenizer}:{},model:n.model})}estimatorEsExacto(e){let n=this.config.tokenizer;if(typeof n.resolve!="function")return false;try{return n.resolve({...e.tokenizer?{tokenizer:e.tokenizer}:{},model:e.model}).exact===!0}catch{return false}}entitled(e){return this.devOpen()?true:!!this.config.licenseGate&&this.config.licenseGate.isEntitled(e)}costModelFor(e){let n=this.config.costModels;if(n){let r=n[e];if(r)return r;let o=e.indexOf("/");if(o>=0){let s=n[e.slice(o+1)];if(s)return s}}return this.config.defaultCostModel?this.config.defaultCostModel:(this.illustrativePriceWarned||(this.illustrativePriceWarned=true,console.warn(`[bv-sala] no cost model configured for "${e}"; falling back to the ILLUSTRATIVE default price. Dollar figures will not match your bill. Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`)),Nr)}};function fn(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}function Ls(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function Pe(){return {executionClass:"NO_RETRIEVAL",confidence:1,reason:"n/a (short-circuited)",rounds:0}}function Fe(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,reason:"no structured payload"}}function dn(t,e="",n=null){if(t==null||typeof t!="object")return "";let r=t,o=[],s=e||"the value",i=m=>typeof r[m]=="number"?r[m]:null,c=i("maxLength"),l=i("minLength"),a=i("maxItems"),u=i("minItems"),f=i("maximum"),p=i("minimum");if(c!=null){let m=n!=null?Math.min(c,n):c;o.push(`${s}<=${m}ch`);}l!=null&&o.push(`${s}>=${l}ch`),a!=null&&o.push(`${s}<=${a} items`),u!=null&&o.push(`${s}>=${u} items`),f!=null&&o.push(`${s}<=${f}`),p!=null&&o.push(`${s}>=${p}`),typeof r.pattern=="string"&&o.push(`${s} matches /${r.pattern}/`);let d=r.properties;if(d&&typeof d=="object")for(let[m,g]of Object.entries(d)){let h=dn(g,e?`${e}.${m}`:m,n);h&&o.push(h);}if(r.items!==void 0){let m=dn(r.items,`${s} entries`,n);m&&o.push(m);}return o.join("; ")}function Vr(t){let e=t.response;return e?e.contractId??e.version??JSON.stringify(e.schema??{}).slice(0,200):""}function Bs(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.test(e.message))}function Ur(t,e){for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}var Ms=6*3600;function gl(t){t.licenseGate&&(console.warn("[bvsala] Se ignora el `licenseGate` inyectado: en el paquete publicado la licencia solo se acepta v\xEDa `licenseKey` verificado contra la clave de BiVelio."),t={...t,licenseGate:void 0});let n={...t,tokenizer:t.tokenizer??pn},r,o;if(t.licenseKey&&!t.licenseGate){let c=Mr;if(t.licenseServerUrl){let l=new we,a=p=>dt(p,c,{revocation:l,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??Ms}),u=a(t.licenseKey);n.licenseGate={isEntitled:p=>u.isEntitled(p),isActive:()=>u.isActive(),status:()=>u.status()};let f=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;r=new pt({url:f,publicKeyPem:c,snapshot:l,getRefreshAfter:()=>u.refreshAfter?.(),...t.now?{nowSeconds:()=>Math.floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.licensePollIntervalSeconds}:{},...t.licenseRevocation??{}}),r.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(o=new ht({url:`${t.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,serviceAccountKey:t.serviceAccountKey,publicKey:c,initialToken:t.licenseKey,revocados:l,onNewToken:p=>{u=a(p);},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),o.start());}else n.licenseGate=zr(t.licenseKey,c,t.now);}let s=new gt(n),i;if(t.serviceAccountKey&&t.metering?.enabled!==false){let c=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/usage`:void 0);if(c){i=new je({url:c,serviceAccountKey:t.serviceAccountKey,...t.metering?.orgId?{orgId:t.metering.orgId}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.metering?.maxBatch!=null?{maxBatch:t.metering.maxBatch}:{},...t.metering?.maxBuffer!=null?{maxBuffer:t.metering.maxBuffer}:{},...t.meteringFetch?{fetchImpl:t.meteringFetch}:t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.metering?.ci!=null?{ci:t.metering.ci}:{}});let l=t.metering?.ci??ln();if(t.metering?.seatId)i.setSeat(t.metering.seatId,l);else {let a=i;un(t.serviceAccountKey).then(u=>a.setSeat(u,l)).catch(()=>{});}i.start();}}return {generate:async c=>{let l=await s.generate(c);if(i)try{i.record(l.report);}catch{}return l},close:()=>{r?.stop(),o?.stop(),i?.stop();}}}var Sl="0.2.0";/*! Bundled license information:
27
+ Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}];w=await this.llamarProveedor({model:n.model,messages:H,schema:E,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),i.actualLlm=2,i.actualInput+=w.usage.inputTokens,i.actualOutput+=w.usage.outputTokens,i.repairOutput+=w.usage.outputTokens,i.repairInput+=w.usage.inputTokens,i.sentInputLocal+=this.tokensFor(this.assemblePromptText(H),n);let N=fn(w.text);T=N.ok?Ie(N.value,E):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},N.ok&&(A=N.value);}else k.ok&&(A=k.value);L=T.valid,l.record("validation",L?"valid":"invalid");}let v=this.now()-I,S=js(A),O={text:w.text,data:A,rendered:S,storedAtMs:this.now()};try{let k=L!==!1&&!M;if(k||l.record("cache-write",M?"skipped: tool-call turn (an action request must not be replayed from cache)":"skipped: response fails its output contract"),k&&o.allowExactCache&&s.exactCache!==!1){let T=this.config.exactCacheTtlMs??864e5,B=o.maxCacheAgeMs==null?T:Math.min(T,o.maxCacheAgeMs);await this.deps.exactCache.set(a,O,B);}k&&o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&await this.deps.semanticCache.store(r,O);}catch(k){l.record("cache-write","failed (non-fatal; answer already served)",{error:k instanceof Error?k.message:String(k)});}let C=this.finish(n,r,O,"miss",i,c,l,d,h,void 0,void 0,L,_.backend,v);return M&&(C.toolCalls=w.toolCalls),w.finishReason!==void 0&&(C.finishReason=w.finishReason),C}finish(e,n,r,o,s,i,c,l,a,u,f,p,d="none",m=0){let g=e.response?.schema,h=p===null?null:p??(g?Ie(r.data,g).valid:true),b=this.buildReport(e,n,o,s,i,c,l,a,u,f,h,d,m);return {requestId:b.requestId,data:r.data,text:r.text,...r.rendered!==void 0?{rendered:r.rendered}:{},report:b}}buildReport(e,n,r,o,s,i,c,l,a,u,f,p,d){let m=o.estimateCost(s),g=i.elapsed();return {requestId:this.generateId(),model:e.model,calls:{baselineLlm:o.baselineLlm,actualLlm:o.actualLlm,avoidedLlm:o.avoidedLlm,baselineRetrieval:o.baselineRetrieval,actualRetrieval:o.actualRetrieval,baselineTools:o.baselineTools,actualTools:o.actualTools,retries:o.retries},tokens:{baselineInput:o.baselineInput,actualInput:o.actualInput,eliminatedInput:o.eliminatedInput,compressedInput:o.compressedInput,baselineOutput:o.publishedBaselineOutput,actualOutput:o.actualOutput,eliminatedOutput:o.eliminatedOutput,...o.providerCachedInput?{providerCachedInput:o.providerCachedInput}:{}},cache:{result:r,...u!==void 0?{confidence:u}:{},...a!==void 0?{ageMs:a}:{}},routing:{executionClass:c.executionClass,confidence:c.confidence,rounds:o.actualRetrieval,reason:c.reason},serialization:{chosen:l.chosen,candidateTokens:l.candidateTokens,instructionOverheadTokens:l.instructionOverheadTokens},...o.compressionReport?{compression:o.compressionReport}:{},constraints:{backend:p,schemaVersion:n.schemaVersion,...f===null?{}:{structurallyValid:f}},quality:{...r!=="miss"?{freshnessPassed:!kt(n).requiresFreshData}:{}},cost:m,latencyMs:{total:g,preprocessing:Math.max(0,g-d),provider:d},traces:i.all()}}async failOpenDirect(e,n){let r=new _e(this.now);r.record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",{error:n instanceof Error?n.message:String(n)});let o=new ge,s=this.costModelFor(e.model),i;try{i=St(e);}catch{i={schemaVersion:e.response?.version??e.response?.contractId??"none"};}let c=e.response?.schema,l=this.now(),a=await this.config.provider.generate({model:e.model,messages:e.messages,...e.tools?.length?{tools:e.tools}:{},...c?{schema:c}:{},...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),u=this.now()-l;o.baselineLlm=1,o.actualLlm=1,o.actualInput=a.usage.inputTokens,o.actualOutput=a.usage.outputTokens,o.baselineInput=a.usage.inputTokens,o.baselineOutput=a.usage.outputTokens,a.usage.cachedInputTokens&&o.providerCached(a.usage.cachedInputTokens);let f=a.text,p=true,d=(a.toolCalls?.length??0)>0;if(d&&(p=null),c&&!d){let g=fn(a.text);p=g.ok?Ie(g.value,c).valid:false,g.ok&&(f=g.value);}let m=this.buildReport(e,i,"miss",o,s,r,Pe(),Fe(),void 0,void 0,p,"none",u);return {requestId:m.requestId,data:f,text:a.text,...d?{toolCalls:a.toolCalls}:{},...a.finishReason!==void 0?{finishReason:a.finishReason}:{},report:m}}asCoalescedFollower(e,n,r,o){let s=new ge;s.avoidCall(n,r);let i=s.estimateCost(o),c=this.generateId();return {...e,requestId:c,report:{...e.report,requestId:c,calls:{...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:s.baselineInput,actualInput:s.actualInput,eliminatedInput:s.eliminatedInput,compressedInput:s.compressedInput,baselineOutput:s.publishedBaselineOutput,actualOutput:s.actualOutput,eliminatedOutput:s.eliminatedOutput,...s.providerCachedInput?{providerCachedInput:s.providerCachedInput}:{}},cache:{result:"singleflight"},cost:i}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,r){let o=e.map(s=>s.content);r!==void 0&&o.push(JSON.stringify(r));for(let s of n??[])o.push(JSON.stringify({type:"function",function:{name:s.id,...s.description?{description:s.description}:{},parameters:s.parameters??{type:"object",properties:{}}}}));return o.join(`
28
+ `)}tokensFor(e,n){return this.config.tokenizer.count(e,{...n.tokenizer?{tokenizer:n.tokenizer}:{},model:n.model})}estimatorEsExacto(e){let n=this.config.tokenizer;if(typeof n.resolve!="function")return false;try{return n.resolve({...e.tokenizer?{tokenizer:e.tokenizer}:{},model:e.model}).exact===!0}catch{return false}}entitled(e){return this.devOpen()?true:!!this.config.licenseGate&&this.config.licenseGate.isEntitled(e)}costModelFor(e){let n=this.config.costModels;if(n){let r=n[e];if(r)return r;let o=e.indexOf("/");if(o>=0){let s=n[e.slice(o+1)];if(s)return s}}return this.config.defaultCostModel?this.config.defaultCostModel:(this.illustrativePriceWarned||(this.illustrativePriceWarned=true,console.warn(`[bv-sala] no cost model configured for "${e}"; falling back to the ILLUSTRATIVE default price. Dollar figures will not match your bill. Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`)),Vr)}};function fn(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}function js(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function Pe(){return {executionClass:"NO_RETRIEVAL",confidence:1,reason:"n/a (short-circuited)",rounds:0}}function Fe(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,reason:"no structured payload"}}function dn(t,e="",n=null){if(t==null||typeof t!="object")return "";let r=t,o=[],s=e||"the value",i=m=>typeof r[m]=="number"?r[m]:null,c=i("maxLength"),l=i("minLength"),a=i("maxItems"),u=i("minItems"),f=i("maximum"),p=i("minimum");if(c!=null){let m=n!=null?Math.min(c,n):c;o.push(`${s}<=${m}ch`);}l!=null&&o.push(`${s}>=${l}ch`),a!=null&&o.push(`${s}<=${a} items`),u!=null&&o.push(`${s}>=${u} items`),f!=null&&o.push(`${s}<=${f}`),p!=null&&o.push(`${s}>=${p}`),typeof r.pattern=="string"&&o.push(`${s} matches /${r.pattern}/`);let d=r.properties;if(d&&typeof d=="object")for(let[m,g]of Object.entries(d)){let h=dn(g,e?`${e}.${m}`:m,n);h&&o.push(h);}if(r.items!==void 0){let m=dn(r.items,`${s} entries`,n);m&&o.push(m);}return o.join("; ")}function Hr(t){let e=t.response;return e?e.contractId??e.version??JSON.stringify(e.schema??{}).slice(0,200):""}function Ps(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.test(e.message))}function Kr(t,e){for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}var Fs=6*3600;function kl(t){t.licenseGate&&(console.warn("[bvsala] Se ignora el `licenseGate` inyectado: en el paquete publicado la licencia solo se acepta v\xEDa `licenseKey` verificado contra la clave de BiVelio."),t={...t,licenseGate:void 0});let n={...t,tokenizer:t.tokenizer??pn},r,o;if(t.licenseKey&&!t.licenseGate){let c=Dr;if(t.licenseServerUrl){let l=new Se,a=p=>dt(p,c,{revocation:l,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??Fs}),u=a(t.licenseKey);n.licenseGate={isEntitled:p=>u.isEntitled(p),isActive:()=>u.isActive(),status:()=>u.status()};let f=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;r=new pt({url:f,publicKeyPem:c,snapshot:l,getRefreshAfter:()=>u.refreshAfter?.(),...t.now?{nowSeconds:()=>Math.floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.licensePollIntervalSeconds}:{},...t.licenseRevocation??{}}),r.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(o=new ht({url:`${t.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,serviceAccountKey:t.serviceAccountKey,publicKey:c,initialToken:t.licenseKey,revocados:l,onNewToken:p=>{u=a(p);},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),o.start());}else n.licenseGate=Nr(t.licenseKey,c,t.now);}let s=new gt(n),i;if(t.serviceAccountKey&&t.metering?.enabled!==false){let c=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/usage`:void 0);if(c){i=new je({url:c,serviceAccountKey:t.serviceAccountKey,...t.metering?.orgId?{orgId:t.metering.orgId}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.metering?.maxBatch!=null?{maxBatch:t.metering.maxBatch}:{},...t.metering?.maxBuffer!=null?{maxBuffer:t.metering.maxBuffer}:{},...t.meteringFetch?{fetchImpl:t.meteringFetch}:t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.metering?.ci!=null?{ci:t.metering.ci}:{}});let l=t.metering?.ci??ln();if(t.metering?.seatId)i.setSeat(t.metering.seatId,l);else {let a=i;un(t.serviceAccountKey).then(u=>a.setSeat(u,l)).catch(()=>{});}i.start();}}return {generate:async c=>{let l=await s.generate(c);if(i)try{i.record(l.report);}catch{}return l},close:()=>{r?.stop(),o?.stop(),i?.stop();}}}var _l="0.2.2";/*! Bundled license information:
29
29
 
30
30
  @noble/curves/utils.js:
31
31
  @noble/curves/abstract/modular.js:
@@ -33,4 +33,4 @@ Return ONLY the corrected JSON object. Keep the same content; fix only what is l
33
33
  @noble/curves/abstract/edwards.js:
34
34
  @noble/curves/ed25519.js:
35
35
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
36
- */export{Sl as BV_SALA_VERSION,Nr as DEFAULT_COST_MODEL,Mr as EMBEDDED_PUBLIC_KEY,vt as ExactTokenizer,$e as ExecutionRouter,qe as FormatSelector,xt as HeuristicEstimator,ze as InMemoryExactCache,wn as InMemorySemanticCache,le as LicenseError,qr as MODELOS_POR_CODIFICACION,At as MockProvider,zn as OpenAICompatibleProvider,Et as ResolverRegistry,pt as RevocationPoller,we as RevocationSnapshot,he as SavingsLedger,Ge as SchemaRegistry,Ne as Singleflight,Io as TOON_INSTRUCTION,yt as TokenizerRegistry,Ve as ToolSelector,_e as TraceCollector,je as UsageEmitter,go as adaptiveK,io as arithmeticResolver,gn as buildExactKey,bn as buildInflightKey,St as canonicalize,ys as computeNextDelay,to as cosine,Sn as createDefaultResolvers,Ns as createHandoff,ba as createMockProvider,gl as createSavingsLayer,Oo as createToonSerializer,Ln as csvSerializer,Rn as decodeToon,ho as dedupe,pn as defaultTokenizerRegistry,un as deriveSeatId,cn as deriveStatus,ln as detectCi,Ai as emptyState,Eo as encodeToon,lo as evalArithmetic,kt as evaluatePolicy,En as executeRetrievalPlan,zr as gateFromKey,me as heuristicEstimator,gs as isKeyset,Oe as isStrictCompatible,Tn as jsonCompactSerializer,so as keyTokensMatch,dt as liveGateFromKey,Li as mergeDelta,ua as noopCompressor,Wr as normalizeText,Bi as projectContext,na as providerNativeBackend,bt as randomId,Zs as registrarTokenizadorExacto,xo as renderState,Mn as resolveConstraintBackend,$r as resolveDependencies,uc as resolveLicense,ge as sha256,ca as shouldCompress,Ee as stableStringify,Cn as toonSerializer,Ke as uniformColumns,Re as validateAgainstSchema,an as verifyCompactSignature,ve as verifyLicenseToken,Fr as verifyRevocationList,la as withProtectedSpans};
36
+ */export{_l as BV_SALA_VERSION,Vr as DEFAULT_COST_MODEL,Dr as EMBEDDED_PUBLIC_KEY,vt as ExactTokenizer,$e as ExecutionRouter,qe as FormatSelector,xt as HeuristicEstimator,ze as InMemoryExactCache,Sn as InMemorySemanticCache,ue as LicenseError,Xs as MODELOS_POR_CODIFICACION,mn as MODELS_BY_ENCODING,Ct as MockProvider,Nn as OpenAICompatibleProvider,Et as ResolverRegistry,pt as RevocationPoller,Se as RevocationSnapshot,ge as SavingsLedger,Ge as SchemaRegistry,Ne as Singleflight,_o as TOON_INSTRUCTION,yt as TokenizerRegistry,Ve as ToolSelector,_e as TraceCollector,je as UsageEmitter,xo as adaptiveK,co as arithmeticResolver,bn as buildExactKey,xn as buildInflightKey,St as canonicalize,Ss as computeNextDelay,ro as cosine,kn as createDefaultResolvers,Hs as createHandoff,Sa as createMockProvider,kl as createSavingsLayer,Ao as createToonSerializer,Bn as csvSerializer,In as decodeToon,bo as dedupe,pn as defaultTokenizerRegistry,un as deriveSeatId,cn as deriveStatus,ln as detectCi,ji as emptyState,Ro as encodeToon,fo as evalArithmetic,kt as evaluatePolicy,Tn as executeRetrievalPlan,Nr as gateFromKey,he as heuristicEstimator,xs as isKeyset,Oe as isStrictCompatible,Rn as jsonCompactSerializer,ao as keyTokensMatch,dt as liveGateFromKey,Pi as mergeDelta,ha as noopCompressor,Qr as normalizeText,Fi as projectContext,aa as providerNativeBackend,bt as randomId,Zr as registerExactTokenizer,Qs as registrarTokenizadorExacto,vo as renderState,Dn as resolveConstraintBackend,Ur as resolveDependencies,hc as resolveLicense,be as sha256,pa as shouldCompress,Te as stableStringify,Cn as toonSerializer,Ke as uniformColumns,Ie as validateAgainstSchema,an as verifyCompactSignature,we as verifyLicenseToken,zr as verifyRevocationList,ma as withProtectedSpans};
package/package.json CHANGED
@@ -1,21 +1,7 @@
1
1
  {
2
2
  "name": "@bivelio/savings-layer",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "BV-SALA — a provider-neutral LLM execution optimizer. A decision layer in front of any LLM provider that, for every request, picks the cheapest execution that preserves required quality. Avoid the call, avoid retrieval, eliminate context, compress, constrain — with four separate ledgers of savings. Proprietary and confidential — property of BiVelio Inc.",
5
- "type": "module",
6
- "license": "SEE LICENSE IN LICENSE",
7
- "author": "BiVelio Inc.",
8
- "publishConfig": {
9
- "access": "public"
10
- },
11
- "homepage": "https://github.com/BiVelio/bivelio-savings-layer",
12
- "repository": {
13
- "type": "git",
14
- "url": "git+https://github.com/BiVelio/bivelio-savings-layer.git"
15
- },
16
- "bugs": {
17
- "url": "https://github.com/BiVelio/bivelio-savings-layer/issues"
18
- },
19
5
  "keywords": [
20
6
  "llm",
21
7
  "gateway",
@@ -30,6 +16,21 @@
30
16
  "token-accounting",
31
17
  "bivelio"
32
18
  ],
19
+ "homepage": "https://savings.bivelio.com",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://savings.bivelio.com"
23
+ },
24
+ "bugs": {
25
+ "email": "support@bivelio.com",
26
+ "url": "https://savings.bivelio.com"
27
+ },
28
+ "license": "SEE LICENSE IN LICENSE",
29
+ "author": "BiVelio Inc.",
30
+ "type": "module",
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
33
34
  "exports": {
34
35
  ".": {
35
36
  "types": "./dist/index.d.ts",