@bivelio/savings-layer 0.4.24 → 0.4.25

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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var xa="2026-09-25",jt={"gpt-4.1":{inputPer1k:.002,outputPer1k:.008,cachedInputPer1k:5e-4},"gpt-4.1-mini":{inputPer1k:4e-4,outputPer1k:.0016,cachedInputPer1k:1e-4},"gpt-4.1-nano":{inputPer1k:1e-4,outputPer1k:4e-4,
1
+ var Pr="2026-09-27",Nt={"gpt-4.1":{inputPer1k:.002,outputPer1k:.008,cachedInputPer1k:5e-4},"gpt-4.1-mini":{inputPer1k:4e-4,outputPer1k:.0016,cachedInputPer1k:1e-4},"gpt-4.1-nano":{inputPer1k:1e-4,outputPer1k:4e-4,
2
2
  cachedInputPer1k:25e-6},"gpt-4o":{inputPer1k:.0025,outputPer1k:.01,cachedInputPer1k:.00125},"gpt-4o-mini":{inputPer1k:15e-5,outputPer1k:6e-4,cachedInputPer1k:75e-6},"gpt-4-turbo":{inputPer1k:.01,outputPer1k:.03},
3
3
  "gpt-4":{inputPer1k:.03,outputPer1k:.06},"gpt-3.5-turbo":{inputPer1k:5e-4,outputPer1k:.0015},"gpt-5":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gpt-5-codex":{inputPer1k:.00125,outputPer1k:.01,
4
4
  cachedInputPer1k:125e-6},"gpt-5-mini":{inputPer1k:25e-5,outputPer1k:.002,cachedInputPer1k:25e-6},"gpt-5-nano":{inputPer1k:5e-5,outputPer1k:4e-4,cachedInputPer1k:5e-6},"gpt-5.1-codex":{inputPer1k:.00125,
@@ -6,344 +6,412 @@ outputPer1k:.01,cachedInputPer1k:125e-6},"gpt-5.1-codex-max":{inputPer1k:.00125,
6
6
  "gpt-5.1-thinking":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gpt-5.2":{inputPer1k:.00175,outputPer1k:.014,cachedInputPer1k:175e-6},"gpt-5.2-codex":{inputPer1k:.00175,outputPer1k:.014,
7
7
  cachedInputPer1k:175e-6},"gpt-5.3-codex":{inputPer1k:.00175,outputPer1k:.014,cachedInputPer1k:175e-6},"gpt-5.4":{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},"gpt-5.4-mini":{inputPer1k:75e-5,
8
8
  outputPer1k:.0045,cachedInputPer1k:75e-6},"gpt-5.4-nano":{inputPer1k:2e-4,outputPer1k:.00125,cachedInputPer1k:2e-5},"gpt-5.5":{inputPer1k:.005,outputPer1k:.03,cachedInputPer1k:5e-4},"gpt-5.6-luna":{inputPer1k:2e-4,
9
- outputPer1k:.0012,cachedInputPer1k:2e-5},"gpt-5.6-sol":{inputPer1k:.004,outputPer1k:.02,cachedInputPer1k:4e-4},"gpt-5.6-terra":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},o3:{inputPer1k:.002,
10
- outputPer1k:.008,cachedInputPer1k:5e-4},"o3-mini":{inputPer1k:.0011,outputPer1k:.0044,cachedInputPer1k:55e-5},"o3-pro":{inputPer1k:.02,outputPer1k:.08},"o4-mini":{inputPer1k:.0011,outputPer1k:.0044,cachedInputPer1k:275e-6},
9
+ outputPer1k:.0012,cachedInputPer1k:2e-5},"gpt-5.6-sol":{inputPer1k:.004,outputPer1k:.02,cachedInputPer1k:4e-4},"gpt-5.6-terra":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gpt-6-astra":{inputPer1k:.01,
10
+ outputPer1k:.05,cachedInputPer1k:.001},"gpt-6-sol":{inputPer1k:.002,outputPer1k:.01,cachedInputPer1k:2e-4},"gpt-6-luna":{inputPer1k:1e-4,outputPer1k:5e-4,cachedInputPer1k:1e-5},o3:{inputPer1k:.002,outputPer1k:.008,
11
+ cachedInputPer1k:5e-4},"o3-mini":{inputPer1k:.0011,outputPer1k:.0044,cachedInputPer1k:55e-5},"o3-pro":{inputPer1k:.02,outputPer1k:.08},"o4-mini":{inputPer1k:.0011,outputPer1k:.0044,cachedInputPer1k:275e-6},
11
12
  "claude-opus-4-5":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4-6":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4-7":{inputPer1k:.005,outputPer1k:.025,
12
- cachedInputPer1k:5e-4},"claude-opus-4-8":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-5":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4":{inputPer1k:.015,
13
- outputPer1k:.075,cachedInputPer1k:.0015},"claude-sonnet-4-5":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-4-6":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"clau\
14
- de-sonnet-5":{inputPer1k:.002,outputPer1k:.01,cachedInputPer1k:2e-4},"claude-fable-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-fable-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},
15
- "claude-mythos-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-sonnet-4":{inputPer1k:.003,outputPer1k:.015,
16
- cachedInputPer1k:3e-4},"claude-haiku-4-5":{inputPer1k:.001,outputPer1k:.005,cachedInputPer1k:1e-4},"claude-3-5-sonnet":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-3-5-haiku":{inputPer1k:8e-4,
17
- outputPer1k:.004,cachedInputPer1k:8e-5},"claude-3-opus":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"claude-3-haiku":{inputPer1k:25e-5,outputPer1k:.00125,cachedInputPer1k:3e-5},"gemini-3\
18
- .7-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,
13
+ cachedInputPer1k:5e-4},"claude-opus-4-8":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-5":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-5-5":{inputPer1k:.004,
14
+ outputPer1k:.02,cachedInputPer1k:2e-4},"claude-opus-4":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"claude-sonnet-4-5":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-so\
15
+ nnet-4-6":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-5":{inputPer1k:.002,outputPer1k:.01,cachedInputPer1k:2e-4},"claude-fable-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},
16
+ "claude-fable-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5":{inputPer1k:.01,outputPer1k:.05,
17
+ cachedInputPer1k:.001},"claude-sonnet-4":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-haiku-4-5":{inputPer1k:.001,outputPer1k:.005,cachedInputPer1k:1e-4},"claude-3-5-sonnet":{inputPer1k:.003,
18
+ outputPer1k:.015,cachedInputPer1k:3e-4},"claude-3-5-haiku":{inputPer1k:8e-4,outputPer1k:.004,cachedInputPer1k:8e-5},"claude-3-opus":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"claude-3-\
19
+ haiku":{inputPer1k:25e-5,outputPer1k:.00125,cachedInputPer1k:3e-5},"gemini-3.8-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.7-flash":{inputPer1k:75e-5,outputPer1k:.00375,
20
+ cachedInputPer1k:75e-6},"gemini-3.6-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.1-flash-lite":{inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:25e-6},"gemini-3-fl\
21
+ ash-preview":{inputPer1k:5e-4,outputPer1k:.003,cachedInputPer1k:5e-5},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,
19
22
  cachedInputPer1k:3e-5},"gemini-3.1-pro-preview":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{
20
- inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}};function Bt(t,e,n){if(!n)return;let r=t[n];if(r)return r;let o=n.lastIndexOf("/"),s=o>=0?n.slice(o+1):n,i=t[s];if(i)return i;for(let a of e){if(!s.
21
- startsWith(a))continue;let c=s.charAt(a.length);if(c!==""&&c!=="-"&&c!=="."&&c!=="_")continue;let u=s.slice(a.length+1);if(!(/^\d/.test(u)&&!/^\d{4}/.test(u)))return t[a]}}function $n(t){return Object.
22
- keys(t).sort((e,n)=>n.length-e.length)}var ka=["o3-deep-research","o4-mini-deep-research"],Nt={...jt,...Object.fromEntries(ka.map(t=>[t,null]))},To=$n(Nt);function Ft(t){return Bt(Nt,To,t)??void 0}var wa=Object.
23
- fromEntries(Object.keys(Nt).map(t=>[t,Nt[t]===null?null:t]));function Vn(t){return Bt(wa,To,t)??void 0}var Sa=/^\d{4}-?\d{2}-?\d{2}$/;function Un(t){let e=Vn(t);if(e===void 0)return;let n=t.lastIndexOf(
24
- "/"),r=n>=0?t.slice(n+1):t;if(!(e!==t&&e!==r&&!Sa.test(r.slice(e.length+1))))return jt[e]}var lt="0.4.24",zt="x-bvsala-version";var Ta=0;function dt(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++Ta,o=Date.now?Date.now():0;for(let s=0;s<
25
- 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]}\
26
- -${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var Bl=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function zl(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 qn=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.
27
- 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,
28
- Math.ceil(e.length/4))}},qe=new qn;var Hn=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=qe){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){
23
+ inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}},Jc={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},
24
+ Yc={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.7-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,
25
+ cachedInputPer1k:15e-5}}],"gemini-3.6-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},Zc=Object.fromEntries(Object.keys(Nt).map(t=>[t,[{...Jc[t],
26
+ precio:Nt[t]},...Yc[t]??[]]]));var Xc=864e13;function Ri(t){let e=t instanceof Date?t.getTime():t,n=typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=Xc?e:Date.now();return new Date(n).toISOString().slice(0,10)}function Ci(t,e){
27
+ for(let n of Zc[t]??[])if(!(n.vigenteDesde!==void 0&&e<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&e>=n.vigenteHasta))return n.precio}function _r(t,e,n){if(!n)return;let r=t[n];if(r)return r;let o=n.lastIndexOf("/"),i=o>=0?n.slice(o+1):n,s=t[i];if(s)return s;for(let a of e){if(!i.startsWith(a))continue;let u=i.charAt(a.length);if(u!==
28
+ ""&&u!=="-"&&u!=="."&&u!=="_")continue;let c=i.slice(a.length+1);if(!(/^\d/.test(c)&&!/^\d{4}/.test(c)))return t[a]}}function Dr(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var Qc=["o3-dee\
29
+ p-research","o4-mini-deep-research","gpt-5.5-pro","gpt-5.4-pro","gpt-5.2-pro","gpt-5-pro","gpt-5.5-cyber","gemini-3.8-flash-tts","gemini-3.8-flash-lite-tts","gemini-3.1-flash-lite-image"],Ir={...Nt,...Object.
30
+ fromEntries(Qc.map(t=>[t,null]))},eu=Dr(Ir);function mn(t,e){let n=ut(t);return n===void 0?void 0:Ci(n,Ri(e))}var tu=Object.fromEntries(Object.keys(Ir).map(t=>[t,Ir[t]===null?null:t]));function ut(t){
31
+ return _r(tu,eu,t)??void 0}var nu=/^\d{4}-?\d{2}-?\d{2}$/;function Le(t,e){let n=ut(t);if(n===void 0)return;let r=t.lastIndexOf("/"),o=r>=0?t.slice(r+1):t;if(!(n!==t&&n!==o&&!nu.test(o.slice(n.length+
32
+ 1))))return Ci(n,Ri(e))}var Se="0.4.25",hn="x-bvsala-version";var ru=0;function jt(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++ru,o=Date.now?Date.now():0;for(let i=0;i<
33
+ 16;i++)e[i]=(i<6?r>>>i*8:o>>>(i-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]}\
34
+ -${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var Kp=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function Jp(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 Or=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 i=o[0];if(/\s/.test(i)){let s=(o.
35
+ match(/\n/g)??[]).length;r+=s+Math.floor(Math.max(0,o.length-1)/2);}else /[A-Za-z]/.test(i)?r+=Math.max(1,Math.ceil(o.length/4)):/\d/.test(i)?r+=Math.max(1,Math.ceil(o.length/2)):r+=1;}return Math.max(r,
36
+ Math.ceil(e.length/4))}},lt=new Or;var Ar=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=lt){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){
29
37
  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.
30
- get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},Kn=new Hn;var Jn=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}},$t={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini",
31
- "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 Wn(t,e={}){let n=e.codificaciones??
32
- ["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 Jn(o,s)),r=true;for(let i of $t[o]??
33
- [])t.mapModel(i,o),t.mapModel(`openai/${i}`,o);}}return r}var Gl=$t,Yl=Wn;var Ro=2592e6,Co=.95,Io=8,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;cacheWriteInputTokens=0;cacheWritePremiumUsd=0;sentInputLocal=0;removedInputLocal=0;elididoLocal=0;estimatorExact=false;repairOutput=0;repairInput=0;callsWithoutUsage=0;discoveryInput=0;discoveryOutput=0;extraCostUsd=0;cascadeInput=0;cascadeOutput=0;cascadeAttempt(e,n){
34
- this.cascadeInput+=Math.max(0,e.inputTokens),this.cascadeOutput+=Math.max(0,e.outputTokens),this.extraCostUsd+=Math.max(0,e.inputTokens)/1e3*n.inputPer1k+Math.max(0,e.outputTokens)/1e3*n.outputPer1k;}cacheWritePremium(e,n,r){
35
- let o=Math.max(0,e);this.cacheWriteInputTokens+=o,this.cacheWritePremiumUsd+=o/1e3*r.inputPer1k*Math.max(0,n-1);}compressionReport=void 0;eliminate(e){this.eliminatedInput+=Math.max(0,e);}compress(e,n){
36
- this.compressedInput+=Math.max(0,e-n);}providerCached(e){this.providerCachedInput+=Math.max(0,e);}reference=null;referenceRejected=null;avoidCallByReference(e){this.avoidCall(e.creditedInputTokens,e.creditedOutputTokens),
38
+ get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},Mr=new Ar;var Lr=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}},gn={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini",
39
+ "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 Nr(t,e={}){let n=e.codificaciones??
40
+ ["o200k_base","cl100k_base"],r=false;for(let o of n){let i;try{i=await import(`gpt-tokenizer/encoding/${o}`);}catch{continue}if(typeof i.encode=="function"){t.register(new Lr(o,i)),r=true;for(let s of gn[o]??
41
+ [])t.mapModel(s,o),t.mapModel(`openai/${s}`,o);}}return r}var sf=gn,af=Nr;var Pi=2592e6,_i=.95,Di=8,dt=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;cacheWriteInputTokens=0;cacheWritePremiumUsd=0;providerCacheWritePremiumUsd=0;sentInputLocal=0;removedInputLocal=0;elididoLocal=0;estimatorExact=false;repairOutput=0;repairInput=0;callsWithoutUsage=0;discoveryInput=0;discoveryOutput=0;extraCostUsd=0;cascadeInput=0;cascadeOutput=0;cascadeAttempt(e,n,r=1){
42
+ this.cascadeInput+=Math.max(0,e.inputTokens),this.cascadeOutput+=Math.max(0,e.outputTokens);let o=Math.max(0,e.cacheWriteInputTokens??0);this.extraCostUsd+=Math.max(0,e.inputTokens)/1e3*n.inputPer1k+Math.
43
+ max(0,e.outputTokens)/1e3*n.outputPer1k+o/1e3*n.inputPer1k*Math.max(0,r-1);}cacheWritePremium(e,n,r){let o=Math.max(0,e);this.cacheWriteInputTokens+=o,this.cacheWritePremiumUsd+=o/1e3*r.inputPer1k*Math.
44
+ max(0,n-1);}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);}providerCacheWritePremium(e,n,r){
45
+ let o=Math.max(0,e);this.providerCacheWritePremiumUsd+=o/1e3*r.inputPer1k*Math.max(0,n-1);}reference=null;referenceRejected=null;avoidCallByReference(e){this.avoidCall(e.creditedInputTokens,e.creditedOutputTokens),
37
46
  this.reference=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.
38
47
  repairOutput-this.discoveryOutput):this.baselineOutput}estimateCost(e){let n=this.avoidedLlm===0,r="estimated";if(n)if(this.callsWithoutUsage>0)this.baselineInput=0,r="unmeasured";else if(this.actualInput>
39
- 0&&this.sentInputLocal>0){let m=this.actualInput/this.sentInputLocal,f=Math.max(0,this.actualInput-this.repairInput-this.discoveryInput);this.baselineInput=f+Math.round(m*this.removedInputLocal),r=this.
48
+ 0&&this.sentInputLocal>0){let m=this.actualInput/this.sentInputLocal,h=Math.max(0,this.actualInput-this.repairInput-this.discoveryInput);this.baselineInput=h+Math.round(m*this.removedInputLocal),r=this.
40
49
  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.
41
- repairOutput-this.discoveryOutput):this.baselineOutput,s=e.cachedInputPer1k??e.inputPer1k,i=Math.min(this.providerCachedInput,this.actualInput),a=m=>Math.max(0,m-i)/1e3*e.inputPer1k+i/1e3*s,c=n?null:this.
42
- reference,u=c?c.tierFactor*(this.baselineInput/1e3*c.cachedInputPer1k+this.baselineOutput/1e3*c.outputPer1k):a(this.baselineInput)+o/1e3*e.outputPer1k;c&&(r=u>0?"reference":"estimated");let l=a(this.actualInput)+
43
- this.actualOutput/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd,d=u===0?0:1-l/u;return {baselineEstimate:Eo(u),actual:Eo(l),netSavings:Ea(d),basis:r}}};function Eo(t){return Math.round(
44
- t*1e10)/1e10}function Ea(t){return Math.round(t*1e6)/1e6}var Ra=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
50
+ repairOutput-this.discoveryOutput):this.baselineOutput,i=e.cachedInputPer1k??e.inputPer1k,s=Math.min(this.providerCachedInput,this.actualInput),a=m=>Math.max(0,m-s)/1e3*e.inputPer1k+s/1e3*i,u=n?null:this.
51
+ reference,c=n?this.providerCacheWritePremiumUsd:0,l=u?u.tierFactor*(this.baselineInput/1e3*u.cachedInputPer1k+this.baselineOutput/1e3*u.outputPer1k):a(this.baselineInput)+o/1e3*e.outputPer1k+c;u&&(r=l>
52
+ 0?"reference":"estimated");let d=a(this.actualInput)+this.actualOutput/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd+c,f=l===0?0:1-d/l;return {baselineEstimate:Ii(l),actual:Ii(d),netSavings:ou(
53
+ f),basis:r}}};function Ii(t){return Math.round(t*1e10)/1e10}function ou(t){return Math.round(t*1e6)/1e6}var iu=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
45
54
  4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
46
55
  1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,
47
- 1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ca=new TextEncoder;function ie(t,e){return t>>>e|t<<32-e}function _o(t){let e=Ca.encode(t),n=e.length*
48
- 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(
49
- [1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let u=0;u<o.length;u+=64){for(let b=0;b<16;b++)a[b]=s.getUint32(u+b*4);for(let b=16;b<
50
- 64;b++){let x=a[b-15],y=a[b-2],k=ie(x,7)^ie(x,18)^x>>>3,E=ie(y,17)^ie(y,19)^y>>>10;a[b]=a[b-16]+k+a[b-7]+E|0;}let l=i[0],d=i[1],m=i[2],f=i[3],h=i[4],g=i[5],p=i[6],v=i[7];for(let b=0;b<64;b++){let x=ie(
51
- h,6)^ie(h,11)^ie(h,25),y=h&g^~h&p,k=v+x+y+Ra[b]+a[b]|0,E=ie(l,2)^ie(l,13)^ie(l,22),w=l&d^l&m^d&m,I=E+w|0;v=p,p=g,g=h,h=f+k|0,f=m,m=d,d=l,l=k+I|0;}i[0]=i[0]+l|0,i[1]=i[1]+d|0,i[2]=i[2]+m|0,i[3]=i[3]+f|0,
52
- i[4]=i[4]+h|0,i[5]=i[5]+g|0,i[6]=i[6]+p|0,i[7]=i[7]+v|0;}let c="";for(let u=0;u<8;u++)c+=(i[u]>>>0).toString(16).padStart(8,"0");return c}var Ia=/\s+/g,_a=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],Pa=/[¿?¡!;.,:'"·•]/g,Da=/([a-z])\p{M}+/gu,Oa=/(^|\s)\p{M}+/gu,
53
- Gn=/\p{L}/u;function X(t){return t>="0"&&t<="9"}function Vt(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,r]of _a)e=e.replace(n,r);return e=e.normalize("NFD").replace(Da,"$1").replace(Oa,"$1").
54
- normalize("NFC"),e=e.replace(Pa,(n,r,o)=>{let s=o[r-1]??"",i=o[r+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return X(s)&&X(i)?n:"";case "!":return X(s)?n:"";case ".":case ",":return X(s)&&X(i)||
55
- X(i)&&!X(s)&&!Gn.test(s)?n:"";case ":":return X(s)&&X(i)?n:"";case "'":case '"':return Gn.test(s)&&Gn.test(i)||X(s)||X(i)?n:"";default:return X(s)||X(i)?n:""}}),e.replace(Ia," ").trim()}function G(t){return _o(
56
- t)}function ae(t){return JSON.stringify(Yn(t))}function Yn(t){if(Array.isArray(t))return t.map(Yn);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=Yn(t[n]);return e}return t}
57
- function Zn(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function Xn(t){let e=t.context??{},n=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(
58
- `
59
- `),r=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${Vt(s.content)}`).join(`
60
- `),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:Zn(t.model),messages:t.messages,normalizedText:r,
61
- systemPromptHash:G(n),toolsetHash:G(ae(o)),structuredDataHash:t.structuredData!==void 0?G(ae(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.contractId??"none",contractId:t.response?.
56
+ 1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),su=new TextEncoder;function be(t,e){return t>>>e|t<<32-e}function Oi(t){let e=su.encode(t),n=e.length*
57
+ 8,r=(e.length+8>>6)+1,o=new Uint8Array(r*64);o.set(e),o[e.length]=128;let i=new DataView(o.buffer);i.setUint32(o.length-8,Math.floor(n/4294967296)),i.setUint32(o.length-4,n>>>0);let s=new Uint32Array(
58
+ [1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let c=0;c<o.length;c+=64){for(let g=0;g<16;g++)a[g]=i.getUint32(c+g*4);for(let g=16;g<
59
+ 64;g++){let y=a[g-15],k=a[g-2],x=be(y,7)^be(y,18)^y>>>3,T=be(k,17)^be(k,19)^k>>>10;a[g]=a[g-16]+x+a[g-7]+T|0;}let l=s[0],d=s[1],f=s[2],m=s[3],h=s[4],b=s[5],p=s[6],v=s[7];for(let g=0;g<64;g++){let y=be(
60
+ h,6)^be(h,11)^be(h,25),k=h&b^~h&p,x=v+y+k+iu[g]+a[g]|0,T=be(l,2)^be(l,13)^be(l,22),w=l&d^l&f^d&f,R=T+w|0;v=p,p=b,b=h,h=m+x|0,m=f,f=d,d=l,l=x+R|0;}s[0]=s[0]+l|0,s[1]=s[1]+d|0,s[2]=s[2]+f|0,s[3]=s[3]+m|0,
61
+ s[4]=s[4]+h|0,s[5]=s[5]+b|0,s[6]=s[6]+p|0,s[7]=s[7]+v|0;}let u="";for(let c=0;c<8;c++)u+=(s[c]>>>0).toString(16).padStart(8,"0");return u}var au=/\s+/g,cu=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],uu=/[¿?¡!;.,:'"·•]/g,lu=/([a-z])\p{M}+/gu,du=/(^|\s)\p{M}+/gu,
62
+ jr=/\p{L}/u;function se(t){return t>="0"&&t<="9"}function bn(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,r]of cu)e=e.replace(n,r);return e=e.normalize("NFD").replace(lu,"$1").replace(du,"$1").
63
+ normalize("NFC"),e=e.replace(uu,(n,r,o)=>{let i=o[r-1]??"",s=o[r+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return se(i)&&se(s)?n:"";case "!":return se(i)?n:"";case ".":case ",":return se(i)&&
64
+ se(s)||se(s)&&!se(i)&&!jr.test(i)?n:"";case ":":return se(i)&&se(s)?n:"";case "'":case '"':return jr.test(i)&&jr.test(s)||se(i)||se(s)?n:"";default:return se(i)||se(s)?n:""}}),e.replace(au," ").trim()}function Y(t){
65
+ return Oi(t)}function ve(t){return JSON.stringify($r(t))}function $r(t){if(Array.isArray(t))return t.map($r);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=$r(t[n]);return e}
66
+ return t}function Fr(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function Br(t){let e=t.context??{},n=t.messages.filter(i=>i.role==="system").map(i=>i.content).
67
+ join(`
68
+ `),r=t.messages.filter(i=>i.role!=="system").map(i=>`${i.role}:${bn(i.content)}`).join(`
69
+ `),o=(t.tools??[]).map(i=>({id:i.id,risk:i.risk,parameters:i.parameters??null})).sort((i,s)=>i.id.localeCompare(s.id));return {model:t.model,modelFamily:Fr(t.model),messages:t.messages,normalizedText:r,
70
+ systemPromptHash:Y(n),toolsetHash:Y(ve(o)),structuredDataHash:t.structuredData!==void 0?Y(ve(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.contractId??"none",contractId:t.response?.
62
71
  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",
63
- knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var Po="n2";function Qn(t,e={}){let n=e.servedModel??t.model,r=ae({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily:Zn(n),
72
+ knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var Ai="n2";function zr(t,e={}){let n=e.servedModel??t.model,r=ve({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily:Fr(n),
64
73
  model:n,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,
65
- freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${Po}:${G(r)}`}function Do(t,e={}){let n=ae({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,
74
+ freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${Ai}:${Y(r)}`}function Mi(t,e={}){let n=ve({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,
66
75
  model:e.servedModel??t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,data:t.structuredDataHash,temperature:t.temperature,seed:t.seed,deferrable:e.deferrable===
67
- true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:inflight:${Po}:${G(n)}`}var Aa=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|cot\
76
+ true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:inflight:${Ai}:${Y(n)}`}var pu=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|cot\
68
77
  izacion|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|\
69
78
  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\xE7\
70
79
  os|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|pog\
71
80
  oda","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\
72
- nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),Ma=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nu\
81
+ nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),fu=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nu\
73
82
  estro|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\
74
83
  |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|profil\
75
84
  o","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|zamow\
76
85
  ienie|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\
77
- 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 er(t){let e=[],n=t.normalizedText,
78
- r=(t.original.tools??[]).some(f=>f.risk==="write"||f.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||Aa.test(n),s=Ma.test(n),i=(t.temperature??0)>.3&&t.seed==null;r&&e.
79
- 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 a=o&&(t.freshnessBucket==
80
- null||t.freshnessBucket==="any"),c=t.freshnessBucket==="live",u=s&&t.principal==null,l=!i&&!a&&!c&&!u&&!r;r&&e.push("write/destructive tools \u2192 exact cache off (side effects must execute)"),c&&e.push(
81
- "freshnessBucket=live \u2192 exact cache off (answer must be current)"),a&&e.push("freshness-sensitive without a freshness bucket \u2192 exact cache off"),u&&e.push("personalized request with no princ\
82
- ipal (context.sessionId) \u2192 exact cache off");let d=!r&&!o&&!s&&!i&&t.freshnessBucket!=="day",m=!r&&!o&&!s&&!i&&t.freshnessBucket!=="day";return {allowExactCache:l,allowSemanticCache:d,allowElision:m,
83
- allowSingleflight:!r&&!u,allowCompression:true,requiresFreshData:o,hasSideEffects:r,isPersonalized:s,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var Ut=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.
84
- now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),Oo(n.value)):null}async set(e,n,r){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let o=this.store.keys().
85
- next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:Oo(n),expiresAtMs:r!=null?this.now()+r:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};function Oo(t){
86
- try{return structuredClone(t)}catch{return t}}var qt=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.
86
+ 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 vn(t){let e=[],n=t.normalizedText,
87
+ r=(t.original.tools??[]).some(g=>g.risk==="write"||g.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||pu.test(n),i=fu.test(n),s=(t.temperature??0)>.3&&t.seed==null,a=t.messages.
88
+ filter(g=>g.role==="user").length,u=(t.original?.tools?.length??0)>0,c=t.messages.some(g=>g.role==="tool"||g.role==="assistant"&&(g.toolCalls?.length??0)>0),l=u||c||a>1,d=t.original?.savings?.semanticCache===
89
+ "include-agentic";r&&e.push("write/destructive tools present"),o&&e.push("freshness-sensitive request"),i&&e.push("personalized/account-scoped request"),s&&e.push("stochastic sampling (temp>0.3, no se\
90
+ ed)");let f=o&&(t.freshnessBucket==null||t.freshnessBucket==="any"),m=t.freshnessBucket==="live",h=i&&t.principal==null,b=!s&&!f&&!m&&!h&&!r;r&&e.push("write/destructive tools \u2192 exact cache off (side \
91
+ effects must execute)"),m&&e.push("freshnessBucket=live \u2192 exact cache off (answer must be current)"),f&&e.push("freshness-sensitive without a freshness bucket \u2192 exact cache off"),h&&e.push("\
92
+ personalized request with no principal (context.sessionId) \u2192 exact cache off");let p=!r&&!o&&!i&&!s&&t.freshnessBucket!=="day"&&(!l||d);l&&!d?e.push('agentic request (tools, tool calls/results or\
93
+ more than one user turn) \u2192 semantic cache off by default (opt in with savings.semanticCache: "include-agentic")'):l&&d&&e.push('agentic request admitted to the semantic cache by savings.semantic\
94
+ Cache: "include-agentic" (write, freshness, personalization and sampling vetoes still apply)');let v=!r&&!o&&!i&&!s&&t.freshnessBucket!=="day";return {allowExactCache:b,allowSemanticCache:p,allowElision:v,
95
+ allowSingleflight:!r&&!h,allowCompression:true,requiresFreshData:o,hasSideEffects:r,isPersonalized:i,isAgentic:l,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var yn=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.
96
+ now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),Li(n.value)):null}async set(e,n,r){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let o=this.store.keys().
97
+ next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:Li(n),expiresAtMs:r!=null?this.now()+r:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};function Li(t){
98
+ try{return structuredClone(t)}catch{return t}}var kn=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.
87
99
  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);}}join(e){let n=this.inflight.get(e);return n&&this.waiters.set(e,(this.
88
- waiters.get(e)??1)+1),n}get activeKeys(){return this.inflight.size}};function La(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e}function Na(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(
89
- Boolean)}function ja(t){let e=new Array(256).fill(0),n=Na(t);if(n.length===0)return e;let r=new Map;for(let s=0;s<n.length;s++){let i=n[s];if(r.set(i,(r.get(i)??0)+1),s+1<n.length){let a=`${i}\0${n[s+
90
- 1]}`;r.set(a,(r.get(a)??0)+1);}}for(let[s,i]of r){let a=La(s),c=a%256,u=a>>>31===1?-1:1;e[c]+=u*(1+Math.log(i));}let o=0;for(let s of e)o+=s*s;if(o=Math.sqrt(o),o===0)return e;for(let s=0;s<e.length;s++)
91
- e[s]/=o;return e}function Ao(t){return ja(t)}var Mo=.72;function Ba(t,e){if(t.length!==e.length)return 0;let n=t.length,r=0,o=0,s=0;for(let i=0;i<n;i++){let a=t[i],c=e[i];r+=a*c,o+=a*a,s+=c*c;}return o===0||s===0?0:r/(Math.sqrt(o)*Math.sqrt(s))}var Fa=new Set(
100
+ waiters.get(e)??1)+1),n}get activeKeys(){return this.inflight.size}};function mu(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e}function hu(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(
101
+ Boolean)}function gu(t){let e=new Array(256).fill(0),n=hu(t);if(n.length===0)return e;let r=new Map;for(let i=0;i<n.length;i++){let s=n[i];if(r.set(s,(r.get(s)??0)+1),i+1<n.length){let a=`${s}\0${n[i+
102
+ 1]}`;r.set(a,(r.get(a)??0)+1);}}for(let[i,s]of r){let a=mu(i),u=a%256,c=a>>>31===1?-1:1;e[u]+=c*(1+Math.log(s));}let o=0;for(let i of e)o+=i*i;if(o=Math.sqrt(o),o===0)return e;for(let i=0;i<e.length;i++)
103
+ e[i]/=o;return e}function Ni(t){return gu(t)}var ji=.72;function bu(t,e){if(t.length!==e.length)return 0;let n=t.length,r=0,o=0,i=0;for(let s=0;s<n;s++){let a=t[s],u=e[s];r+=a*u,o+=a*a,i+=u*u;}return o===0||i===0?0:r/(Math.sqrt(o)*Math.sqrt(i))}var vu=new Set(
92
104
  ["no","not","never","none","cannot","cant","without","nor","nt","isnt","arent","wasnt","werent","dont","doesnt","didnt","wont","shouldnt","sin","nunca","jamas","jam\xE1s","tampoco","ni","ningun","ning\
93
- \xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),za=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what",
105
+ \xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),yu=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what",
94
106
  "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",
95
107
  "than","then","s","el","la","los","las","un","una","unos","unas","de","del","al","en","por","para","con","sin","sobre","y","o","u","es","son","era","eran","ser","estar","esta","este","esto","estos","e\
96
108
  stas","ese","esa","eso","que","cual","cuales","quien","quienes","como","cuando","donde","dame","dime","quiero","necesito","puedes","podrias","favor","porfavor","gracias","me","mi","mis","tu","tus","su",
97
109
  "sus","lo","le","se","hay","el","la","els","les","un","una","uns","unes","de","del","dels","al","als","en","per","amb","sense","sobre","i","o","es","son","era","eren","ser","estar","aquest","aquesta",
98
- "aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function pt(t){return (t.
99
- match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function tr(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)
100
- return false;n.set(r,o-1);}return true}function ft(t){return t.split(/\s+/).filter(Boolean)}function mt(t){return t.filter(e=>Fa.has(e.replace(/'/g,""))||e.endsWith("n't")).length}var $a=/^(system|user|assistant|tool):/;
101
- function Lo(t){return t.split(`
102
- `).map(e=>{let n=$a.exec(e);return n?{rol:n[1],texto:e.slice(n[0].length)}:{rol:"",texto:e}})}function Va(t,e){let n=Lo(t),r=Lo(e);if(n.length!==r.length)return false;for(let o=0;o<n.length;o++)if(n[o].rol!==
103
- r[o].rol||!Ua(n[o].texto,r[o].texto))return false;return true}function Ua(t,e){if(!tr(pt(t),pt(e)))return false;let n=ft(t),r=ft(e);if(mt(n)!==mt(r))return false;let o=u=>u.length>1&&!za.has(u)&&!/^\d/.test(u),s=new Set(
104
- n.filter(o)),i=new Set(r.filter(o));if(s.size===0&&i.size===0)return true;let a=0;for(let u of s)i.has(u)&&a++;let c=s.size+i.size-a;return c===0?true:a/c>=.75}var No=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;constructor(e={}){
105
- let n=e.embed==null;this.embed=e.embed??Ao,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??(n?Mo:.9),this.acceptThreshold=e.acceptThreshold??.85,this.ttlMs=e.ttlMs,this.maxRecords=
106
- 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||
107
- 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.
108
- 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;
109
- let s=Ba(n,o.embedding);if(s<this.similarityThreshold||!Va(e.normalizedText,o.query))continue;let i=this.verify?await this.verify(e.normalizedText,o.query):s,a=Math.min(s,i);a<this.acceptThreshold||(!r||
110
- a>r.confidence)&&(r={record:o,similarity:s,verifierScore:i,confidence:a,ageMs:this.now()-o.storedAtMs});}return r}async store(e,n){let r=await this.embed(e.normalizedText);this.records.length>=this.maxRecords&&
111
- 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.
112
- contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.structuredDataHash,locale:e.locale,schemaVersion:e.schemaVersion,safetyPolicyVersion:e.safetyPolicyVersion,storedAtMs:this.
113
- 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 nr=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}},
114
- qa={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]??Ha(t.normalizedText))?.trim();if(!n)return null;
115
- let r=Ja(n);return r===null||!Number.isFinite(r)?null:{text:Ka(r),data:{value:r},resolver:"arithmetic"}}};function Ha(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function Ka(t){
116
- return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function Ja(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],r=[],o={"+":1,"-":1,
117
- "*":2,"/":2,"%":2},s=a=>{let c=n.pop(),u=n.pop();if(u===void 0||c===void 0)return false;switch(a){case "+":return n.push(u+c),true;case "-":return n.push(u-c),true;case "*":return n.push(u*c),true;case "/":return c===
118
- 0?false:(n.push(u/c),true);case "%":return c===0?false:(n.push(u%c),true);default:return false}},i=true;for(let a of e)if(/^\d/.test(a))n.push(Number(a)),i=false;else if(a==="(")r.push(a),i=true;else if(a===")"){for(;r.length&&
119
- 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[a];)if(!s(r.pop()))return null;r.push(a),
120
- i=true;}for(;r.length;){let a=r.pop();if(a==="("||!s(a))return null}return n.length===1?n[0]:null}function jo(){return new nr().register(qa)}var Wa=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,Bo=/\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,
121
- Ga=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,Ht=class{classifier;maxRounds;constructor(e={}){this.
122
- 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.
123
- test(r))return be("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return be("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(Ga.test(r)&&!Bo.test(r))return be("NO_RETRIEVAL",
124
- .8,"self-contained transformation",0);let s=this.classifier?.classify(r);return s&&s.confidence>=.75?be(s.executionClass,s.confidence,"local classifier",Ya(s.executionClass,this.maxRounds)):n==="singl\
125
- e"?be("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?be("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):Wa.test(r)?be("MULTI_HOP_RETRIEVAL",.7,"comparison/compoun\
126
- d question",Math.min(this.maxRounds,2)):Bo.test(r)?be("SINGLE_RETRIEVAL",.65,"single factual lookup",1):be("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function Ya(t,e){return t===
127
- "SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function be(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var rr=class{constructor(e=512){this.cap=e;}cap;map=new Map;read(e){return this.map.get(e)}record(e,n,r){this.map.size>=this.cap&&!this.map.has(e)&&this.map.clear(),this.map.set(e,{ids:n,turns:r});}};function Za(t){
128
- return !t.some(e=>Array.isArray(e.intents)&&e.intents.length>0)&&!t.some(e=>typeof e.risk=="string")}var Kt=class{maxTools;scoreIntentMatch;learningTurns;freezer;constructor(e={}){this.maxTools=e.maxTools??
129
- 8,this.scoreIntentMatch=e.scoreIntentMatch??Xa,this.learningTurns=e.learningTurns??16,this.freezer=e.freezer??new rr;}passthrough(e){if(!e||e.length===0)return {tools:[],droppedIds:[],reason:"no tools p\
110
+ "aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function $t(t){return (t.
111
+ match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function Vr(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)
112
+ return false;n.set(r,o-1);}return true}function Ft(t){return t.split(/\s+/).filter(Boolean)}function Bt(t){return t.filter(e=>vu.has(e.replace(/'/g,""))||e.endsWith("n't")).length}var ku=/^(system|user|assistant|tool):/;
113
+ function $i(t){return t.split(`
114
+ `).map(e=>{let n=ku.exec(e);return n?{rol:n[1],texto:e.slice(n[0].length)}:{rol:"",texto:e}})}function xu(t,e){let n=$i(t),r=$i(e);if(n.length!==r.length)return false;for(let o=0;o<n.length;o++)if(n[o].rol!==
115
+ r[o].rol||!wu(n[o].texto,r[o].texto))return false;return true}function wu(t,e){if(!Vr($t(t),$t(e)))return false;let n=Ft(t),r=Ft(e);if(Bt(n)!==Bt(r))return false;let o=c=>c.length>1&&!yu.has(c)&&!/^\d/.test(c),i=new Set(
116
+ n.filter(o)),s=new Set(r.filter(o));if(i.size===0&&s.size===0)return true;let a=0;for(let c of i)s.has(c)&&a++;let u=i.size+s.size-a;return u===0?true:a/u>=.75}var Fi=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;embebedorPropio;constructor(e={}){
117
+ let n=e.embed==null;this.embebedorPropio=n,this.embed=e.embed??Ni,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??(n?ji:.9),this.acceptThreshold=e.acceptThreshold??.85,this.ttlMs=
118
+ 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){
119
+ 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!==
120
+ e.systemPromptHash||o.structuredDataHash!==e.structuredDataHash||o.locale!==e.locale||o.schemaVersion!==e.schemaVersion||o.safetyPolicyVersion!==e.safetyPolicyVersion||o.toolsetHash!==e.toolsetHash||o.
121
+ temperature!==e.temperature||o.seed!==e.seed||this.ttlMs!=null&&this.now()-o.storedAtMs>this.ttlMs)continue;let i=bu(n,o.embedding);if(i<this.similarityThreshold||!xu(e.normalizedText,o.query))continue;
122
+ let s=this.verify?await this.verify(e.normalizedText,o.query):i,a=Math.min(i,s);a<this.acceptThreshold||(!r||a>r.confidence)&&(r={record:o,similarity:i,verifierScore:s,confidence:a,ageMs:this.now()-o.
123
+ storedAtMs,similarityFloor:this.similarityThreshold,acceptFloor:this.acceptThreshold,embedder:this.embebedorPropio?"built_in":"custom",verifierRan:this.verify!=null});}return r}async store(e,n){let r=await this.
124
+ 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,
125
+ principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.structuredDataHash,locale:e.locale,schemaVersion:e.
126
+ schemaVersion,safetyPolicyVersion:e.safetyPolicyVersion,toolsetHash:e.toolsetHash,temperature:e.temperature,seed:e.seed,storedAtMs:this.now()});}invalidateEpoch(e){let n=0;for(let r=this.records.length-
127
+ 1;r>=0;r--)this.records[r].knowledgeEpoch===e&&(this.records.splice(r,1),n++);return n}get size(){return this.records.length}};var Ur=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}},
128
+ Su={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]??Tu(t.normalizedText))?.trim();if(!n)return null;
129
+ let r=Ru(n);return r===null||!Number.isFinite(r)?null:{text:Eu(r),data:{value:r},resolver:"arithmetic"}}};function Tu(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function Eu(t){
130
+ return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function Ru(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],r=[],o={"+":1,"-":1,
131
+ "*":2,"/":2,"%":2},i=a=>{let u=n.pop(),c=n.pop();if(c===void 0||u===void 0)return false;switch(a){case "+":return n.push(c+u),true;case "-":return n.push(c-u),true;case "*":return n.push(c*u),true;case "/":return u===
132
+ 0?false:(n.push(c/u),true);case "%":return u===0?false:(n.push(c%u),true);default:return false}},s=true;for(let a of e)if(/^\d/.test(a))n.push(Number(a)),s=false;else if(a==="(")r.push(a),s=true;else if(a===")"){for(;r.length&&
133
+ r[r.length-1]!=="(";)if(!i(r.pop()))return null;if(r.pop()!=="(")return null;s=false;}else {if(s)return null;for(;r.length&&r[r.length-1]!=="("&&o[r[r.length-1]]>=o[a];)if(!i(r.pop()))return null;r.push(a),
134
+ s=true;}for(;r.length;){let a=r.pop();if(a==="("||!i(a))return null}return n.length===1?n[0]:null}function Bi(){return new Ur().register(Su)}var Cu=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,zi=/\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,
135
+ Iu=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,xn=class{classifier;maxRounds;constructor(e={}){this.
136
+ classifier=e.classifier,this.maxRounds=e.maxRounds??2;}classify(e){let n=e.original.retrieval?.mode,r=e.normalizedText;if((e.original.tools??[]).some(s=>s.risk==="write"||s.risk==="destructive")&&/\b(create|update|delete|send|pay|book|cancel|crea|actualiza|elimina|env[ií]a|paga)\b/i.
137
+ test(r))return Te("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return Te("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(Iu.test(r)&&!zi.test(r))return Te("NO_RETRIEVAL",
138
+ .8,"self-contained transformation",0);let i=this.classifier?.classify(r);return i&&i.confidence>=.75?Te(i.executionClass,i.confidence,"local classifier",Pu(i.executionClass,this.maxRounds)):n==="singl\
139
+ e"?Te("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?Te("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):Cu.test(r)?Te("MULTI_HOP_RETRIEVAL",.7,"comparison/compoun\
140
+ d question",Math.min(this.maxRounds,2)):zi.test(r)?Te("SINGLE_RETRIEVAL",.65,"single factual lookup",1):Te("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function Pu(t,e){return t===
141
+ "SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function Te(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var qr=class{constructor(e=512){this.cap=e;}cap;map=new Map;read(e){return this.map.get(e)}record(e,n,r){this.map.size>=this.cap&&!this.map.has(e)&&this.map.clear(),this.map.set(e,{ids:n,turns:r});}};function _u(t){
142
+ return !t.some(e=>Array.isArray(e.intents)&&e.intents.length>0)&&!t.some(e=>typeof e.risk=="string")}var wn=class{maxTools;scoreIntentMatch;learningTurns;freezer;constructor(e={}){this.maxTools=e.maxTools??
143
+ 8,this.scoreIntentMatch=e.scoreIntentMatch??Du,this.learningTurns=e.learningTurns??16,this.freezer=e.freezer??new qr;}passthrough(e){if(!e||e.length===0)return {tools:[],droppedIds:[],reason:"no tools p\
130
144
  rovided",setIsStable:true};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}\
131
145
  , capped at maxTools=${this.maxTools}; risk gating is the caller's responsibility while routing is off)`,setIsStable:true}}select(e,n,r,o){if(!n||n.length===0)return {tools:[],droppedIds:[],reason:"no to\
132
- ols provided",setIsStable:true};if(Za(n)){let p=this.passthrough(n);return {...p,reason:`catalogue declares no \`intents\` and no \`risk\`: nothing to select on, passed through (${p.tools.length}/${n.length}\
133
- , capped at maxTools=${this.maxTools}). Declare ToolDescriptor.intents/risk to enable pruning`}}let s=r==="TOOL_ACTION",i=n.filter(p=>s||p.risk==="read"),a=p=>s&&p.risk!=="read",c=i.filter(p=>!a(p)),u=i.
134
- filter(p=>a(p)),l=u.map(p=>({tool:p,score:this.scoreIntentMatch(e,p)})).sort((p,v)=>v.score-p.score).map(p=>p.tool),d=c.map(p=>({tool:p,score:this.scoreIntentMatch(e,p)})).filter(p=>p.score>0).sort((p,v)=>v.
135
- score-p.score).map(p=>p.tool),f=[...l.slice(0,this.maxTools),...d.slice(0,Math.max(0,this.maxTools-u.length))].map(p=>({tool:p})).map(p=>p.tool).sort((p,v)=>p.id<v.id?-1:p.id>v.id?1:0);if(o!==void 0){
136
- let p=this.freezer.read(o),v=(p?.turns??0)+1;if(p&&v>this.learningTurns){let x=new Set(p.ids),y=n.filter(E=>x.has(E.id));this.freezer.record(o,p.ids,v);let k=new Set(y.map(E=>E.id));return {tools:y,droppedIds:n.
137
- filter(E=>!k.has(E.id)).map(E=>E.id),reason:`frozen tool set after ${this.learningTurns} turns (${y.length}/${n.length}): it no longer depends on this request's text, so the prefix cache survives`,setIsStable:true}}
138
- let b=[...new Set([...p?.ids??[],...f.map(x=>x.id)])].sort().slice(0,this.maxTools);this.freezer.record(o,b,v);}let h=new Set(f.map(p=>p.id)),g=n.filter(p=>!h.has(p.id)).map(p=>p.id);return {tools:f,droppedIds:g,
139
- reason:`selected ${f.length}/${n.length} by intent match (writes ${s?"allowed":"blocked"})`,setIsStable:g.length===0}}};function Xa(t,e){let n=Vt(t),r=0;for(let o of Array.isArray(e.intents)?e.intents:
140
- []){let s=Vt(o);s&&(n.includes(s)?r+=2:s.split(/\s+/).some(i=>i.length>3&&n.includes(i))&&(r+=1));}return r}function Qa(t){let e=new Set,n=[];for(let r of t){let o=r.hash??tc(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function ec(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((i,a)=>(a.score??
141
- 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 a=(i.score??0)/o;if(s.length<n||a>=.4&&s.length<e.maxDocuments)s.push(
142
- i);else break}return s}async function Fo(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};
143
- let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,r=[];for(let i=0;i<n;i++){let a=await e.retriever.retrieve(t.query,t.maxDocuments*2);r.push(...a);}let o=r.length;r=Qa(r),e.reranker&&
144
- (r=await e.reranker.rerank(t.query,r));let s=ec(r,{maxDocuments:t.maxDocuments});return {docs:s,rounds:n,retrievedCount:o,keptCount:s.length}}function tc(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function jd(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function Bd(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{
145
- ...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&sc(o)?Object.assign(n.userPreferences,
146
- o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let s=rc(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],
147
- oc(n,r);return n}function Fd(t){let e=t.rawTurns??3,n=[],r=nc(t.state);r&&n.push({role:"system",content:`Conversation state:
148
- ${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function nc(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`fa\
146
+ ols provided",setIsStable:true};if(_u(n)){let p=this.passthrough(n);return {...p,reason:`catalogue declares no \`intents\` and no \`risk\`: nothing to select on, passed through (${p.tools.length}/${n.length}\
147
+ , capped at maxTools=${this.maxTools}). Declare ToolDescriptor.intents/risk to enable pruning`}}let i=r==="TOOL_ACTION",s=n.filter(p=>i||p.risk==="read"),a=p=>i&&p.risk!=="read",u=s.filter(p=>!a(p)),c=s.
148
+ filter(p=>a(p)),l=c.map(p=>({tool:p,score:this.scoreIntentMatch(e,p)})).sort((p,v)=>v.score-p.score).map(p=>p.tool),d=u.map(p=>({tool:p,score:this.scoreIntentMatch(e,p)})).filter(p=>p.score>0).sort((p,v)=>v.
149
+ score-p.score).map(p=>p.tool),m=[...l.slice(0,this.maxTools),...d.slice(0,Math.max(0,this.maxTools-c.length))].map(p=>({tool:p})).map(p=>p.tool).sort((p,v)=>p.id<v.id?-1:p.id>v.id?1:0);if(o!==void 0){
150
+ let p=this.freezer.read(o),v=(p?.turns??0)+1;if(p&&v>this.learningTurns){let y=new Set(p.ids),k=n.filter(T=>y.has(T.id));this.freezer.record(o,p.ids,v);let x=new Set(k.map(T=>T.id));return {tools:k,droppedIds:n.
151
+ filter(T=>!x.has(T.id)).map(T=>T.id),reason:`frozen tool set after ${this.learningTurns} turns (${k.length}/${n.length}): it no longer depends on this request's text, so the prefix cache survives`,setIsStable:true}}
152
+ let g=[...new Set([...p?.ids??[],...m.map(y=>y.id)])].sort().slice(0,this.maxTools);this.freezer.record(o,g,v);}let h=new Set(m.map(p=>p.id)),b=n.filter(p=>!h.has(p.id)).map(p=>p.id);return {tools:m,droppedIds:b,
153
+ reason:`selected ${m.length}/${n.length} by intent match (writes ${i?"allowed":"blocked"})`,setIsStable:b.length===0}}};function Du(t,e){let n=bn(t),r=0;for(let o of Array.isArray(e.intents)?e.intents:
154
+ []){let i=bn(o);i&&(n.includes(i)?r+=2:i.split(/\s+/).some(s=>s.length>3&&n.includes(s))&&(r+=1));}return r}function Ou(t){let e=new Set,n=[];for(let r of t){let o=r.hash??Mu(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function Au(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((s,a)=>(a.score??
155
+ 0)-(s.score??0));if(r.length<=n)return r;let o=r[0]?.score??0;if(o<=0)return r.slice(0,e.maxDocuments);let i=[];for(let s of r){let a=(s.score??0)/o;if(i.length<n||a>=.4&&i.length<e.maxDocuments)i.push(
156
+ s);else break}return i}async function Vi(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};
157
+ let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,r=[];for(let s=0;s<n;s++){let a=await e.retriever.retrieve(t.query,t.maxDocuments*2);r.push(...a);}let o=r.length;r=Ou(r),e.reranker&&
158
+ (r=await e.reranker.rerank(t.query,r));let i=Au(r,{maxDocuments:t.maxDocuments});return {docs:i,rounds:n,retrievedCount:o,keptCount:i.length}}function Mu(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function Gf(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function Jf(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{
159
+ ...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&$u(o)?Object.assign(n.userPreferences,
160
+ o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let i=Nu(n,r);i?i.push(...o.map(String)):n.confirmedFacts[r]=o;}for(let r of e.remove??[])delete n.confirmedFacts[r],delete n.userPreferences[r],
161
+ ju(n,r);return n}function Yf(t){let e=t.rawTurns??3,n=[],r=Lu(t.state);r&&n.push({role:"system",content:`Conversation state:
162
+ ${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function Lu(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`fa\
149
163
  cts: ${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(
150
164
  "; ")}`),t.openItems.length&&e.push(`open: ${t.openItems.join("; ")}`),e.join(`
151
- `)}function rc(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 oc(t,e){
152
- for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function sc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var zo={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function $o(t,e={}){let n=e.delimiter??",",r=e.indent??" ",s=t.split(`
153
- `).filter(c=>c.trim().length>0).map(c=>({indent:ic(c,r),content:c.slice(Vo(c,r))}));if(s.length===0)return {};let i=s[0];if(i.indent===0){let c=i.content.match(/^\[(\d+)\]\{(.*)\}:\s*$/);if(c){let l=Ke(
154
- c[2],n),d=Number(c[1]),m=[];for(let f=0,h=1;f<d&&h<s.length;f++,h++){let g=s[h];if(g.indent!==1)break;let p=Ke(g.content,n),v={};l.forEach((b,x)=>{v[b]=ht(p[x]??"null");}),m.push(v);}return m}let u=i.content.
155
- match(/^\[(\d+)\]:\s*(.*)$/);if(u){let l=u[2];return Number(u[1])===0||l.trim()===""?[]:Ke(l,n).map(ht)}}let[a]=Uo(s,0,0,n);return a}function Vo(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}
156
- function ic(t,e){return Vo(t,e)/e.length}function Uo(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 a=ac(i.content,r);if(!a){s++;continue}let{key:c,
157
- kind:u}=a;if(u.type==="scalar")o[c]=u.value,s++;else if(u.type==="inlineArray")o[c]=u.values,s++;else if(u.type==="emptyArray")o[c]=[],s++;else if(u.type==="table"){let l=[];s++;for(let d=0;d<u.count&&
158
- s<t.length;d++,s++){let m=t[s];if(m.indent!==n+1)break;let f=Ke(m.content,r),h={};u.columns.forEach((g,p)=>{h[g]=ht(f[p]??"null");}),l.push(h);}o[c]=l;}else {let[l,d]=Uo(t,s+1,n+1,r);o[c]=l,s=d;}}return [o,
159
- s]}function ac(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:Jt(n[1]),kind:{type:"table",count:Number(n[2]),columns:Ke(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){
160
- let s=Number(r[2]),i=r[3];return s===0||i.trim()===""?{key:Jt(r[1]),kind:{type:"emptyArray"}}:{key:Jt(r[1]),kind:{type:"inlineArray",values:Ke(i,e).map(ht)}}}let o=t.match(/^([^:]+):\s*(.*)$/);if(o){let s=Jt(
161
- o[1]),i=o[2];return i===""?{key:s,kind:{type:"object"}}:{key:s,kind:{type:"scalar",value:ht(i)}}}return null}function Ke(t,e){let n=[],r="",o=false;for(let s=0;s<t.length;s++){let i=t[s];o?i==='"'?t[s+1]===
162
- '"'?(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 ht(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,
163
- '"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function Jt(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,
164
- '"'):e}function cc(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return ir(null,t,0,o,n,r),o.join(`
165
- `)}function ir(t,e,n,r,o,s){let i=s.repeat(n),a=t===null?"":`${lc(t)}`;if(Array.isArray(e)){uc(a,e,n,r,o,s);return}if(sr(e)){t!==null&&r.push(`${i}${a}:`);let c=t===null?n:n+1;for(let[u,l]of Object.entries(
166
- e))ir(u,l,c,r,o,s);return}r.push(`${i}${a}: ${Wt(e,o)}`);}function uc(t,e,n,r,o,s){let i=s.repeat(n),a=t===""?"":t;if(e.length===0){r.push(`${i}${a}[0]:`);return}if(e.every(or)){let d=e.map(m=>Wt(m,o)).
167
- join(o);r.push(`${i}${a}[${e.length}]: ${d}`);return}let c=Gt(e);if(c){r.push(`${i}${a}[${e.length}]{${c.join(o)}}:`);let d=s.repeat(n+1);for(let m of e){let f=c.map(h=>Wt(m[h],o)).join(o);r.push(`${d}${f}`);}
168
- return}r.push(`${i}${a}[${e.length}]:`);let u=n+1,l=s.repeat(u);for(let d of e)if(or(d))r.push(`${l}- ${Wt(d,o)}`);else {let m=[];ir(null,d,0,m,o,s);let[f,...h]=m;r.push(`${l}- ${f??""}`);for(let g of h)
169
- r.push(`${l}${s}${g}`);}}function Gt(t){if(t.length===0)return null;let e=t[0];if(!sr(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(!sr(
170
- o))return null;let s=Object.keys(o);if(s.slice().sort().join("\0")!==r)return null;for(let i of s)if(!or(o[i]))return null}return n}function lc(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:qo(t)}function Wt(t,e){
165
+ `)}function Nu(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 ju(t,e){
166
+ for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function $u(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ui={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function qi(t,e={}){let n=e.delimiter??",",r=e.indent??" ",i=t.split(`
167
+ `).filter(u=>u.trim().length>0).map(u=>({indent:Fu(u,r),content:u.slice(Hi(u,r))}));if(i.length===0)return {};let s=i[0];if(s.indent===0){let u=s.content.match(/^\[(\d+)\]\{(.*)\}:\s*$/);if(u){let l=pt(
168
+ u[2],n),d=Number(u[1]),f=[];for(let m=0,h=1;m<d&&h<i.length;m++,h++){let b=i[h];if(b.indent!==1)break;let p=pt(b.content,n),v={};l.forEach((g,y)=>{v[g]=zt(p[y]??"null");}),f.push(v);}return f}let c=s.content.
169
+ match(/^\[(\d+)\]:\s*(.*)$/);if(c){let l=c[2];return Number(c[1])===0||l.trim()===""?[]:pt(l,n).map(zt)}}let[a]=Wi(i,0,0,n);return a}function Hi(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}
170
+ function Fu(t,e){return Hi(t,e)/e.length}function Wi(t,e,n,r){let o={},i=e;for(;i<t.length;){let s=t[i];if(s.indent<n)break;if(s.indent>n){i++;continue}let a=Bu(s.content,r);if(!a){i++;continue}let{key:u,
171
+ kind:c}=a;if(c.type==="scalar")o[u]=c.value,i++;else if(c.type==="inlineArray")o[u]=c.values,i++;else if(c.type==="emptyArray")o[u]=[],i++;else if(c.type==="table"){let l=[];i++;for(let d=0;d<c.count&&
172
+ i<t.length;d++,i++){let f=t[i];if(f.indent!==n+1)break;let m=pt(f.content,r),h={};c.columns.forEach((b,p)=>{h[b]=zt(m[p]??"null");}),l.push(h);}o[u]=l;}else {let[l,d]=Wi(t,i+1,n+1,r);o[u]=l,i=d;}}return [o,
173
+ i]}function Bu(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:Sn(n[1]),kind:{type:"table",count:Number(n[2]),columns:pt(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){
174
+ let i=Number(r[2]),s=r[3];return i===0||s.trim()===""?{key:Sn(r[1]),kind:{type:"emptyArray"}}:{key:Sn(r[1]),kind:{type:"inlineArray",values:pt(s,e).map(zt)}}}let o=t.match(/^([^:]+):\s*(.*)$/);if(o){let i=Sn(
175
+ o[1]),s=o[2];return s===""?{key:i,kind:{type:"object"}}:{key:i,kind:{type:"scalar",value:zt(s)}}}return null}function pt(t,e){let n=[],r="",o=false;for(let i=0;i<t.length;i++){let s=t[i];o?s==='"'?t[i+1]===
176
+ '"'?(r+='"',i++):o=false:r+=s:s==='"'?o=true:s===e?(n.push(r),r=""):r+=s;}return n.push(r),n.map(i=>i.trim())}function zt(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,
177
+ '"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function Sn(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,
178
+ '"'):e}function zu(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return Kr(null,t,0,o,n,r),o.join(`
179
+ `)}function Kr(t,e,n,r,o,i){let s=i.repeat(n),a=t===null?"":`${Uu(t)}`;if(Array.isArray(e)){Vu(a,e,n,r,o,i);return}if(Wr(e)){t!==null&&r.push(`${s}${a}:`);let u=t===null?n:n+1;for(let[c,l]of Object.entries(
180
+ e))Kr(c,l,u,r,o,i);return}r.push(`${s}${a}: ${Tn(e,o)}`);}function Vu(t,e,n,r,o,i){let s=i.repeat(n),a=t===""?"":t;if(e.length===0){r.push(`${s}${a}[0]:`);return}if(e.every(Hr)){let d=e.map(f=>Tn(f,o)).
181
+ join(o);r.push(`${s}${a}[${e.length}]: ${d}`);return}let u=En(e);if(u){r.push(`${s}${a}[${e.length}]{${u.join(o)}}:`);let d=i.repeat(n+1);for(let f of e){let m=u.map(h=>Tn(f[h],o)).join(o);r.push(`${d}${m}`);}
182
+ return}r.push(`${s}${a}[${e.length}]:`);let c=n+1,l=i.repeat(c);for(let d of e)if(Hr(d))r.push(`${l}- ${Tn(d,o)}`);else {let f=[];Kr(null,d,0,f,o,i);let[m,...h]=f;r.push(`${l}- ${m??""}`);for(let b of h)
183
+ r.push(`${l}${i}${b}`);}}function En(t){if(t.length===0)return null;let e=t[0];if(!Wr(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(!Wr(
184
+ o))return null;let i=Object.keys(o);if(i.slice().sort().join("\0")!==r)return null;for(let s of i)if(!Hr(o[s]))return null}return n}function Uu(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:Ki(t)}function Tn(t,e){
171
185
  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(`
172
- `)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?qo(n):n}function qo(t){return `"${t.replace(/"/g,'""')}"`}function or(t){return t===null||typeof t=="string"||typeof t==
173
- "number"||typeof t=="boolean"}function sr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var dc="Data is the compact encoder: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; ea\
174
- ch 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 pc(t={}){return {format:"compact-rows",supports(){return true},
175
- encode(e){return cc(e,t)},instruction(){return dc},decode(e){return $o(e,t)}}}var Ho=pc();var Jo={format:"csv",supports(t){return Array.isArray(t)&&Gt(t)!==null},encode(t){let e=t,n=Gt(e),r=n.map(Ko).join(","),o=e.map(s=>n.map(i=>Ko(s[i])).join(","));return [r,...o].join(`
176
- `)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function Ko(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,
177
- '""')}"`:e}var Yt=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[zo,Ho,Jo],this.minSavingsTokens=e.minimumSavingsTokens??
178
- 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 u of this.serializers){if(!u.supports(
179
- e))continue;let l=u.encode(e);if(u.format!=="json-compact"&&!fc(u,l,e))continue;let d=u.instruction(e),m=this.tokenizer.count(l,r),f=d?this.tokenizer.count(d,r):0,h=this.qualityPenalty(n.model??"",u.format);
180
- o.push({format:u.format,encoded:l,instruction:d,payloadTokens:m,instructionTokens:f,penalty:h,total:m+f+h});}let s=o.find(u=>u.format==="json-compact"),i={};for(let u of o)i[u.format]=u.total;if(!s){let u=o[0];
181
- return u?Wo(u,i,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:i,instructionOverheadTokens:0,reason:"no serializer supported payload; defa\
182
- ulted to JSON"}}let a=s,c="json baseline (no challenger cleared thresholds)";for(let u of o){if(u.format==="json-compact")continue;let l=s.total-u.total,d=s.total===0?0:l/s.total;l>=this.minSavingsTokens&&
183
- d>=this.minSavingsRatio&&u.total<a.total&&(a=u,c=`${u.format} saved ${l} tokens (${(d*100).toFixed(1)}%) vs json`);}return Wo(a,i,c)}};function fc(t,e,n){if(!t.decode)return false;try{return ar(t.decode(e),
184
- n)}catch{return false}}function ar(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.
185
- length)return false;for(let i=0;i<t.length;i++)if(!ar(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.
186
- call(e,i)||!ar(t[i],e[i]))return false;return true}function Wo(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function ee(t,e,n="$"){let r=[];return cr(t,e,n,r),{valid:r.length===0,errors:r}}function mc(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
187
- string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function cr(t,e,n,r){switch(e.enum&&!e.enum.some(s=>yc(s,t))&&r.push({path:n,message:"value not in enum"}),
188
- e.type??mc(t)){case "object":hc(t,e,n,r);break;case "array":gc(t,e,n,r);break;case "string":bc(t,e,n,r);break;case "number":case "integer":vc(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,
189
- message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function hc(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,
190
- 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(
191
- 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&&
192
- cr(o[s],i,`${n}.${s}`,r);}function gc(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 maxIte\
193
- ms ${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)=>cr(o,e.items,`${n}[${s}]`,r));}function bc(t,e,n,r){if(typeof t!=
186
+ `)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?Ki(n):n}function Ki(t){return `"${t.replace(/"/g,'""')}"`}function Hr(t){return t===null||typeof t=="string"||typeof t==
187
+ "number"||typeof t=="boolean"}function Wr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var qu="Data is the compact encoder: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; ea\
188
+ ch 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 Hu(t={}){return {format:"compact-rows",supports(){return true},
189
+ encode(e){return zu(e,t)},instruction(){return qu},decode(e){return qi(e,t)}}}var Gi=Hu();var Yi={format:"csv",supports(t){return Array.isArray(t)&&En(t)!==null},encode(t){let e=t,n=En(e),r=n.map(Ji).join(","),o=e.map(i=>n.map(s=>Ji(i[s])).join(","));return [r,...o].join(`
190
+ `)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function Ji(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,
191
+ '""')}"`:e}var Rn=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[Ui,Gi,Yi],this.minSavingsTokens=e.minimumSavingsTokens??
192
+ 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 c of this.serializers){if(!c.supports(
193
+ e))continue;let l=c.encode(e);if(c.format!=="json-compact"&&!Wu(c,l,e))continue;let d=c.instruction(e),f=this.tokenizer.count(l,r),m=d?this.tokenizer.count(d,r):0,h=this.qualityPenalty(n.model??"",c.format);
194
+ o.push({format:c.format,encoded:l,instruction:d,payloadTokens:f,instructionTokens:m,penalty:h,total:f+m+h});}let i=o.find(c=>c.format==="json-compact"),s={};for(let c of o)s[c.format]=c.total;if(!i){let c=o[0];
195
+ return c?Zi(c,s,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:s,instructionOverheadTokens:0,reason:"no serializer supported payload; defa\
196
+ ulted to JSON"}}let a=i,u="json baseline (no challenger cleared thresholds)";for(let c of o){if(c.format==="json-compact")continue;let l=i.total-c.total,d=i.total===0?0:l/i.total;l>=this.minSavingsTokens&&
197
+ d>=this.minSavingsRatio&&c.total<a.total&&(a=c,u=`${c.format} saved ${l} tokens (${(d*100).toFixed(1)}%) vs json`);}return Zi(a,s,u)}};function Wu(t,e,n){if(!t.decode)return false;try{return Gr(t.decode(e),
198
+ n)}catch{return false}}function Gr(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.
199
+ length)return false;for(let s=0;s<t.length;s++)if(!Gr(t[s],e[s]))return false;return true}let o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)return false;for(let s of o)if(!Object.prototype.hasOwnProperty.
200
+ call(e,s)||!Gr(t[s],e[s]))return false;return true}function Zi(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function de(t,e,n="$"){let r=[];return Jr(t,e,n,r),{valid:r.length===0,errors:r}}function Ku(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
201
+ string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function Jr(t,e,n,r){switch(e.enum&&!e.enum.some(i=>Xu(i,t))&&r.push({path:n,message:"value not in enum"}),
202
+ e.type??Ku(t)){case "object":Gu(t,e,n,r);break;case "array":Ju(t,e,n,r);break;case "string":Yu(t,e,n,r);break;case "number":case "integer":Zu(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,
203
+ message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function Gu(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,
204
+ message:"expected object"});return}let o=t;for(let i of e.required??[])i in o||r.push({path:`${n}.${i}`,message:"missing required property"});if(e.additionalProperties===false&&e.properties){let i=new Set(
205
+ Object.keys(e.properties));for(let s of Object.keys(o))i.has(s)||r.push({path:`${n}.${s}`,message:"additional property not allowed"});}if(e.properties)for(let[i,s]of Object.entries(e.properties))i in o&&
206
+ Jr(o[i],s,`${n}.${i}`,r);}function Ju(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 maxIte\
207
+ ms ${e.maxItems}`}),e.minItems!=null&&t.length<e.minItems&&r.push({path:n,message:`array below minItems ${e.minItems}`}),e.items&&t.forEach((o,i)=>Jr(o,e.items,`${n}[${i}]`,r));}function Yu(t,e,n,r){if(typeof t!=
194
208
  "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.
195
209
  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 expres\
196
- sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function vc(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}
210
+ sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function Zu(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}
197
211
  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.
198
- minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function yc(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var Zt=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 ur(
199
- e,n,r),r}};function ur(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??{}))ur(o,`${e}\
200
- .${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&ur(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: s\
201
- tring should set maxLength or use an enum`);}function Go(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 valid\
202
- ate + repair"}}function cp(t=()=>true){return {id:"provider-native",supports:t}}function lr(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;
203
- return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function hp(t){return {async compress(e){let n=e.protectedSpans??[],r=e.text,o=[];n.forEach((c,u)=>{
204
- let l=`\0PROTECT_${u}\0`;o.push({token:l,span:c}),r=r.split(c.text).join(l);});let s=await t.compress({text:r,...e.targetRatio!=null?{targetRatio:e.targetRatio}:{}}),i=s.compressed,a=true;for(let{token:c,
205
- span:u}of o){if(!i.includes(c)){a=false;break}i=i.split(c).join(u.text);}return a?{...s,compressed:i,protectedSpans:n.length,fidelityPassed:true}:{compressed:e.text,originalTokens:s.originalTokens,compressedTokens:s.
206
- originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var gp={async compress(t){return {compressed:t.text,originalTokens:0,
207
- compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function Yo(t,e){let n=i=>i.toLowerCase().replace(/[.,;:!¡?¿()[\]{}"«»…]/g,
208
- " ").replace(/\s+/g," ").trim(),o=n((i=>{let a=new Set,c=[];for(let u of i.split(`
209
- `)){let l=u.trim();l&&a.has(l)||(l&&a.add(l),c.push(u));}return c.join(`
210
- `)})(t)),s=n(e);return !(!tr(pt(o),pt(s))||mt(ft(o))!==mt(ft(s)))}var Zo=new WeakSet;function Xo(t){Zo.add(t);}function dr(t){return typeof t=="object"&&t!==null&&Zo.has(t)}var pr=class{id="mock";options;constructor(e={}){this.options=e,Xo(this);}async generate(e,n){let r=e.messages.map(c=>c.content).join(`
211
- `),o=qe.count(r);if(e.tools&&e.tools.length>0){let c=JSON.stringify(e.tools.map(u=>({name:u.id,description:u.description,parameters:u.parameters??{}})));o+=qe.count(c);}let s,i=false;if(e.schema){let c=this.
212
- options.data??Xt(e.schema);s=JSON.stringify(c),i=true;}else s=this.options.answer??`mock-response(${e.model})`;let a=Math.min(e.maxOutputTokens??Number.MAX_SAFE_INTEGER,qe.count(s));return {text:s,usage:{
213
- inputTokens:o,outputTokens:a,...this.options.cachedInputTokens!=null?{cachedInputTokens:this.options.cachedInputTokens}:{}},structuredNatively:i}}async*generateStream(e){let n=await this.generate(e),r=Math.
214
- max(1,this.options.streamChunkChars??8);for(let o=0;o<n.text.length;o+=r)yield {type:"text",delta:n.text.slice(o,o+r)};yield {type:"done",response:n};}};function Xt(t){if(t.enum&&t.enum.length>0)return t.
215
- enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?Xt(r):null;}for(let[n,r]of Object.entries(t.properties??{}))n in e||(e[n]=Xt(r));return e}case "\
216
- array":return t.items?[Xt(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 Sp(t){return new pr(
217
- t)}var Qo={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},es=Math.min(...Object.values(Qo).filter(t=>t<1)),Qt="flex";function en(t){if(t==null||t==="")return null;let e=Qo[t];return e==
218
- null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}function ts(t,e){return !t||t.factor==null||!t.conDescuento||!Number.isFinite(e)||e<=0?null:e*(1-t.factor)}var xc="slo\
219
- wer and variable: OpenAI publishes no latency commitment for the flex tier. What IS documented is the failure shape \u2014 the default SDK timeout is 10 minutes and a request that exceeds it returns 408, a\
220
- nd when flex capacity is short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",kc="unchanged: this provider has no cheaper synchronous processing ti\
221
- er, so nothing was asked for and the request was scheduled exactly as it would have been.",ns="this provider has no cheaper synchronous processing tier, so the request was sent unchanged and nothing i\
222
- s credited; on this provider the deferred discount lives only in the asynchronous batch API, which is not a request/response call";function rs(t){return t==null||t===""?kc:t===Qt?xc:`unknown: this lay\
223
- er has no published latency statement for the "${t}" tier.`}var os=new Set;function F(t,e){os.has(t)||(os.add(t),console.warn(e));}function gt(t){return {esquemaEnFormatoNativo:false,esquemaEstricto:false,esquemaPorPrompt:false,piezasDelAdaptador:t}}var wc=2;function Je(t){return wc*(t??[]).filter(e=>e.parameters==null).length}var tn=new WeakMap;
224
- function We(t,e){return tn.set(t,e),t}function ss(t){return typeof t=="object"&&t!==null?tn.get(t):void 0}function is(t,e){let n=tn.get(t);return n&&tn.set(e,n),e}var fr=class{decoder;resto="";crPendiente=false;alPrincipio=true;datos="";evento="";ultimoId;push(e){let n=typeof e=="string"?e:(this.decoder??=new TextDecoder("utf-8")).decode(e,{stream:true});return this.procesar(
212
+ minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function Xu(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var Cn=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 Yr(
213
+ e,n,r),r}};function Yr(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??{}))Yr(o,`${e}\
214
+ .${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&Yr(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: s\
215
+ tring should set maxLength or use an enum`);}function Xi(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 valid\
216
+ ate + repair"}}function ym(t=()=>true){return {id:"provider-native",supports:t}}function Zr(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;
217
+ return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function Rm(t){return {async compress(e){let n=e.protectedSpans??[],r=e.text,o=[];n.forEach((u,c)=>{
218
+ let l=`\0PROTECT_${c}\0`;o.push({token:l,span:u}),r=r.split(u.text).join(l);});let i=await t.compress({text:r,...e.targetRatio!=null?{targetRatio:e.targetRatio}:{}}),s=i.compressed,a=true;for(let{token:u,
219
+ span:c}of o){if(!s.includes(u)){a=false;break}s=s.split(u).join(c.text);}return a?{...i,compressed:s,protectedSpans:n.length,fidelityPassed:true}:{compressed:e.text,originalTokens:i.originalTokens,compressedTokens:i.
220
+ originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var Cm={async compress(t){return {compressed:t.text,originalTokens:0,
221
+ compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function Qi(t,e){let n=s=>s.toLowerCase().replace(/[.,;:!¡?¿()[\]{}"«»…]/g,
222
+ " ").replace(/\s+/g," ").trim(),o=n((s=>{let a=new Set,u=[];for(let c of s.split(`
223
+ `)){let l=c.trim();l&&a.has(l)||(l&&a.add(l),u.push(c));}return u.join(`
224
+ `)})(t)),i=n(e);return !(!Vr($t(o),$t(i))||Bt(Ft(o))!==Bt(Ft(i)))}var es=new WeakSet;function ts(t){es.add(t);}function Xr(t){return typeof t=="object"&&t!==null&&es.has(t)}var Qr=class{id="mock";options;constructor(e={}){this.options=e,ts(this);}async generate(e,n){let r=e.messages.map(u=>u.content).join(`
225
+ `),o=lt.count(r);if(e.tools&&e.tools.length>0){let u=JSON.stringify(e.tools.map(c=>({name:c.id,description:c.description,parameters:c.parameters??{}})));o+=lt.count(u);}let i,s=false;if(e.schema){let u=this.
226
+ options.data??In(e.schema);i=JSON.stringify(u),s=true;}else i=this.options.answer??`mock-response(${e.model})`;let a=Math.min(e.maxOutputTokens??Number.MAX_SAFE_INTEGER,lt.count(i));return {text:i,usage:{
227
+ inputTokens:o,outputTokens:a,...this.options.cachedInputTokens!=null?{cachedInputTokens:this.options.cachedInputTokens}:{}},structuredNatively:s}}async*generateStream(e){let n=await this.generate(e),r=Math.
228
+ max(1,this.options.streamChunkChars??8);for(let o=0;o<n.text.length;o+=r)yield {type:"text",delta:n.text.slice(o,o+r)};yield {type:"done",response:n};}};function In(t){if(t.enum&&t.enum.length>0)return t.
229
+ enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?In(r):null;}for(let[n,r]of Object.entries(t.properties??{}))n in e||(e[n]=In(r));return e}case "\
230
+ array":return t.items?[In(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 Mm(t){return new Qr(
231
+ t)}function ns(t){let e=t.toLowerCase(),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e}function rs(t){let e=/^gpt-(\d+)(?:\.(\d+))?(?![\d.])/.exec(t);if(!e)return false;let n=Number(e[1]),r=e[2]===void 0?0:
232
+ Number(e[2]);return n>5||n===5&&r>=6}function Ye(t){let e=ns(t);return e.startsWith("gpt-")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?rs(e)?1.25:1:e.startsWith("gemini")?1:1.25}function Vt(t){
233
+ return rs(ns(t))?1.25:1}var Qu="https://developers.openai.com/api/docs/pricing",el="https://ai.google.dev/gemini-api/docs/pricing",os="2026-09-27",ae=t=>({...t,fuente:Qu,consultado:os}),ft=t=>({...t,fuente:el,consultado:os}),
234
+ tl={openai:{flex:{"gpt-5":ae({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mini":ae({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":ae({inputPer1k:25e-6,
235
+ cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":ae({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),"gpt-5.4":ae({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{
236
+ inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),"gpt-5.4-mini":ae({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),
237
+ "gpt-5.4-nano":ae({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":ae({inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.015,largo:{estandar:{inputPer1k:.01,cachedInputPer1k:.001,
238
+ outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.6-luna":ae({inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,
239
+ cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,outputPer1k:9e-4}}}),"gpt-5.6-sol":ae({inputPer1k:.002,cachedInputPer1k:2e-4,
240
+ cacheWritePer1k:.0025,outputPer1k:.01,largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},
241
+ vigenteHasta:"2026-11-21"}),"gpt-5.6-terra":ae({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,
242
+ outputPer1k:.018},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),o3:ae({inputPer1k:.001,cachedInputPer1k:25e-5,outputPer1k:.004}),"o4-mini":ae({inputPer1k:55e-5,
243
+ cachedInputPer1k:138e-6,outputPer1k:.0022})}},google:{flex:{"gemini-3.7-flash":ft({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.5-flash":ft({inputPer1k:75e-5,
244
+ outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":ft({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":ft({inputPer1k:.001,outputPer1k:.006,cachedInputPer1k:2e-4,
245
+ largo:{estandar:{inputPer1k:.004,outputPer1k:.018,cachedInputPer1k:4e-4},tier:{inputPer1k:.002,outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":ft({inputPer1k:625e-6,outputPer1k:.005,cachedInputPer1k:125e-6,
246
+ largo:{estandar:{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},tier:{inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-flash":ft({inputPer1k:15e-5,outputPer1k:.00125,
247
+ cachedInputPer1k:3e-5})}}};function Ne(t){let e=t.lastIndexOf("/");return e>=0?t.slice(e+1):t}function Pn(t){let e=t.toLowerCase(),n=e.indexOf("/"),r=n>0?e.slice(0,n):"",o=Ne(e);return r==="openai"||r===
248
+ "azure-openai"?"openai":r==="google"||r==="google-vertex"?"google":/^(gpt-|o[1-9](-|$))/.test(o)?"openai":o.startsWith("gemini")?"google":null}function nl(t){return Date.parse(`${t}T23:59:59.999Z`)}function _n(t,e,n,r=Date.
249
+ now()){if(Le(n)===void 0)return;let o=ut(n);if(o===void 0)return;let i=tl[t]?.[e],s=i?i[o]:void 0;if(s&&!(s.vigenteHasta&&r>nl(s.vigenteHasta)))return s}function Dn(t){let e=Le(t);if(e)return {...e,cacheWritePer1k:e.
250
+ inputPer1k*Ye(Ne(t))}}var is={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},ss=Math.min(...Object.values(is).filter(t=>t<1)),mt="flex";function eo(t){if(t==null||t==="")return null;let e=is[t];return e==
251
+ null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}var On=1e10;function to(t){let e=Math.floor(t*On)/On;return e>t&&(e=(Math.floor(t*On)-1)/On),e<=0?0:e}var An=t=>typeof t==
252
+ "number"&&Number.isFinite(t);function as(t){let e=eo(t.tierServido);if(!e)return {ok:false,motivo:"no-served-tier"};if(e.factor==null)return {ok:false,motivo:"unknown-tier"};if(!e.conDescuento)return {ok:false,motivo:"\
253
+ standard-rate-tier"};let n=t.uso;if(n.complete===false||!An(n.inputTokens)||!An(n.outputTokens)||n.cachedInputTokens!=null&&!An(n.cachedInputTokens)||n.cacheWriteInputTokens!=null&&!An(n.cacheWriteInputTokens))
254
+ return {ok:false,motivo:"incomplete-usage"};let r=Dn(t.modelo);if(!r)return {ok:false,motivo:"no-standard-price"};let o=t.origen??Pn(t.modelo),i=o?_n(o,e.servido,t.modelo,t.ahoraMs):void 0;if(!i)return {ok:false,
255
+ motivo:"no-tier-price"};let s=Math.max(0,n.inputTokens),a=Ye(Ne(t.modelo)),u=n.cachedInputTokens!=null,c=a<=1||n.cacheWriteInputTokens!=null,l=u?Math.min(Math.max(0,n.cachedInputTokens??0),s):0,d=a>1&&
256
+ c?Math.min(Math.max(0,n.cacheWriteInputTokens??0),s-l):0,f=s-l-d,m=Math.max(0,n.outputTokens),h={input:r.inputPer1k,"cached input":r.cachedInputPer1k??r.inputPer1k,"cache write":r.cacheWritePer1k,output:r.
257
+ outputPer1k},b={input:i.inputPer1k,"cached input":i.cachedInputPer1k,"cache write":i.cacheWritePer1k,output:i.outputPer1k},p=[{tokens:f,posibles:["input",...u?[]:["cached input"],...c?[]:["cache write"]]},
258
+ {tokens:l,posibles:["cached input"]},{tokens:d,posibles:["cache write"]},{tokens:m,posibles:["output"]}],v=f>0&&p[0].posibles.length>1,g=t.precioDelCliente,y=g?{input:g.inputPer1k,"cached input":g.cachedInputPer1k??
259
+ g.inputPer1k,"cache write":g.inputPer1k*a,output:g.outputPer1k}:void 0,k=(L,$)=>{let B=$?y[L]:h[L],z=b[L];return z===void 0?{std:B,aplicado:B}:$?{std:B,aplicado:h[L]>0?B*(z/h[L]):B}:{std:B,aplicado:z}},
260
+ x=new Set,T=L=>{let $=0,B=0;for(let z of p){if(z.tokens<=0)continue;let Z=z.posibles[0],I=k(Z,L);for(let ne of z.posibles.slice(1)){let De=k(ne,L);De.std-De.aplicado<I.std-I.aplicado&&(Z=ne,I=De);}b[Z]===
261
+ void 0&&z.posibles.length===1&&x.add(Z),$+=z.tokens/1e3*I.std,B+=z.tokens/1e3*I.aplicado;}return {std:$,aplicado:B}},w=T(false),R=w.std-w.aplicado,D=w.std,O=w.aplicado,_=R,S=false;if(g){let L=T(true);D=L.std;let $=L.
262
+ std-L.aplicado;S=$>R,_=Math.min($,R),O=S?L.std-_:L.aplicado;}if(!(_>0))return {ok:false,motivo:"no-difference"};let C=to(_);if(C<=0)return {ok:false,motivo:"no-difference"};let P=[];if(t.origen===null?P.push("\
263
+ the endpoint is not the provider's own API as attested by this package's adapter, so the rate cards it bills cannot be confirmed"):t.tierLeidoDe!=="cuerpo"&&P.push("the served tier was read from a res\
264
+ ponse header whose values the provider does not document"),g&&P.push("priced from your costModels: your standard rate times the published tier-to-standard ratio"+(S?", capped at the difference between\
265
+ the two published rate cards":"")),v){let L=[...u?[]:["read from"],...c?[]:["written to"]].join(" or ");P.push(`the provider's usage did not say how many input tokens were ${L} its prompt cache, so t\
266
+ hose tokens are priced at the smallest per-token difference they could have had`);}x.size>0&&P.push(`the provider publishes no ${[...x].join(" or ")} price for this tier, so those tokens add nothing`);
267
+ let A=P.length===0;return {ok:true,importe:C,basis:A?"measured":"estimated",costeEstandar:D,costeAplicado:O,factorEfectivo:O/D,motivoBasis:A?`the provider's own usage for this call at two published rate \
268
+ cards (${i.fuente}, checked ${i.consultado}), with the served tier read back from the provider's official API`:`estimated: ${P.join("; ")}`,consultado:i.consultado}}var rl="slower and variable: OpenAI\
269
+ publishes no latency commitment for the flex tier. What IS documented is the failure shape \u2014 the default SDK timeout is 10 minutes and a request that exceeds it returns 408, and when flex capacity is\
270
+ short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",ol='slower and variable: Google targets minutes for the Flex tier ("Minutes (1\u201315 min target)\
271
+ ", https://ai.google.dev/gemini-api/docs/flex-inference) and treats it as sheddable. When Flex capacity is unavailable the request fails with 503 or 429 and is never upgraded to the Standard tier on t\
272
+ he server side. Do not put a deferrable request on a user-facing path.',il="slower and variable, and unknown here: this endpoint is not attested as OpenAI's or Google's own API, so this layer has no p\
273
+ ublished latency statement for it. On those two providers a flex request without capacity fails (429, or 503 on Google) instead of waiting; expect that failure shape. Do not put a deferrable request o\
274
+ n a user-facing path.",sl="unchanged: this provider has no cheaper synchronous processing tier, so nothing was asked for and the request was scheduled exactly as it would have been.",cs="this provider\
275
+ has no cheaper synchronous processing tier, so the request was sent unchanged and nothing is credited; on this provider the deferred discount lives only in the asynchronous batch API, which is not a \
276
+ request/response call";function us(t,e=null){return t==null||t===""?sl:t===mt?e==="openai"?rl:e==="google"?ol:il:`unknown: this layer has no published latency statement for the "${t}" tier. A cheaper \
277
+ tier without capacity usually fails (429 or 503) rather than waiting; do not put a deferrable request on a user-facing path.`}var ls=1024;function Ut(t,e){return e==="openai"&&Pn(Ne(t))==="openai"&&Ye(Ne(t))>1}function ds(t){let e=Le(t);if(!e||!(e.inputPer1k>0))return null;let n=(e.cachedInputPer1k??e.inputPer1k)/e.inputPer1k;
278
+ return {minimumCacheTokens:ls,cacheReadMultiplier:n,cacheWriteMultiplier:Ye(Ne(t))}}function ps(t){let e=t.consultado??Pr,n=Math.max(0,t.uso.inputTokens),r=Math.min(Math.max(0,t.uso.cachedInputTokens??
279
+ 0),n),o=Math.min(Math.max(0,t.uso.cacheWriteInputTokens??0),n-r),i=n-r-o;if(n<ls||i<=0)return {importe:0,costeEstandar:0,costeAplicado:0,tokensOrdinarios:Math.max(0,i),consultado:e};let s=i/1e3*t.fila.
280
+ cacheWritePer1k,a=i/1e3*t.fila.inputPer1k;return {importe:to(s-a),costeEstandar:s,costeAplicado:a,tokensOrdinarios:i,consultado:e}}var fs=new Set;function V(t,e){fs.has(t)||(fs.add(t),console.warn(e));}function qt(t){return {esquemaEnFormatoNativo:false,esquemaEstricto:false,esquemaPorPrompt:false,piezasDelAdaptador:t}}var al=2;function ht(t){return al*(t??[]).filter(e=>e.parameters==null).length}var Mn=new WeakMap;
281
+ function gt(t,e){return Mn.set(t,e),t}function Ln(t){return typeof t=="object"&&t!==null?Mn.get(t):void 0}var ms=new WeakMap;function hs(t,e){ms.set(t,e);}function Ht(t){return typeof t=="object"&&t!==
282
+ null?ms.get(t):void 0}function gs(t,e){let n=Mn.get(t);return n&&Mn.set(e,n),e}var no=class{decoder;resto="";crPendiente=false;alPrincipio=true;datos="";evento="";ultimoId;push(e){let n=typeof e=="string"?e:(this.decoder??=new TextDecoder("utf-8")).decode(e,{stream:true});return this.procesar(
225
283
  n)}end(){let e=[];if(this.decoder){let n=this.decoder.decode();n!==""&&e.push(...this.procesar(n));}return this.resto!==""&&(this.linea(this.resto,e),this.resto=""),this.despachar(e),this.crPendiente=false,
226
284
  e}procesar(e){let n=[];if(e==="")return n;let r=e;if(this.alPrincipio&&(this.alPrincipio=false,r.charCodeAt(0)===65279&&(r=r.slice(1)),r===""))return n;let o=0;this.crPendiente&&(this.crPendiente=false,r.charCodeAt(
227
- 0)===10&&(o=1));let s=o;for(;o<r.length;){let i=r.charCodeAt(o);if(i!==10&&i!==13){o++;continue}this.linea(this.resto+r.slice(s,o),n),this.resto="",i===13&&(o+1<r.length?r.charCodeAt(o+1)===10&&o++:this.
228
- crPendiente=true),o++,s=o;}return this.resto+=r.slice(s),n}linea(e,n){if(e===""){this.despachar(n);return}if(e.charCodeAt(0)===58)return;let r=e.indexOf(":"),o,s;switch(r===-1?(o=e,s=""):(o=e.slice(0,r),
229
- s=e.slice(r+1),s.charCodeAt(0)===32&&(s=s.slice(1))),o){case "data":this.datos+=s+`
230
- `;break;case "event":this.evento=s;break;case "id":s.includes("\0")||(this.ultimoId=s);break;}}despachar(e){if(this.datos===""){this.evento="";return}e.push({event:this.evento===""?"message":
231
- this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};async function*nn(t){let e=new fr;if(typeof t=="string"){yield*e.push(t),yield*e.
232
- end();return}let n=t.getReader();try{for(;;){let{done:r,value:o}=await n.read();if(r)break;o!==void 0&&(yield*e.push(o));}yield*e.end();}finally{try{await n.cancel();}catch{}}}function Re(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.
233
- map(String):[];if(o.some(i=>!s.includes(i)))return false;for(let i of Object.values(n))if(!Re(i))return false}if(e.items!==void 0&&!Re(e.items))return false;for(let o of ["anyOf","oneOf","allOf"]){let s=e[o];if(Array.
234
- isArray(s)&&s.some(i=>!Re(i)))return false}let r=e.$defs??e.definitions;return !(r&&typeof r=="object"&&Object.values(r).some(o=>!Re(o)))}function Sc(t){return !/response_format/i.test(t)||/invalid schema/i.
235
- test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.test(t)}function Tc(t){return `Respond with a single JSON object and nothing else: no prose, no\
285
+ 0)===10&&(o=1));let i=o;for(;o<r.length;){let s=r.charCodeAt(o);if(s!==10&&s!==13){o++;continue}this.linea(this.resto+r.slice(i,o),n),this.resto="",s===13&&(o+1<r.length?r.charCodeAt(o+1)===10&&o++:this.
286
+ crPendiente=true),o++,i=o;}return this.resto+=r.slice(i),n}linea(e,n){if(e===""){this.despachar(n);return}if(e.charCodeAt(0)===58)return;let r=e.indexOf(":"),o,i;switch(r===-1?(o=e,i=""):(o=e.slice(0,r),
287
+ i=e.slice(r+1),i.charCodeAt(0)===32&&(i=i.slice(1))),o){case "data":this.datos+=i+`
288
+ `;break;case "event":this.evento=i;break;case "id":i.includes("\0")||(this.ultimoId=i);break;}}despachar(e){if(this.datos===""){this.evento="";return}e.push({event:this.evento===""?"message":
289
+ this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};async function*Nn(t){let e=new no;if(typeof t=="string"){yield*e.push(t),yield*e.
290
+ end();return}let n=t.getReader();try{for(;;){let{done:r,value:o}=await n.read();if(r)break;o!==void 0&&(yield*e.push(o));}yield*e.end();}finally{try{await n.cancel();}catch{}}}function je(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),i=Array.isArray(e.required)?e.required.
291
+ map(String):[];if(o.some(s=>!i.includes(s)))return false;for(let s of Object.values(n))if(!je(s))return false}if(e.items!==void 0&&!je(e.items))return false;for(let o of ["anyOf","oneOf","allOf"]){let i=e[o];if(Array.
292
+ isArray(i)&&i.some(s=>!je(s)))return false}let r=e.$defs??e.definitions;return !(r&&typeof r=="object"&&Object.values(r).some(o=>!je(o)))}function cl(t){return !/response_format/i.test(t)||/invalid schema/i.
293
+ test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.test(t)}function ul(t){return `Respond with a single JSON object and nothing else: no prose, no\
236
294
  explanation, no markdown code fences. The object must validate against this JSON Schema:
237
- `+JSON.stringify(t)}var Ec=/(^|\.)api\.openai\.com$|\.openai\.azure\.com$/i;function as(t,e,n){return e??Rc(n)?t.replace(/^[^/]+\//,""):t}function Rc(t){try{return Ec.test(new URL(t).hostname)}catch{return false}}
238
- var cs=class{id;opts;fetchImpl;sinResponseFormat=new Set;streamOptionsRejected=false;constructor(e){this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch;}async generate(e,n){
239
- let r=as(e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n?.signal,s=e.schema!=null&&!this.sinResponseFormat.has(r),i=await this.enviar(r,e,s,void 0,o);if(!i.ok&&i.status===400&&s){let a=await on(
240
- i);if(!Sc(a))throw new Error(`provider ${i.status}: ${a}`);this.sinResponseFormat.add(r),F(`sin-response-format:${r}`,`[bvsala] Model "${r}" rejects \`response_format\` with a 400: it has no structured \
241
- outputs. The request is repeated asking for the JSON via prompt (once only: the model is noted and the following requests go straight there). The schema still travels and the layer still validates, bu\
242
- t the guarantee comes from the layer, not the provider, and the report says so: \`constraints.backend: "none"\`. To recover the native guarantee, use a model with structured outputs (gpt-4o or later).`),
243
- s=false,i=await this.enviar(r,e,false,void 0,o);}if(!i.ok){let a=await on(i);throw new Error(`provider ${i.status}: ${a}`)}return this.leer(i,e,s)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===
244
- true){let y=await this.generate(e);y.text!==""&&(yield {type:"text",delta:y.text}),yield {type:"done",response:y};return}let r=as(e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n.signal,s=!this.
245
- streamOptionsRejected,i=await this.enviar(r,e,false,{includeUsage:s,...o?{signal:o}:{}});if(!i.ok&&s&&(i.status===400||i.status===422)){let y=await on(i);if(i.status!==422&&!/stream_options|include_usage/i.
246
- test(y))throw new Error(`provider ${i.status}: ${y}`);if(this.opts.requireUsage)throw new Error(`provider ${i.status}: this endpoint rejects stream_options, so a streamed answer would carry no usage a\
247
- nd requireUsage is set. ${y}`);i=await this.enviar(r,e,false,{includeUsage:false,...o?{signal:o}:{}}),i.ok&&(this.streamOptionsRejected=true,F(`sin-stream-options:${this.opts.baseUrl}`,"[bvsala] This endpoint\
248
- rejects `stream_options`, so streamed answers from it carry no usage: they are reported as `unmeasured` and never billed. Use `generate()` for a measured figure, or an endpoint that reports usage whe\
249
- n streaming."));}if(!i.ok)throw new Error(`provider ${i.status}: ${await on(i)}`);if((i.headers.get("content-type")??"").includes("application/json")){let y=await this.leer(i,e,false);y.text!==""&&(yield {
250
- type:"text",delta:y.text}),yield {type:"done",response:y};return}let a=i.body,c=a&&typeof a.getReader=="function"?a:await i.text(),u="",l=new Map,d,m,f,h=false;for await(let y of nn(c)){if(y.data==="[DONE\
251
- ]")break;let k;try{k=JSON.parse(y.data);}catch{continue}if(k===null||typeof k!="object")continue;if(k.error!=null){let I=k.error,O=typeof I.message=="string"?I.message:JSON.stringify(k.error);throw new Error(
252
- `provider stream error: ${O}`)}let E=k.choices?.[0],w=E?.delta;(rn(w?.reasoning_content)||rn(w?.reasoning))&&(h=true),typeof w?.content=="string"&&w.content!==""&&(u+=w.content,yield {type:"text",delta:w.
253
- content});for(let I of w?.tool_calls??[]){let O=typeof I.index=="number"?I.index:0,C=l.get(O)??{args:""};!C.id&&typeof I.id=="string"&&I.id!==""&&(C.id=I.id);let _=I.function?.name;!C.name&&typeof _==
254
- "string"&&_!==""&&(C.name=_),typeof I.function?.arguments=="string"&&(C.args+=I.function.arguments),l.set(O,C);}E?.finish_reason!=null&&(d=E.finish_reason),k.usage!=null&&typeof k.usage=="object"&&(m=k.
255
- usage),typeof k.service_tier=="string"&&k.service_tier!==""&&(f=k.service_tier);}if(d===void 0)throw new Error("provider stream ended before completion (no finish_reason)");let g=typeof m?.prompt_tokens!=
256
- "number",p=typeof m?.completion_tokens!="number";if(this.opts.requireUsage&&(g||p))throw new Error(ls(m?.prompt_tokens,m?.completion_tokens));let v=us(m,h),b={inputTokens:m?.prompt_tokens??0,outputTokens:m?.
257
- completion_tokens??0,...m?.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:m.prompt_tokens_details.cached_tokens}:{},...v!==void 0?{reasoningTokens:v}:{},...g||p?{complete:false}:{}},x=[...l.
258
- entries()].sort((y,k)=>y[0]-k[0]).map(([,y])=>({...y.id?{id:y.id}:{},name:y.name??"",arguments:y.args})).filter(y=>y.name!=="");yield {type:"done",response:We({text:u,...x.length>0?{toolCalls:x}:{},finishReason:d,
259
- ...f?{servedServiceTier:f}:{},usage:b,structuredNatively:false,raw:m??null},gt(Je(e.tools)))};}async enviar(e,n,r,o,s){let i=n.messages.map(c=>c.role==="tool"?{role:"tool",content:c.content,tool_call_id:c.
260
- toolCallId??c.metadata?.tool_call_id,...c.name?{name:c.name}:{}}:c.role==="assistant"&&c.toolCalls&&c.toolCalls.length>0?{role:"assistant",content:c.content||null,tool_calls:c.toolCalls.map((u,l)=>({id:u.
261
- id??`call_${l}`,type:"function",function:{name:u.name,arguments:u.arguments}}))}:{role:c.role,content:c.content});n.schema&&!r&&i.push({role:"system",content:Tc(n.schema)});let a={model:e,messages:i};
262
- if(n.maxOutputTokens!=null&&(a.max_tokens=n.maxOutputTokens),n.temperature!=null&&(a.temperature=n.temperature),n.seed!=null&&(a.seed=n.seed),n.promptCacheKey!=null&&(a.prompt_cache_key=n.promptCacheKey),
263
- n.deferrable===true&&(a.service_tier=Qt),n.schema&&r){let c=Re(n.schema);c||F("strict-incompatible","[bvsala] The response contract does not meet OpenAI's `strict` mode (in strict, `required` must list \
264
- ALL the keys in `properties`, and every object needs `additionalProperties: false`). The schema is sent with `strict: false`: the model is still guided and the layer still validates, but the guarantee\
265
- comes from the layer, not the provider. To recover it, make every key in the contract required."),a.response_format={type:"json_schema",json_schema:{name:"bvsala_contract",schema:n.schema,strict:c}};}
266
- return n.tools&&n.tools.length>0&&(a.tools=n.tools.map(c=>({type:"function",function:{name:c.id,...c.description?{description:c.description}:{},parameters:c.parameters??{type:"object",properties:{}}}}))),
267
- o&&(a.stream=true,o.includeUsage&&(a.stream_options={include_usage:true})),await this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{"content-type":"applicatio\
268
- n/json",...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.headers},body:JSON.stringify(a),...o?.signal?{signal:o.signal}:!o&&s?{signal:s}:{}})}async leer(e,n,r){let o=await e.
269
- json(),s=o.choices?.[0]?.message,i=s?.content??"",a=(s?.tool_calls??[]).map(p=>({...p.id?{id:p.id}:{},name:p.function?.name??"",arguments:p.function?.arguments??""})).filter(p=>p.name!==""),c=o.usage??
270
- {},u=c.prompt_tokens??0,l=c.completion_tokens??0,d=typeof c.prompt_tokens!="number",m=typeof c.completion_tokens!="number";if(this.opts.requireUsage&&(d||m))throw new Error(ls(c.prompt_tokens,c.completion_tokens));
271
- let f=o.choices?.[0]?.finish_reason,h=typeof o.service_tier=="string"&&o.service_tier!==""?o.service_tier:void 0,g=us(c,rn(s?.reasoning_content)||rn(s?.reasoning));return We({text:i,...a.length>0?{toolCalls:a}:
272
- {},...f?{finishReason:f}:{},...h?{servedServiceTier:h}:{},...n.deferrable===true?{requestedServiceTier:Qt}:{},usage:{inputTokens:u,outputTokens:l,...c.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:c.
273
- prompt_tokens_details.cached_tokens}:{},...g!==void 0?{reasoningTokens:g}:{},...d||m?{complete:false}:{}},structuredNatively:n.schema!=null&&r,raw:o},{esquemaEnFormatoNativo:n.schema!=null&&r,esquemaEstricto:n.
274
- schema!=null&&r&&Re(n.schema),esquemaPorPrompt:n.schema!=null&&!r,piezasDelAdaptador:Je(n.tools)})}};function us(t,e){let n=t?.completion_tokens_details?.reasoning_tokens;if(!(typeof n!="number"||!Number.
275
- isInteger(n)||n<0)&&!(n===0&&e))return n}function rn(t){return typeof t=="string"&&t!==""}function ls(t,e){return `provider returned incomplete usage (prompt=${t??"absent"}, completion=${e??"absent"});\
276
- cannot measure cost. For gateways/streaming, ensure usage reporting is enabled.`}async function on(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function ds(t){return `Respond with a single JSON object and nothing else: no prose, no explanation, no markdown code fences. The object must validate against this JSON Schema:
277
- `+JSON.stringify(t)}var sn=4,Le="bvsala_contract",ps=class{id;opts;fetchImpl;constructor(e={}){this.opts=e,this.id=`anthropic:${e.baseUrl??"https://api.anthropic.com/v1"}`,this.fetchImpl=e.fetchImpl??fetch;}modeloEnElCable(e){
295
+ `+JSON.stringify(t)}var ll=/(^|\.)api\.openai\.com$|\.openai\.azure\.com$/i;function bs(t,e,n){return e??fl(n)?t.replace(/^[^/]+\//,""):t}var dl={"api.openai.com":"openai","generativelanguage.googleap\
296
+ is.com":"google"};function pl(t){try{let e=new URL(t);return e.protocol!=="https:"?null:dl[e.hostname.toLowerCase()]??null}catch{return null}}var vs="x-gemini-service-tier";function ys(t,e){try{let n=t.
297
+ headers?.get?.(e);return typeof n=="string"&&n.trim()!==""?n.trim():void 0}catch{return}}function ro(t,e,n){if(e.explicitCacheWrites!==true||!Ut(t,n))return null;let r=e.stablePrefixMessages;if(r==null||
298
+ !Number.isInteger(r)||r<=0||r>e.messages.length)return {puntos:0,indice:-1};let o=e.messages[r-1];return (o.role==="system"||o.role==="user"||o.role==="tool")&&typeof o.content=="string"&&o.content!==""?
299
+ {puntos:1,indice:r-1}:{puntos:0,indice:-1}}function fl(t){try{return ll.test(new URL(t).hostname)}catch{return false}}var ks=class{id;opts;fetchImpl;sinResponseFormat=new Set;streamOptionsRejected=false;origen;constructor(e){
300
+ this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch,this.origen=pl(e.baseUrl),hs(this,this.origen);}async generate(e,n){let r=bs(e.model,this.opts.stripProviderPrefix,
301
+ this.opts.baseUrl),o=n?.signal,i=e.schema!=null&&!this.sinResponseFormat.has(r),s=await this.enviar(r,e,i,void 0,o);if(!s.ok&&s.status===400&&i){let a=await $n(s);if(!cl(a))throw new Error(`provider ${s.
302
+ status}: ${a}`);this.sinResponseFormat.add(r),V(`sin-response-format:${r}`,`[bvsala] Model "${r}" rejects \`response_format\` with a 400: it has no structured outputs. The request is repeated asking for\
303
+ the JSON via prompt (once only: the model is noted and the following requests go straight there). The schema still travels and the layer still validates, but the guarantee comes from the layer, not t\
304
+ he provider, and the report says so: \`constraints.backend: "none"\`. To recover the native guarantee, use a model with structured outputs (gpt-4o or later).`),i=false,s=await this.enviar(r,e,false,void 0,o);}
305
+ if(!s.ok){let a=await $n(s);throw new Error(`provider ${s.status}: ${a}`)}return this.leer(s,e,i,r)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let w=await this.generate(e);w.text!==
306
+ ""&&(yield {type:"text",delta:w.text}),yield {type:"done",response:w};return}let r=bs(e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n.signal,i=!this.streamOptionsRejected,s=await this.enviar(
307
+ r,e,false,{includeUsage:i,...o?{signal:o}:{}});if(!s.ok&&i&&(s.status===400||s.status===422)){let w=await $n(s);if(s.status!==422&&!/stream_options|include_usage/i.test(w))throw new Error(`provider ${s.status}\
308
+ : ${w}`);if(this.opts.requireUsage)throw new Error(`provider ${s.status}: this endpoint rejects stream_options, so a streamed answer would carry no usage and requireUsage is set. ${w}`);s=await this.enviar(
309
+ r,e,false,{includeUsage:false,...o?{signal:o}:{}}),s.ok&&(this.streamOptionsRejected=true,V(`sin-stream-options:${this.opts.baseUrl}`,"[bvsala] This endpoint rejects `stream_options`, so streamed answers from\
310
+ it carry no usage: they are reported as `unmeasured` and never billed. Use `generate()` for a measured figure, or an endpoint that reports usage when streaming."));}if(!s.ok)throw new Error(`provider ${s.
311
+ status}: ${await $n(s)}`);if((s.headers.get("content-type")??"").includes("application/json")){let w=await this.leer(s,e,false,r);w.text!==""&&(yield {type:"text",delta:w.text}),yield {type:"done",response:w};
312
+ return}let a=s.body,u=a&&typeof a.getReader=="function"?a:await s.text(),c="",l=new Map,d,f,m,h=false;for await(let w of Nn(u)){if(w.data==="[DONE]")break;let R;try{R=JSON.parse(w.data);}catch{continue}if(R===
313
+ null||typeof R!="object")continue;if(R.error!=null){let _=R.error,S=typeof _.message=="string"?_.message:JSON.stringify(R.error);throw new Error(`provider stream error: ${S}`)}let D=R.choices?.[0],O=D?.
314
+ delta;(jn(O?.reasoning_content)||jn(O?.reasoning))&&(h=true),typeof O?.content=="string"&&O.content!==""&&(c+=O.content,yield {type:"text",delta:O.content});for(let _ of O?.tool_calls??[]){let S=typeof _.
315
+ index=="number"?_.index:0,C=l.get(S)??{args:""};!C.id&&typeof _.id=="string"&&_.id!==""&&(C.id=_.id);let P=_.function?.name;!C.name&&typeof P=="string"&&P!==""&&(C.name=P),typeof _.function?.arguments==
316
+ "string"&&(C.args+=_.function.arguments),l.set(S,C);}D?.finish_reason!=null&&(d=D.finish_reason),R.usage!=null&&typeof R.usage=="object"&&(f=R.usage),typeof R.service_tier=="string"&&R.service_tier!==""&&
317
+ (m=R.service_tier);}if(d===void 0)throw new Error("provider stream ended before completion (no finish_reason)");let b=typeof f?.prompt_tokens!="number",p=typeof f?.completion_tokens!="number";if(this.opts.
318
+ requireUsage&&(b||p))throw new Error(Ss(f?.prompt_tokens,f?.completion_tokens));let v=xs(f,h),g=ws(f),y={inputTokens:f?.prompt_tokens??0,outputTokens:f?.completion_tokens??0,...f?.prompt_tokens_details?.
319
+ cached_tokens!=null?{cachedInputTokens:f.prompt_tokens_details.cached_tokens}:{},...g!==void 0?{cacheWriteInputTokens:g}:{},...v!==void 0?{reasoningTokens:v}:{},...b||p?{complete:false}:{}},k=[...l.entries()].
320
+ sort((w,R)=>w[0]-R[0]).map(([,w])=>({...w.id?{id:w.id}:{},name:w.name??"",arguments:w.args})).filter(w=>w.name!==""),x=m?"cuerpo":void 0;!m&&this.origen==="google"&&(m=ys(s,vs),m&&(x="cabecera"));let T=ro(
321
+ r,e,this.origen);yield {type:"done",response:gt({text:c,...k.length>0?{toolCalls:k}:{},finishReason:d,...m?{servedServiceTier:m}:{},usage:y,structuredNatively:false,raw:f??null},{...qt(ht(e.tools)),origen:this.
322
+ origen,...x?{tierLeidoDe:x}:{},...T?{cacheExplicita:{puntos:T.puntos}}:{}})};}async enviar(e,n,r,o,i){let s=n.messages.map(c=>c.role==="tool"?{role:"tool",content:c.content,tool_call_id:c.toolCallId??c.
323
+ metadata?.tool_call_id,...c.name?{name:c.name}:{}}:c.role==="assistant"&&c.toolCalls&&c.toolCalls.length>0?{role:"assistant",content:c.content||null,tool_calls:c.toolCalls.map((l,d)=>({id:l.id??`call_${d}`,
324
+ type:"function",function:{name:l.name,arguments:l.arguments}}))}:{role:c.role,content:c.content}),a=ro(e,n,this.origen);if(a?.puntos===1){let c=s[a.indice];c.content=[{type:"text",text:c.content,prompt_cache_breakpoint:{
325
+ mode:"explicit"}}];}n.schema&&!r&&s.push({role:"system",content:ul(n.schema)});let u={model:e,messages:s};if(n.maxOutputTokens!=null&&(u.max_tokens=n.maxOutputTokens),n.temperature!=null&&(u.temperature=
326
+ n.temperature),n.seed!=null&&(u.seed=n.seed),n.promptCacheKey!=null&&(u.prompt_cache_key=n.promptCacheKey),n.deferrable===true&&(u.service_tier=mt),a&&(u.prompt_cache_options={mode:"explicit"}),n.schema&&
327
+ r){let c=je(n.schema);c||V("strict-incompatible","[bvsala] The response contract does not meet OpenAI's `strict` mode (in strict, `required` must list ALL the keys in `properties`, and every object ne\
328
+ eds `additionalProperties: false`). The schema is sent with `strict: false`: the model is still guided and the layer still validates, but the guarantee comes from the layer, not the provider. To recov\
329
+ er it, make every key in the contract required."),u.response_format={type:"json_schema",json_schema:{name:"bvsala_contract",schema:n.schema,strict:c}};}return n.tools&&n.tools.length>0&&(u.tools=n.tools.
330
+ map(c=>({type:"function",function:{name:c.id,...c.description?{description:c.description}:{},parameters:c.parameters??{type:"object",properties:{}}}}))),o&&(u.stream=true,o.includeUsage&&(u.stream_options=
331
+ {include_usage:true})),await this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",...this.opts.apiKey?{authorization:`Bearer\
332
+ ${this.opts.apiKey}`}:{},...this.opts.headers},body:JSON.stringify(u),...o?.signal?{signal:o.signal}:!o&&i?{signal:i}:{}})}async leer(e,n,r,o){let i=await e.json(),s=i.choices?.[0]?.message,a=s?.content??
333
+ "",u=(s?.tool_calls??[]).map(k=>({...k.id?{id:k.id}:{},name:k.function?.name??"",arguments:k.function?.arguments??""})).filter(k=>k.name!==""),c=i.usage??{},l=c.prompt_tokens??0,d=c.completion_tokens??
334
+ 0,f=typeof c.prompt_tokens!="number",m=typeof c.completion_tokens!="number";if(this.opts.requireUsage&&(f||m))throw new Error(Ss(c.prompt_tokens,c.completion_tokens));let h=i.choices?.[0]?.finish_reason,
335
+ b=typeof i.service_tier=="string"&&i.service_tier!==""?i.service_tier:void 0,p=b?"cuerpo":void 0;!b&&this.origen==="google"&&(b=ys(e,vs),b&&(p="cabecera"));let v=ws(c),g=ro(o,n,this.origen),y=xs(c,jn(
336
+ s?.reasoning_content)||jn(s?.reasoning));return gt({text:a,...u.length>0?{toolCalls:u}:{},...h?{finishReason:h}:{},...b?{servedServiceTier:b}:{},...n.deferrable===true?{requestedServiceTier:mt}:{},usage:{
337
+ inputTokens:l,outputTokens:d,...c.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:c.prompt_tokens_details.cached_tokens}:{},...v!==void 0?{cacheWriteInputTokens:v}:{},...y!==void 0?{reasoningTokens:y}:
338
+ {},...f||m?{complete:false}:{}},structuredNatively:n.schema!=null&&r,raw:i},{esquemaEnFormatoNativo:n.schema!=null&&r,esquemaEstricto:n.schema!=null&&r&&je(n.schema),esquemaPorPrompt:n.schema!=null&&!r,piezasDelAdaptador:ht(
339
+ n.tools),origen:this.origen,...p?{tierLeidoDe:p}:{},...g?{cacheExplicita:{puntos:g.puntos}}:{}})}};function xs(t,e){let n=t?.completion_tokens_details?.reasoning_tokens;if(!(typeof n!="number"||!Number.
340
+ isInteger(n)||n<0)&&!(n===0&&e))return n}function ws(t){let e=t?.prompt_tokens_details?.cache_write_tokens;return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:void 0}function jn(t){return typeof t==
341
+ "string"&&t!==""}function Ss(t,e){return `provider returned incomplete usage (prompt=${t??"absent"}, completion=${e??"absent"}); cannot measure cost. For gateways/streaming, ensure usage reporting is e\
342
+ nabled.`}async function $n(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function Ts(t){return `Respond with a single JSON object and nothing else: no prose, no explanation, no markdown code fences. The object must validate against this JSON Schema:
343
+ `+JSON.stringify(t)}var bt=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:0;function Es(t){if(!Array.isArray(t))return null;let e={input:0,output:0,cacheRead:0,cacheWrite:0,cacheWrite1h:0,iteraciones:0};for(let n of t){
344
+ if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;e.iteraciones++,e.input+=bt(r.input_tokens),e.output+=bt(r.output_tokens),e.cacheRead+=bt(r.cache_read_input_tokens);
345
+ let o=r.cache_creation,i=bt(o?.ephemeral_5m_input_tokens),s=bt(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?bt(r.cache_creation_input_tokens):i+s;e.cacheWrite+=a,e.cacheWrite1h+=
346
+ Math.min(s,a);}return e.iteraciones>0?e:null}function oo(t,e,n){let r=t??{},o=Es(r.iterations),i=Rs(r.cache_read_input_tokens,o?.cacheRead),s=Rs(r.cache_creation_input_tokens,o?.cacheWrite),a=(r.input_tokens??0)+(o?.input??0)+(s??0)+(i??0),u=(e??
347
+ 0)+(o?.output??0),c=typeof r.input_tokens!="number",l=typeof e!="number";return {usage:{inputTokens:a,outputTokens:u,...i!=null?{cachedInputTokens:i}:{},...s!=null?{cacheWriteInputTokens:s}:{},...n||l||
348
+ o?{}:{reasoningTokens:0},...c||l?{complete:false}:{}},entradaAusente:c,salidaAusente:l}}function Rs(t,e){return e?(t??0)+e:t}function io(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
349
+ function so(t,e){let n=Object.fromEntries(Object.entries(e??{}).filter(([,o])=>o!=null)),r=t?.cache_creation||e?.cache_creation?{...t?.cache_creation??{},...e?.cache_creation??{}}:void 0;return {...t??
350
+ {},...n,...r?{cache_creation:r}:{}}}function ao(t){return t==="thinking"||t==="redacted_thinking"}function co(t){switch(t){case "end_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "\
351
+ tool_calls";case "refusal":return "content_filter";default:return t}}var Fn=4,Ze="bvsala_contract",Cs=class{id;opts;fetchImpl;constructor(e={}){this.opts=e,this.id=`anthropic:${e.baseUrl??"https://api.anthropic.com/v1"}`,this.fetchImpl=e.fetchImpl??fetch;}modeloEnElCable(e){
278
352
  let n=this.opts.baseUrl??"https://api.anthropic.com/v1",r=false;try{r=/(^|\.)api\.anthropic\.com$/i.test(new URL(n).hostname);}catch{r=false;}return this.opts.stripProviderPrefix??r?e.replace(/^[^/]+\//,""):e}async generate(e,n){
279
- let r=this.construirCuerpo(e),o=await this.enviar(r.body,n?.signal);if(!o.ok)throw new Error(`provider ${o.status}: ${await bs(o)}`);return this.leer(o,e,r.contratoNativo,r.turnoAnadido,r.esquemaPorPrompt)}async*generateStream(e,n={}){
280
- if(e.schema!=null||e.deferrable===true){let y=await this.generate(e);y.text!==""&&(yield {type:"text",delta:y.text}),yield {type:"done",response:y};return}let r=this.construirCuerpo(e),o=r.body;o.stream=true;
281
- let s=await this.enviar(o,n.signal);if(!s.ok)throw new Error(`provider ${s.status}: ${await bs(s)}`);if((s.headers.get("content-type")??"").includes("application/json")){let y=await this.leer(s,e,r.contratoNativo,
282
- r.turnoAnadido,r.esquemaPorPrompt);y.text!==""&&(yield {type:"text",delta:y.text}),yield {type:"done",response:y};return}let i=s.body,a=i&&typeof i.getReader=="function"?i:await s.text(),c="",u=new Map,
283
- l,d,m=false,f=false,h,g=false;for await(let y of nn(a)){let k;try{k=JSON.parse(y.data);}catch{continue}if(k===null||typeof k!="object")continue;let E=y.event!=="message"?y.event:k.type??y.event;if(E==="message_\
284
- start")l=k.message?.usage??l;else if(E==="content_block_start"){let w=k.content_block;fs(w?.type)&&(g=true),typeof k.index=="number"&&w&&u.set(k.index,{tipo:w.type??"",...typeof w.id=="string"?{id:w.id}:
285
- {},...typeof w.name=="string"?{name:w.name}:{},json:""});}else if(E==="content_block_delta"){let w=k.delta;if(w?.type==="text_delta"&&typeof w.text=="string"&&w.text!=="")c+=w.text,yield {type:"text",delta:w.
286
- text};else if(w?.type==="input_json_delta"&&typeof w.partial_json=="string"){let I=typeof k.index=="number"?u.get(k.index):void 0;I&&(I.json+=w.partial_json);}}else if(E==="message_delta")m=true,h=k.delta?.
287
- stop_reason??h,k.usage&&(d=hs(d,k.usage));else if(E==="message_stop"){f=true;break}else if(E==="error")throw new Error(`provider stream error: ${k.error?.type}: ${k.error?.message}`)}if(!f&&!m)throw new Error(
288
- "provider stream ended before completion (no message_delta)");let p=hs(l,d),v;if(!m)v={inputTokens:0,outputTokens:0,complete:false};else {let y=p.cache_read_input_tokens,k=p.cache_creation_input_tokens;v=
289
- {inputTokens:(p.input_tokens??0)+(k??0)+(y??0),outputTokens:d?.output_tokens??0,...y!=null?{cachedInputTokens:y}:{},...k!=null?{cacheWriteInputTokens:k}:{},...g||typeof d?.output_tokens!="number"?{}:{
290
- reasoningTokens:0},...typeof p.input_tokens!="number"||typeof d?.output_tokens!="number"?{complete:false}:{}};}if(this.opts.requireUsage&&v.complete===false)throw new Error(gs(m?p.input_tokens:void 0,m?d?.output_tokens:
291
- void 0));let b=[...u.entries()].sort((y,k)=>y[0]-k[0]).map(([,y])=>y).filter(y=>y.tipo==="tool_use"&&y.name!==Le).map(y=>({...y.id?{id:y.id}:{},name:y.name??"",arguments:Ic(y.json)})).filter(y=>y.name!==
292
- ""),x=typeof p.service_tier=="string"&&p.service_tier!==""?p.service_tier:void 0;yield {type:"done",response:We({text:c,...b.length>0?{toolCalls:b}:{},...h?{finishReason:ms(h)}:{},...x?{servedServiceTier:x}:
293
- {},usage:v,structuredNatively:false,raw:{usage:p,stop_reason:h}},gt((r.turnoAnadido?1:0)+Je(e.tools)))};}async enviar(e,n){let r=(this.opts.baseUrl??"https://api.anthropic.com/v1").replace(/\/$/,"");return await this.
353
+ let r=this.construirCuerpo(e),o=await this.enviar(r.body,n?.signal);if(!o.ok)throw new Error(`provider ${o.status}: ${await Ps(o)}`);return this.leer(o,e,r.contratoNativo,r.turnoAnadido,r.esquemaPorPrompt)}async*generateStream(e,n={}){
354
+ if(e.schema!=null||e.deferrable===true){let x=await this.generate(e);x.text!==""&&(yield {type:"text",delta:x.text}),yield {type:"done",response:x};return}let r=this.construirCuerpo(e),o=r.body;o.stream=true;
355
+ let i=await this.enviar(o,n.signal);if(!i.ok)throw new Error(`provider ${i.status}: ${await Ps(i)}`);if((i.headers.get("content-type")??"").includes("application/json")){let x=await this.leer(i,e,r.contratoNativo,
356
+ r.turnoAnadido,r.esquemaPorPrompt);x.text!==""&&(yield {type:"text",delta:x.text}),yield {type:"done",response:x};return}let s=i.body,a=s&&typeof s.getReader=="function"?s:await i.text(),u="",c=new Map,
357
+ l,d,f=false,m=false,h,b=false;for await(let x of Nn(a)){let T;try{T=JSON.parse(x.data);}catch{continue}if(T===null||typeof T!="object")continue;let w=x.event!=="message"?x.event:T.type??x.event;if(w==="message_\
358
+ start")l=T.message?.usage??l;else if(w==="content_block_start"){let R=T.content_block;ao(R?.type)&&(b=true),typeof T.index=="number"&&R&&c.set(T.index,{tipo:R.type??"",...typeof R.id=="string"?{id:R.id}:
359
+ {},...typeof R.name=="string"?{name:R.name}:{},json:""});}else if(w==="content_block_delta"){let R=T.delta;if(R?.type==="text_delta"&&typeof R.text=="string"&&R.text!=="")u+=R.text,yield {type:"text",delta:R.
360
+ text};else if(R?.type==="input_json_delta"&&typeof R.partial_json=="string"){let D=typeof T.index=="number"?c.get(T.index):void 0;D&&(D.json+=R.partial_json);}}else if(w==="message_delta")f=true,h=T.delta?.
361
+ stop_reason??h,T.usage&&(d=so(d,T.usage));else if(w==="message_stop"){m=true;break}else if(w==="error")throw new Error(`provider stream error: ${T.error?.type}: ${T.error?.message}`)}if(!m&&!f)throw new Error(
362
+ "provider stream ended before completion (no message_delta)");let p=so(l,d),g=(f?oo(p,d?.output_tokens,b):void 0)?.usage??{inputTokens:0,outputTokens:0,complete:false};if(this.opts.requireUsage&&g.complete===
363
+ false)throw new Error(Is(f?p.input_tokens:void 0,f?d?.output_tokens:void 0));let y=[...c.entries()].sort((x,T)=>x[0]-T[0]).map(([,x])=>x).filter(x=>x.tipo==="tool_use"&&x.name!==Ze).map(x=>({...x.id?{id:x.
364
+ id}:{},name:x.name??"",arguments:hl(x.json)})).filter(x=>x.name!==""),k=io(p);yield {type:"done",response:gt({text:u,...y.length>0?{toolCalls:y}:{},...h?{finishReason:co(h)}:{},...k?{servedServiceTier:k}:
365
+ {},usage:g,structuredNatively:false,raw:{usage:p,stop_reason:h}},qt((r.turnoAnadido?1:0)+ht(e.tools)))};}async enviar(e,n){let r=(this.opts.baseUrl??"https://api.anthropic.com/v1").replace(/\/$/,"");return await this.
294
366
  fetchImpl(`${r}/messages`,{method:"POST",headers:{"content-type":"application/json","anthropic-version":this.opts.apiVersion??"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.
295
- opts.headers},body:JSON.stringify(e),...n?{signal:n}:{}})}construirCuerpo(e){let{system:n,messages:r,prefijoEnMensajes:o,prefijoEnSystem:s,turnoAnadido:i}=Cc(e);if(r.length===0)throw new Error("anthro\
296
- pic: the request has no user/assistant message. The Messages API needs at least one, and system prompts travel in the `system` field \u2014 they do not count.");let a=(e.tools??[]).map(f=>({name:f.id,
297
- ...f.description?{description:f.description}:{},input_schema:f.parameters??{type:"object",properties:{}}})),c=false,u=false,l=false;if(e.schema){let f=a.length>0,h=a.some(p=>p.name===Le),g=Re(e.schema);h?(n.push(
298
- {type:"text",text:ds(e.schema)}),u=true,F("anthropic-contrato-nombre-ocupado",`[bvsala] One of your tools is already named \`${Le}\`, so the output contract cannot travel as a tool without colliding with\
299
- it (duplicate tool names are a provider error). The schema is sent as prompt text instead, which is measurably more expensive on this API. Rename that tool to get the cheaper path.`)):(!g&&!f&&F("ant\
367
+ opts.headers},body:JSON.stringify(e),...n?{signal:n}:{}})}construirCuerpo(e){let{system:n,messages:r,prefijoEnMensajes:o,prefijoEnSystem:i,turnoAnadido:s}=ml(e);if(r.length===0)throw new Error("anthro\
368
+ pic: the request has no user/assistant message. The Messages API needs at least one, and system prompts travel in the `system` field \u2014 they do not count.");let a=(e.tools??[]).map(m=>({name:m.id,
369
+ ...m.description?{description:m.description}:{},input_schema:m.parameters??{type:"object",properties:{}}})),u=false,c=false,l=false;if(e.schema){let m=a.length>0,h=a.some(p=>p.name===Ze),b=je(e.schema);h?(n.push(
370
+ {type:"text",text:Ts(e.schema)}),c=true,V("anthropic-contrato-nombre-ocupado",`[bvsala] One of your tools is already named \`${Ze}\`, so the output contract cannot travel as a tool without colliding with\
371
+ it (duplicate tool names are a provider error). The schema is sent as prompt text instead, which is measurably more expensive on this API. Rename that tool to get the cheaper path.`)):(!b&&!m&&V("ant\
300
372
  hropic-strict-incompatible","[bvsala] The response contract does not meet `strict` mode (in strict, `required` must list ALL the keys in `properties`, and every object needs `additionalProperties: fal\
301
- se`). The schema is sent without `strict`: the model is still guided and the layer still validates, but the guarantee comes from the layer, not the provider."),c=g&&!f,a.push({name:Le,description:f?"R\
373
+ se`). The schema is sent without `strict`: the model is still guided and the layer still validates, but the guarantee comes from the layer, not the provider."),u=b&&!m,a.push({name:Ze,description:m?"R\
302
374
  eturn the final answer in the required shape. Use the other tools first if you need data; call this one instead of writing the answer as text.":"Return the final answer in the required shape.",input_schema:e.
303
- schema,...c?{strict:true}:{}}),f&&(l=this.opts.forceAnswerThroughTool!==false,F("anthropic-contrato-con-herramientas","[bvsala] This request carries BOTH your tools and an output contract. On Anthropic's M\
375
+ schema,...u?{strict:true}:{}}),m&&(l=this.opts.forceAnswerThroughTool!==false,V("anthropic-contrato-con-herramientas","[bvsala] This request carries BOTH your tools and an output contract. On Anthropic's M\
304
376
  essages API a specific shape is only GUARANTEED by forcing that exact tool, and forcing ours would leave the model unable to call yours. The contract travels as one extra tool"+(l?' and the request is\
305
377
  sent with `tool_choice: {type: "any"}`, so the model must answer through SOME tool \u2014 yours or the contract \u2014 and can no longer reply in prose. Your tool turn is untouched. The guarantee is still the \
306
378
  layer\'s, not the provider\'s (`constraints.backend: "none"`), because the model may pick one of your tools and defer the final answer to the next turn.':", not forced (`forceAnswerThroughTool: false`\
307
379
  ). The guarantee is the layer's, not the provider's (`constraints.backend: \"none\"`), and if the model answers in prose the layer pays a second full call to repair it \u2014 on this API that second call re-\
308
380
  pays the whole tool-use overhead.")+" Dropping either the tools or the contract from this request is what makes the guarantee free.")));}let d={model:this.modeloEnElCable(e.model),max_tokens:e.maxOutputTokens??
309
- this.opts.defaultMaxOutputTokens??4096,messages:r};n.length>0&&(d.system=n),e.temperature!=null&&(d.temperature=e.temperature),a.length>0&&(d.tools=a),c?d.tool_choice={type:"tool",name:Le}:l&&(d.tool_choice=
310
- {type:"any"}),e.deferrable===true&&F("anthropic-sin-tier-diferible","[bvsala] This request was declared deferrable, but the Anthropic Messages API has NO cheaper synchronous tier: its `service_tier` cho\
381
+ this.opts.defaultMaxOutputTokens??4096,messages:r};n.length>0&&(d.system=n),e.temperature!=null&&(d.temperature=e.temperature),a.length>0&&(d.tools=a),u?d.tool_choice={type:"tool",name:Ze}:l&&(d.tool_choice=
382
+ {type:"any"}),e.deferrable===true&&V("anthropic-sin-tier-diferible","[bvsala] This request was declared deferrable, but the Anthropic Messages API has NO cheaper synchronous tier: its `service_tier` cho\
311
383
  oses between priority capacity (more expensive) and standard, not a flex. The request goes out unchanged and the report credits no discount. The 50% for deferring exists in the Message Batches API, wh\
312
- ich is asynchronous and does not fit a request/response call.");let m=this.marcarCache(e,n,r,o,s);return this.opts.automaticCache===true&&e.stablePrefixMessages!=null&&m<Math.min(this.opts.maxCacheBreakpoints??
313
- sn,sn)&&(d.cache_control={type:"ephemeral"}),{body:d,contratoNativo:c,turnoAnadido:i,esquemaPorPrompt:u}}marcarCache(e,n,r,o,s){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return 0;let i=Math.
314
- min(this.opts.maxCacheBreakpoints??sn,sn);if(i<=0)return 0;let a=i,c=s>0?n[s-1]:void 0;if(c&&(c.cache_control={type:"ephemeral"},i-=1),i>0&&o>0){let u=r[Math.min(o,r.length)-1],l=u?.content[u.content.
315
- length-1];l&&(l.cache_control={type:"ephemeral"},i-=1);}return a-i}async leer(e,n,r,o,s){let i=await e.json(),a=i.content??[],c=a.some(k=>fs(k.type)),u=a.filter(k=>k.type==="text").map(k=>k.text??"").join(
316
- ""),l=a.filter(k=>k.type==="tool_use"&&k.name!==Le).map(k=>({...k.id?{id:k.id}:{},name:k.name??"",arguments:JSON.stringify(k.input??{})})).filter(k=>k.name!==""),d=a.find(k=>k.type==="tool_use"&&k.name===
317
- Le),m=d?JSON.stringify(d.input??{}):u,f=i.usage??{},h=f.cache_read_input_tokens,g=f.cache_creation_input_tokens,p=(f.input_tokens??0)+(g??0)+(h??0),v=f.output_tokens??0,b=typeof f.input_tokens!="numbe\
318
- r",x=typeof f.output_tokens!="number";if(this.opts.requireUsage&&(b||x))throw new Error(gs(f.input_tokens,f.output_tokens));let y=typeof f.service_tier=="string"&&f.service_tier!==""?f.service_tier:void 0;
319
- return We({text:m,...l.length>0?{toolCalls:l}:{},...i.stop_reason?{finishReason:ms(i.stop_reason)}:{},...y?{servedServiceTier:y}:{},usage:{inputTokens:p,outputTokens:v,...h!=null?{cachedInputTokens:h}:
320
- {},...g!=null?{cacheWriteInputTokens:g}:{},...c||x?{}:{reasoningTokens:0},...b||x?{complete:false}:{}},structuredNatively:n.schema!=null&&r,raw:i},{...gt((o?1:0)+Je(n.tools)),esquemaPorPrompt:s})}};function Cc(t){
321
- let e=[],n=[],r=t.stablePrefixMessages??0,o=0,s=0,i=true;t.messages.forEach((c,u)=>{if(c.role==="system"&&i){e.push({type:"text",text:c.content}),u<r&&(s=e.length);return}i=false,n.push({role:c.role==="ass\
322
- istant"?"assistant":"user",content:[{type:"text",text:c.content}]}),u<r&&(o=n.length);});let a=false;return n.length>0&&n[0].role==="assistant"&&(n.unshift({role:"user",content:[{type:"text",text:"(contin\
323
- ue)"}]}),o>0&&(o+=1),a=true),{system:e,messages:n,prefijoEnMensajes:o,prefijoEnSystem:s,turnoAnadido:a}}function fs(t){return t==="thinking"||t==="redacted_thinking"}function ms(t){switch(t){case "end_tu\
324
- rn":return "stop";case "max_tokens":return "length";case "tool_use":return "tool_calls";case "refusal":return "content_filter";default:return t}}function hs(t,e){let n=Object.fromEntries(Object.entries(e??{}).
325
- filter(([,o])=>o!=null)),r=t?.cache_creation||e?.cache_creation?{...t?.cache_creation??{},...e?.cache_creation??{}}:void 0;return {...t??{},...n,...r?{cache_creation:r}:{}}}function Ic(t){try{return JSON.
326
- stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function gs(t,e){return `provider returned incomplete usage (input=${t??"absent"}, output=${e??"absent"}); cannot measure cost.`}async function bs(t){
327
- try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}var bt=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.
328
- now()-this.start}all(){return this.events}};var Ce=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function mr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function an(t,e=""){if(typeof t!="number"){let n=e&&
329
- `"${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 ne(t,e,n=""){
330
- let r=mr(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){let i=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`,u=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(u):
331
- new TypeError(u)}return t}function hr(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 ys(t,e){ne(t,void 0,"digestInt\
332
- o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function vt(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function cn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var xs=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",_c=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function un(t){if(ne(t),xs)return t.toHex();
333
- let e="";for(let n=0;n<t.length;n++)e+=_c[t[n]];return e}var ve={_0:48,_9:57,A:65,F:70,a:97,f:102};function vs(t){if(t>=ve._0&&t<=ve._9)return t-ve._0;if(t>=ve.A&&t<=ve.F)return t-(ve.A-10);if(t>=ve.a&&
334
- t<=ve.f)return t-(ve.a-10)}function yt(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(xs)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?
335
- 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=vs(t.charCodeAt(
336
- s)),a=vs(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a;}return r}function gr(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];ne(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 ks(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 ws(t=32){
337
- an(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(
338
- `"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var Ss=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var ln=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=
339
- new Uint8Array(e),this.view=cn(this.buffer);}update(e){hr(this),ne(e);let{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=cn(e);for(;o<=s-i;i+=
340
- o)this.process(c,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){hr(this),
341
- ys(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;n[i++]=128,vt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let d=i;d<o;d++)n[d]=0;r.setBigUint64(
342
- o-8,BigInt(this.length*8),s),this.process(r,0);let a=cn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_s\
343
- ha2: outputLen bigger than state");for(let d=0;d<u;d++)a.setUint32(4*d,l[d],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.
344
- constructor,e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};var J=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var dn=BigInt(4294967295),Ts=BigInt(32);function Pc(t,e=false){return e?{h:Number(t&dn),l:Number(t>>Ts&dn)}:{h:Number(t>>Ts&dn)|0,l:Number(t&dn)|0}}function Es(t,e=false){let n=t.length,r=new Uint32Array(n),
345
- o=new Uint32Array(n);for(let s=0;s<n;s++){let{h:i,l:a}=Pc(t[s],e);[r[s],o[s]]=[i,a];}return [r,o]}var br=(t,e,n)=>t>>>n,vr=(t,e,n)=>t<<32-n|e>>>n,Ne=(t,e,n)=>t>>>n|e<<32-n,je=(t,e,n)=>t<<32-n|e>>>n,xt=(t,e,n)=>t<<64-n|e>>>n-32,kt=(t,e,n)=>t>>>n-32|e<<64-n;function ce(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var Rs=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Cs=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Is=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),_s=(t,e,n,r,o)=>e+
346
- n+r+o+(t/2**32|0)|0,Ps=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Ds=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0;var Os=Es(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
384
+ ich is asynchronous and does not fit a request/response call.");let f=this.marcarCache(e,n,r,o,i);return this.opts.automaticCache===true&&e.stablePrefixMessages!=null&&f<Math.min(this.opts.maxCacheBreakpoints??
385
+ Fn,Fn)&&(d.cache_control={type:"ephemeral"}),{body:d,contratoNativo:u,turnoAnadido:s,esquemaPorPrompt:c}}marcarCache(e,n,r,o,i){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return 0;let s=Math.
386
+ min(this.opts.maxCacheBreakpoints??Fn,Fn);if(s<=0)return 0;let a=s,u=i>0?n[i-1]:void 0;if(u&&(u.cache_control={type:"ephemeral"},s-=1),s>0&&o>0){let c=r[Math.min(o,r.length)-1],l=c?.content[c.content.
387
+ length-1];l&&(l.cache_control={type:"ephemeral"},s-=1);}return a-s}async leer(e,n,r,o,i){let s=await e.json(),a=s.content??[],u=a.some(g=>ao(g.type)),c=a.filter(g=>g.type==="text").map(g=>g.text??"").join(
388
+ ""),l=a.filter(g=>g.type==="tool_use"&&g.name!==Ze).map(g=>({...g.id?{id:g.id}:{},name:g.name??"",arguments:JSON.stringify(g.input??{})})).filter(g=>g.name!==""),d=a.find(g=>g.type==="tool_use"&&g.name===
389
+ Ze),f=d?JSON.stringify(d.input??{}):c,m=s.usage,{usage:h,entradaAusente:b,salidaAusente:p}=oo(m,m?.output_tokens,u);if(this.opts.requireUsage&&(b||p))throw new Error(Is(m?.input_tokens,m?.output_tokens));
390
+ let v=io(m);return gt({text:f,...l.length>0?{toolCalls:l}:{},...s.stop_reason?{finishReason:co(s.stop_reason)}:{},...v?{servedServiceTier:v}:{},usage:h,structuredNatively:n.schema!=null&&r,raw:s},{...qt(
391
+ (o?1:0)+ht(n.tools)),esquemaPorPrompt:i})}};function ml(t){let e=[],n=[],r=t.stablePrefixMessages??0,o=0,i=0,s=true;t.messages.forEach((u,c)=>{if(u.role==="system"&&s){e.push({type:"text",text:u.content}),
392
+ c<r&&(i=e.length);return}s=false,n.push({role:u.role==="assistant"?"assistant":"user",content:[{type:"text",text:u.content}]}),c<r&&(o=n.length);});let a=false;return n.length>0&&n[0].role==="assistant"&&(n.
393
+ unshift({role:"user",content:[{type:"text",text:"(continue)"}]}),o>0&&(o+=1),a=true),{system:e,messages:n,prefijoEnMensajes:o,prefijoEnSystem:i,turnoAnadido:a}}function hl(t){try{return JSON.stringify(JSON.
394
+ parse(t===""?"{}":t))}catch{return t}}function Is(t,e){return `provider returned incomplete usage (input=${t??"absent"}, output=${e??"absent"}); cannot measure cost.`}async function Ps(t){try{return (await t.
395
+ text()).slice(0,500)}catch{return "<no body>"}}var Wt=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.
396
+ now()-this.start}all(){return this.events}};var $e=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function uo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Bn(t,e=""){if(typeof t!="number"){let n=e&&
397
+ `"${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 he(t,e,n=""){
398
+ let r=uo(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",u=r?`length=${o}`:`type=${typeof t}`,c=s+"expected Uint8Array"+a+", got "+u;throw r?new RangeError(c):
399
+ new TypeError(c)}return t}function lo(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 Ds(t,e){he(t,void 0,"digestInt\
400
+ o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function Kt(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function zn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Os=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",gl=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Vn(t){if(he(t),Os)return t.toHex();
401
+ let e="";for(let n=0;n<t.length;n++)e+=gl[t[n]];return e}var Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function _s(t){if(t>=Ee._0&&t<=Ee._9)return t-Ee._0;if(t>=Ee.A&&t<=Ee.F)return t-(Ee.A-10);if(t>=Ee.a&&
402
+ t<=Ee.f)return t-(Ee.a-10)}function Gt(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Os)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?
403
+ 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,i=0;o<n;o++,i+=2){let s=_s(t.charCodeAt(
404
+ i)),a=_s(t.charCodeAt(i+1));if(s===void 0||a===void 0){let u=t[i]+t[i+1];throw new RangeError('hex string expected, got non-hex character "'+u+'" at index '+i)}r[o]=s*16+a;}return r}function po(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];he(o),e+=o.length;}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let i=t[r];n.set(i,o),o+=i.length;}return n}function As(t,e={}){let n=(o,i)=>t(i).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 Ms(t=32){
405
+ Bn(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(
406
+ `"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var Ls=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var Un=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=
407
+ new Uint8Array(e),this.view=zn(this.buffer);}update(e){lo(this),he(e);let{view:n,buffer:r,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let u=zn(e);for(;o<=i-s;s+=
408
+ o)this.process(u,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){lo(this),
409
+ Ds(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,Kt(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let d=s;d<o;d++)n[d]=0;r.setBigUint64(
410
+ o-8,BigInt(this.length*8),i),this.process(r,0);let a=zn(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=u/4,l=this.get();if(c>l.length)throw new Error("_s\
411
+ ha2: outputLen bigger than state");for(let d=0;d<c;d++)a.setUint32(4*d,l[d],i);}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.
412
+ constructor,e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};var G=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var qn=BigInt(4294967295),Ns=BigInt(32);function bl(t,e=false){return e?{h:Number(t&qn),l:Number(t>>Ns&qn)}:{h:Number(t>>Ns&qn)|0,l:Number(t&qn)|0}}function js(t,e=false){let n=t.length,r=new Uint32Array(n),
413
+ o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=bl(t[i],e);[r[i],o[i]]=[s,a];}return [r,o]}var fo=(t,e,n)=>t>>>n,mo=(t,e,n)=>t<<32-n|e>>>n,Xe=(t,e,n)=>t>>>n|e<<32-n,Qe=(t,e,n)=>t<<32-n|e>>>n,Jt=(t,e,n)=>t<<64-n|e>>>n-32,Yt=(t,e,n)=>t>>>n-32|e<<64-n;function ye(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var $s=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Fs=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Bs=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),zs=(t,e,n,r,o)=>e+
414
+ n+r+o+(t/2**32|0)|0,Vs=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Us=(t,e,n,r,o,i)=>e+n+r+o+i+(t/2**32|0)|0;var qs=js(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
347
415
  "0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
348
416
  8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
349
417
  0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
@@ -351,158 +419,158 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
351
419
  x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
352
420
  efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
353
421
  eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
354
- 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Oc=Os[0],Ac=Os[1],Ie=new Uint32Array(80),_e=new Uint32Array(80),yr=class extends ln{constructor(e){
355
- super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:d,Fl:m,Gh:f,Gl:h,Hh:g,Hl:p}=this;return [e,n,r,o,s,i,a,c,u,l,d,m,f,h,g,p]}set(e,n,r,o,s,i,a,c,u,l,d,m,f,h,g,p){this.Ah=
356
- e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=d|0,this.Fl=m|0,this.Gh=f|0,this.Gl=h|0,this.Hh=g|0,this.Hl=p|0;}process(e,n){for(let x=0;x<
357
- 16;x++,n+=4)Ie[x]=e.getUint32(n),_e[x]=e.getUint32(n+=4);for(let x=16;x<80;x++){let y=Ie[x-15]|0,k=_e[x-15]|0,E=Ne(y,k,1)^Ne(y,k,8)^br(y,k,7),w=je(y,k,1)^je(y,k,8)^vr(y,k,7),I=Ie[x-2]|0,O=_e[x-2]|0,C=Ne(
358
- I,O,19)^xt(I,O,61)^br(I,O,6),_=je(I,O,19)^kt(I,O,61)^vr(I,O,6),T=Is(w,_,_e[x-7],_e[x-16]),R=_s(T,E,C,Ie[x-7],Ie[x-16]);Ie[x]=R|0,_e[x]=T|0;}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:d,El:m,Fh:f,Fl:h,
359
- Gh:g,Gl:p,Hh:v,Hl:b}=this;for(let x=0;x<80;x++){let y=Ne(d,m,14)^Ne(d,m,18)^xt(d,m,41),k=je(d,m,14)^je(d,m,18)^kt(d,m,41),E=d&f^~d&g,w=m&h^~m&p,I=Ps(b,k,w,Ac[x],_e[x]),O=Ds(I,v,y,E,Oc[x],Ie[x]),C=I|0,
360
- _=Ne(r,o,28)^xt(r,o,34)^xt(r,o,39),T=je(r,o,28)^kt(r,o,34)^kt(r,o,39),R=r&s^r&a^s&a,D=o&i^o&c^i&c;v=g|0,b=p|0,g=f|0,p=h|0,f=d|0,h=m|0,{h:d,l:m}=ce(u|0,l|0,O|0,C|0),u=a|0,l=c|0,a=s|0,c=i|0,s=r|0,i=o|0;
361
- let M=Rs(C,T,D);r=Cs(M,O,_,R),o=M|0;}(({h:r,l:o}=ce(this.Ah|0,this.Al|0,r|0,o|0))),{h:s,l:i}=ce(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ce(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=ce(this.Dh|0,this.Dl|0,u|0,l|
362
- 0),{h:d,l:m}=ce(this.Eh|0,this.El|0,d|0,m|0),{h:f,l:h}=ce(this.Fh|0,this.Fl|0,f|0,h|0),{h:g,l:p}=ce(this.Gh|0,this.Gl|0,g|0,p|0),{h:v,l:b}=ce(this.Hh|0,this.Hl|0,v|0,b|0),this.set(r,o,s,i,a,c,u,l,d,m,
363
- f,h,g,p,v,b);}roundClean(){vt(Ie,_e);}destroy(){this.destroyed=true,vt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},xr=class extends yr{Ah=J[0]|0;Al=J[1]|0;Bh=J[2]|0;Bl=J[3]|0;Ch=J[4]|0;Cl=J[5]|
364
- 0;Dh=J[6]|0;Dl=J[7]|0;Eh=J[8]|0;El=J[9]|0;Fh=J[10]|0;Fl=J[11]|0;Gh=J[12]|0;Gl=J[13]|0;Hh=J[14]|0;Hl=J[15]|0;constructor(){super(64);}};var pn=ks(()=>new xr,Ss(3));var U=(t,e,n)=>ne(t,e,n),wr=an,Sr=un,ue=(...t)=>gr(...t),As=t=>yt(t),hn=mr,Ms=t=>ws(t),mn=BigInt(0),kr=BigInt(1);function Ge(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"e\
365
- xpected boolean, got type="+typeof t)}return t}function Mc(t){if(typeof t=="bigint"){if(!fn(t))throw new RangeError("positive bigint expected, got "+t)}else wr(t);return t}function ye(t,e=""){if(typeof t!=
366
- "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 Ls(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?mn:BigInt("0x"+t)}function Tr(t){return Ls(un(t))}function xe(t){return Ls(un(wt(ne(t)).reverse()))}
367
- function Er(t,e){if(an(e),e===0)throw new RangeError("zero length");t=Mc(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return yt(n.padStart(e*2,"0"))}function Ns(t,e){
368
- return Er(t,e).reverse()}function js(t,e){if(t=U(t),e=U(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 wt(t){return Uint8Array.from(U(t))}var fn=t=>typeof t=="bigint"&&mn<=t;function Lc(t,e,n){return fn(t)&&fn(e)&&fn(n)&&e<=t&&t<n}function Rr(t,e,n,r){if(!Lc(e,n,r))throw new RangeError(
369
- "expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Cr(t){if(t<mn)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>mn;t>>=kr,e+=1);return e}var Bs=t=>(kr<<BigInt(t))-kr;function Be(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function r(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(
370
- `param "${s}" is invalid: expected own property`);let c=t[s];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${u}`)}let o=(s,i)=>Object.
371
- entries(s).forEach(([a,c])=>r(a,c,i));o(e,false),o(n,true);}var Ir=()=>{throw new Error("not implemented")};var W=BigInt(0),H=BigInt(1),Fe=BigInt(2),Vs=BigInt(3),Us=BigInt(4),qs=BigInt(5),Nc=BigInt(7),Hs=BigInt(8),jc=BigInt(9),Ks=BigInt(16);function z(t,e){if(e<=W)throw new Error("mod: expected positive mod\
372
- ulus, got "+e);let n=t%e;return n>=W?n:e+n}function re(t,e,n){if(e<W)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >W;)r*=r,r%=n;return r}function Fs(t,e){if(t===W)throw new Error("invert: expected non-zero n\
373
- umber");if(e<=W)throw new Error("invert: expected positive modulus, got "+e);let n=z(t,e),r=e,o=W,i=H;for(;n!==W;){let u=r/n,l=r-n*u,d=o-i*u;r=n,n=l,o=i,i=d;}if(r!==H)throw new Error(
374
- "invert: does not exist");return z(o,e)}function _r(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function Js(t,e){let n=t,r=(n.ORDER+H)/Us,o=n.pow(e,r);return _r(n,o,
375
- e),o}function Bc(t,e){let n=t,r=(n.ORDER-qs)/Hs,o=n.mul(e,Fe),s=n.pow(o,r),i=n.mul(e,s),a=n.mul(n.mul(i,Fe),s),c=n.mul(i,n.sub(a,n.ONE));return _r(n,c,e),c}function Fc(t){let e=yn(t),n=Ws(t),r=n(e,e.neg(
376
- e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+Nc)/Ks;return((a,c)=>{let u=a,l=u.pow(c,i),d=u.mul(l,r),m=u.mul(l,o),f=u.mul(l,s),h=u.eql(u.sqr(d),c),g=u.eql(u.sqr(m),c);l=u.cmov(l,d,h),d=u.cmov(f,m,g);let p=u.
377
- eql(u.sqr(d),c),v=u.cmov(l,d,p);return _r(u,v,c),v})}function Ws(t){if(t<Vs)throw new Error("sqrt is not defined for small field");let e=t-H,n=0;for(;e%Fe===W;)e/=Fe,n++;let r=Fe,o=yn(t);for(;zs(o,r)===
378
- 1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Js;let s=o.pow(r,e),i=(e+H)/Fe;return function(c,u){let l=c;if(l.is0(u))return u;if(zs(l,u)!==1)throw new Error(
379
- "Cannot find square root");let d=n,m=l.mul(l.ONE,s),f=l.pow(u,e),h=l.pow(u,i);for(;!l.eql(f,l.ONE);){if(l.is0(f))return l.ZERO;let g=1,p=l.sqr(f);for(;!l.eql(p,l.ONE);)if(g++,p=l.sqr(p),g===d)throw new Error(
380
- "Cannot find square root");let v=H<<BigInt(d-g-1),b=l.pow(m,v);d=g,m=l.sqr(b),f=l.mul(f,m),h=l.mul(h,b);}return h}}function zc(t){return t%Us===Vs?Js:t%Hs===qs?Bc:t%Ks===jc?Fc(t):Ws(t)}var ke=(t,e)=>(z(
381
- t,e)&H)===H,$c=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Gs(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=$c.
382
- reduce((r,o)=>(r[o]="function",r),e);if(Be(t,n),ye(t.BYTES,"BYTES"),ye(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=H)throw new Error("inval\
383
- id field: expected ORDER > 1, got "+t.ORDER);return t}function Vc(t,e,n){let r=t;if(n<W)throw new Error("invalid exponent, negatives unsupported");if(n===W)return r.ONE;if(n===H)return e;let o=r.ONE,s=e;
384
- for(;n>W;)n&H&&(o=r.mul(o,s)),s=r.sqr(s),n>>=H;return o}function vn(t,e,n=false){let r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),s=e.reduce((a,c,u)=>r.is0(c)?a:(o[u]=a,r.mul(a,c)),r.ONE),i=r.inv(s);return e.
385
- reduceRight((a,c,u)=>r.is0(c)?a:(o[u]=r.mul(a,o[u]),r.mul(a,c)),i),o}function zs(t,e){let n=t,r=(n.ORDER-H)/Fe,o=n.pow(e,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Uc(t,e){if(e!==void 0&&wr(e),t<=W)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);
386
- let n=Cr(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 $s=new WeakMap,
387
- bn=class{ORDER;BITS;BYTES;isLE;ZERO=W;ONE=H;_lengths;_mod;constructor(e,n={}){if(e<=H)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
422
+ 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),yl=qs[0],kl=qs[1],Fe=new Uint32Array(80),Be=new Uint32Array(80),ho=class extends Un{constructor(e){
423
+ super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:u,Eh:c,El:l,Fh:d,Fl:f,Gh:m,Gl:h,Hh:b,Hl:p}=this;return [e,n,r,o,i,s,a,u,c,l,d,f,m,h,b,p]}set(e,n,r,o,i,s,a,u,c,l,d,f,m,h,b,p){this.Ah=
424
+ e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=u|0,this.Eh=c|0,this.El=l|0,this.Fh=d|0,this.Fl=f|0,this.Gh=m|0,this.Gl=h|0,this.Hh=b|0,this.Hl=p|0;}process(e,n){for(let y=0;y<
425
+ 16;y++,n+=4)Fe[y]=e.getUint32(n),Be[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){let k=Fe[y-15]|0,x=Be[y-15]|0,T=Xe(k,x,1)^Xe(k,x,8)^fo(k,x,7),w=Qe(k,x,1)^Qe(k,x,8)^mo(k,x,7),R=Fe[y-2]|0,D=Be[y-2]|0,O=Xe(
426
+ R,D,19)^Jt(R,D,61)^fo(R,D,6),_=Qe(R,D,19)^Yt(R,D,61)^mo(R,D,6),S=Bs(w,_,Be[y-7],Be[y-16]),C=zs(S,T,O,Fe[y-7],Fe[y-16]);Fe[y]=C|0,Be[y]=S|0;}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:u,Dh:c,Dl:l,Eh:d,El:f,Fh:m,Fl:h,
427
+ Gh:b,Gl:p,Hh:v,Hl:g}=this;for(let y=0;y<80;y++){let k=Xe(d,f,14)^Xe(d,f,18)^Jt(d,f,41),x=Qe(d,f,14)^Qe(d,f,18)^Yt(d,f,41),T=d&m^~d&b,w=f&h^~f&p,R=Vs(g,x,w,kl[y],Be[y]),D=Us(R,v,k,T,yl[y],Fe[y]),O=R|0,
428
+ _=Xe(r,o,28)^Jt(r,o,34)^Jt(r,o,39),S=Qe(r,o,28)^Yt(r,o,34)^Yt(r,o,39),C=r&i^r&a^i&a,P=o&s^o&u^s&u;v=b|0,g=p|0,b=m|0,p=h|0,m=d|0,h=f|0,{h:d,l:f}=ye(c|0,l|0,D|0,O|0),c=a|0,l=u|0,a=i|0,u=s|0,i=r|0,s=o|0;
429
+ let A=$s(O,S,P);r=Fs(A,D,_,C),o=A|0;}(({h:r,l:o}=ye(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=ye(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:u}=ye(this.Ch|0,this.Cl|0,a|0,u|0),{h:c,l}=ye(this.Dh|0,this.Dl|0,c|0,l|
430
+ 0),{h:d,l:f}=ye(this.Eh|0,this.El|0,d|0,f|0),{h:m,l:h}=ye(this.Fh|0,this.Fl|0,m|0,h|0),{h:b,l:p}=ye(this.Gh|0,this.Gl|0,b|0,p|0),{h:v,l:g}=ye(this.Hh|0,this.Hl|0,v|0,g|0),this.set(r,o,i,s,a,u,c,l,d,f,
431
+ m,h,b,p,v,g);}roundClean(){Kt(Fe,Be);}destroy(){this.destroyed=true,Kt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},go=class extends ho{Ah=G[0]|0;Al=G[1]|0;Bh=G[2]|0;Bl=G[3]|0;Ch=G[4]|0;Cl=G[5]|
432
+ 0;Dh=G[6]|0;Dl=G[7]|0;Eh=G[8]|0;El=G[9]|0;Fh=G[10]|0;Fl=G[11]|0;Gh=G[12]|0;Gl=G[13]|0;Hh=G[14]|0;Hl=G[15]|0;constructor(){super(64);}};var Hn=As(()=>new go,Ls(3));var q=(t,e,n)=>he(t,e,n),vo=Bn,yo=Vn,ke=(...t)=>po(...t),Hs=t=>Gt(t),Gn=uo,Ws=t=>Ms(t),Kn=BigInt(0),bo=BigInt(1);function vt(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"e\
433
+ xpected boolean, got type="+typeof t)}return t}function xl(t){if(typeof t=="bigint"){if(!Wn(t))throw new RangeError("positive bigint expected, got "+t)}else vo(t);return t}function Re(t,e=""){if(typeof t!=
434
+ "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 Ks(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Kn:BigInt("0x"+t)}function ko(t){return Ks(Vn(t))}function Ce(t){return Ks(Vn(Zt(he(t)).reverse()))}
435
+ function xo(t,e){if(Bn(e),e===0)throw new RangeError("zero length");t=xl(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return Gt(n.padStart(e*2,"0"))}function Gs(t,e){
436
+ return xo(t,e).reverse()}function Js(t,e){if(t=q(t),e=q(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 Zt(t){return Uint8Array.from(q(t))}var Wn=t=>typeof t=="bigint"&&Kn<=t;function wl(t,e,n){return Wn(t)&&Wn(e)&&Wn(n)&&e<=t&&t<n}function wo(t,e,n,r){if(!wl(e,n,r))throw new RangeError(
437
+ "expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function So(t){if(t<Kn)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>Kn;t>>=bo,e+=1);return e}var Ys=t=>(bo<<BigInt(t))-bo;function et(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function r(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(t,i))throw new TypeError(
438
+ `param "${i}" is invalid: expected own property`);let u=t[i];if(a&&u===void 0)return;let c=typeof u;if(c!==s||u===null)throw new TypeError(`param "${i}" is invalid: expected ${s}, got ${c}`)}let o=(i,s)=>Object.
439
+ entries(i).forEach(([a,u])=>r(a,u,s));o(e,false),o(n,true);}var To=()=>{throw new Error("not implemented")};var J=BigInt(0),W=BigInt(1),tt=BigInt(2),ea=BigInt(3),ta=BigInt(4),na=BigInt(5),Sl=BigInt(7),ra=BigInt(8),Tl=BigInt(9),oa=BigInt(16);function U(t,e){if(e<=J)throw new Error("mod: expected positive mod\
440
+ ulus, got "+e);let n=t%e;return n>=J?n:e+n}function ge(t,e,n){if(e<J)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >J;)r*=r,r%=n;return r}function Zs(t,e){if(t===J)throw new Error("invert: expected non-zero n\
441
+ umber");if(e<=J)throw new Error("invert: expected positive modulus, got "+e);let n=U(t,e),r=e,o=J,s=W;for(;n!==J;){let c=r/n,l=r-n*c,d=o-s*c;r=n,n=l,o=s,s=d;}if(r!==W)throw new Error(
442
+ "invert: does not exist");return U(o,e)}function Eo(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function ia(t,e){let n=t,r=(n.ORDER+W)/ta,o=n.pow(e,r);return Eo(n,o,
443
+ e),o}function El(t,e){let n=t,r=(n.ORDER-na)/ra,o=n.mul(e,tt),i=n.pow(o,r),s=n.mul(e,i),a=n.mul(n.mul(s,tt),i),u=n.mul(s,n.sub(a,n.ONE));return Eo(n,u,e),u}function Rl(t){let e=Xn(t),n=sa(t),r=n(e,e.neg(
444
+ e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+Sl)/oa;return((a,u)=>{let c=a,l=c.pow(u,s),d=c.mul(l,r),f=c.mul(l,o),m=c.mul(l,i),h=c.eql(c.sqr(d),u),b=c.eql(c.sqr(f),u);l=c.cmov(l,d,h),d=c.cmov(m,f,b);let p=c.
445
+ eql(c.sqr(d),u),v=c.cmov(l,d,p);return Eo(c,v,u),v})}function sa(t){if(t<ea)throw new Error("sqrt is not defined for small field");let e=t-W,n=0;for(;e%tt===J;)e/=tt,n++;let r=tt,o=Xn(t);for(;Xs(o,r)===
446
+ 1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return ia;let i=o.pow(r,e),s=(e+W)/tt;return function(u,c){let l=u;if(l.is0(c))return c;if(Xs(l,c)!==1)throw new Error(
447
+ "Cannot find square root");let d=n,f=l.mul(l.ONE,i),m=l.pow(c,e),h=l.pow(c,s);for(;!l.eql(m,l.ONE);){if(l.is0(m))return l.ZERO;let b=1,p=l.sqr(m);for(;!l.eql(p,l.ONE);)if(b++,p=l.sqr(p),b===d)throw new Error(
448
+ "Cannot find square root");let v=W<<BigInt(d-b-1),g=l.pow(f,v);d=b,f=l.sqr(g),m=l.mul(m,f),h=l.mul(h,g);}return h}}function Cl(t){return t%ta===ea?ia:t%ra===na?El:t%oa===Tl?Rl(t):sa(t)}var Ie=(t,e)=>(U(
449
+ t,e)&W)===W,Il=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function aa(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=Il.
450
+ reduce((r,o)=>(r[o]="function",r),e);if(et(t,n),Re(t.BYTES,"BYTES"),Re(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=W)throw new Error("inval\
451
+ id field: expected ORDER > 1, got "+t.ORDER);return t}function Pl(t,e,n){let r=t;if(n<J)throw new Error("invalid exponent, negatives unsupported");if(n===J)return r.ONE;if(n===W)return e;let o=r.ONE,i=e;
452
+ for(;n>J;)n&W&&(o=r.mul(o,i)),i=r.sqr(i),n>>=W;return o}function Zn(t,e,n=false){let r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),i=e.reduce((a,u,c)=>r.is0(u)?a:(o[c]=a,r.mul(a,u)),r.ONE),s=r.inv(i);return e.
453
+ reduceRight((a,u,c)=>r.is0(u)?a:(o[c]=r.mul(a,o[c]),r.mul(a,u)),s),o}function Xs(t,e){let n=t,r=(n.ORDER-W)/tt,o=n.pow(e,r),i=n.eql(o,n.ONE),s=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function _l(t,e){if(e!==void 0&&vo(e),t<=J)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);
454
+ let n=So(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 Qs=new WeakMap,
455
+ Yn=class{ORDER;BITS;BYTES;isLE;ZERO=J;ONE=W;_lengths;_mod;constructor(e,n={}){if(e<=W)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
388
456
  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.
389
- freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:s}=Uc(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2\
390
- 048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this);}create(e){return z(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got\
391
- "+typeof e);return W<=e&&e<this.ORDER}is0(e){return e===W}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&H)===H}neg(e){return z(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return z(
392
- e*e,this.ORDER)}add(e,n){return z(e+n,this.ORDER)}sub(e,n){return z(e-n,this.ORDER)}mul(e,n){return z(e*n,this.ORDER)}pow(e,n){return Vc(this,e,n)}div(e,n){return z(e*Fs(n,this.ORDER),this.ORDER)}sqrN(e){
393
- return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Fs(e,this.ORDER)}sqrt(e){let n=$s.get(this);return n||$s.set(this,n=zc(this.ORDER)),n(this,e)}toBytes(e){return this.
394
- isLE?Ns(e,this.BYTES):Er(e,this.BYTES)}fromBytes(e,n=false){U(e);let{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes\
395
- : expected "+r+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?xe(e):
396
- Tr(e);if(a&&(c=z(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return vn(this,e)}cmov(e,n,r){return Ge(r,"condition"),r?n:e}};Object.
397
- freeze(bn.prototype);function yn(t,e={}){return new bn(t,e)}var xn=BigInt(0),Ar=BigInt(1);function Ys(t,e){let n=e.negate();return t?n:e}function wn(t,e){let n=vn(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function ei(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
398
- throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Pr(t,e){ei(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=Bs(t),i=BigInt(t);return {windows:n,windowSize:r,mask:s,maxNumber:o,
399
- shiftBy:i}}function Zs(t,e,n){let{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n,a=Number(t&o),c=t>>i;a>r&&(a-=s,c+=Ar);let u=e*r,l=u+Math.abs(a)-1,d=a===0,m=a<0,f=e%2!==0;return {nextN:c,offset:l,isZero:d,
400
- isNeg:m,isNegF:f,offsetF:u}}var Dr=new WeakMap,ti=new WeakMap;function Or(t){return ti.get(t)||1}function Xs(t){if(t!==xn)throw new Error("invalid wNAF")}var kn=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
401
- e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>xn;)n&Ar&&(r=r.add(o)),o=o.double(),n>>=Ar;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Pr(n,this.bits),s=[],
402
- i=e,a=i;for(let c=0;c<r;c++){a=i,s.push(a);for(let u=1;u<o;u++)a=a.add(i),s.push(a);i=a.double();}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,
403
- i=Pr(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:m,offsetF:f}=Zs(r,a,i);r=c,l?s=s.add(Ys(m,n[f])):o=o.add(Ys(d,n[u]));}return Xs(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.
404
- ZERO){let s=Pr(e,this.bits);for(let i=0;i<s.windows&&r!==xn;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=Zs(r,i,s);if(r=a,!u){let d=n[c];o=o.add(l?d.negate():d);}}return Xs(r),o}getPrecomputes(e,n,r){let o=Dr.
405
- get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Dr.set(n,o))),o}cached(e,n,r){let o=Or(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let s=Or(
406
- e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){ei(n,this.bits),ti.set(e,n),Dr.delete(e);}hasCache(e){return Or(e)!==1}};function Qs(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Gs(e),e}else return yn(t,{isLE:n})}function ni(t,e,n={},r){if(r===void 0&&(r=t==="edwar\
407
- ds"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of ["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>xn))throw new Error(`CURVE.${c} must be positive bigint`)}
408
- let o=Qs(e.p,n.Fp,r),s=Qs(e.n,n.Fn,r),a=["Gx","Gy","a","d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.
409
- freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function ri(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var Pe=BigInt(0),K=BigInt(1),Mr=BigInt(2),qc=BigInt(8);function Hc(t,e,n,r){let o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function oi(t,e={}){
410
- let n=e,r=ni("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r,i=r.CURVE,{h:a}=i;Be(n,{},{uvRatio:"function"});let c=Mr<<BigInt(s.BYTES*8)-K,u=g=>o.create(g),l=n.uvRatio===void 0?(g,p)=>{try{return {isValid:!0,value:o.
411
- sqrt(o.div(g,p))}}catch{return {isValid:false,value:Pe}}}:n.uvRatio;if(!Hc(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(g,p,v=false){let b=v?K:Pe;return Rr("coordinate "+g,p,
412
- b,c),p}function m(g){if(!(g instanceof f))throw new Error("EdwardsPoint expected")}class f{static BASE=new f(i.Gx,i.Gy,K,u(i.Gx*i.Gy));static ZERO=new f(Pe,K,K,Pe);static Fp=o;static Fn=s;X;Y;Z;T;constructor(p,v,b,x){
413
- this.X=d("x",p),this.Y=d("y",v),this.Z=d("z",b,true),this.T=d("t",x),Object.freeze(this);}static CURVE(){return i}static fromAffine(p){if(p instanceof f)throw new Error("extended point not allowed");let{
414
- x:v,y:b}=p||{};return d("x",v),d("y",b),new f(v,b,K,u(v*b))}static fromBytes(p,v=false){let b=o.BYTES,{a:x,d:y}=i;p=wt(U(p,b,"point")),Ge(v,"zip215");let k=wt(p),E=p[b-1];k[b-1]=E&-129;let w=xe(k),I=v?c:
415
- o.ORDER;Rr("point.y",w,Pe,I);let O=u(w*w),C=u(O-K),_=u(y*O-x),{isValid:T,value:R}=l(C,_);if(!T)throw new Error("bad point: invalid y coordinate");let D=(R&K)===K,M=(E&128)!==0;if(!v&&R===Pe&&M)throw new Error(
416
- "bad point: x=0 and x_0=1");return M!==D&&(R=u(-R)),f.fromAffine({x:R,y:w})}static fromHex(p,v=false){return f.fromBytes(As(p),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,v=true){
417
- return h.createCache(this,p),v||this.multiply(Mr),this}assertValidity(){let p=this,{a:v,d:b}=i;if(p.is0())throw new Error("bad point: ZERO");let{X:x,Y:y,Z:k,T:E}=p,w=u(x*x),I=u(y*y),O=u(k*k),C=u(O*O),
418
- _=u(w*v),T=u(O*u(_+I)),R=u(C+u(b*u(w*I)));if(T!==R)throw new Error("bad point: equation left != right (1)");let D=u(x*y),M=u(k*E);if(D!==M)throw new Error("bad point: equation left != right (2)")}equals(p){
419
- m(p);let{X:v,Y:b,Z:x}=this,{X:y,Y:k,Z:E}=p,w=u(v*E),I=u(y*x),O=u(b*E),C=u(k*x);return w===I&&O===C}is0(){return this.equals(f.ZERO)}negate(){return new f(u(-this.X),this.Y,this.Z,u(-this.T))}double(){
420
- let{a:p}=i,{X:v,Y:b,Z:x}=this,y=u(v*v),k=u(b*b),E=u(Mr*u(x*x)),w=u(p*y),I=v+b,O=u(u(I*I)-y-k),C=w+k,_=C-E,T=w-k,R=u(O*_),D=u(C*T),M=u(O*T),j=u(_*C);return new f(R,D,j,M)}add(p){m(p);let{a:v,d:b}=i,{X:x,
421
- Y:y,Z:k,T:E}=this,{X:w,Y:I,Z:O,T:C}=p,_=u(x*w),T=u(y*I),R=u(E*b*C),D=u(k*O),M=u((x+y)*(w+I)-_-T),j=D-R,$=D+R,Y=u(T-v*_),oe=u(M*j),P=u($*Y),se=u(M*Y),B=u(j*$);return new f(oe,P,B,se)}subtract(p){return m(
422
- p),this.add(p.negate())}multiply(p){if(!s.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:b}=h.cached(this,p,x=>wn(f,x));return wn(f,[v,b])[0]}multiplyUnsafe(p){
423
- if(!s.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===Pe?f.ZERO:this.is0()||p===K?this:h.unsafe(this,p,v=>wn(f,v))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){
424
- return h.unsafe(this,i.n).is0()}toAffine(p){let v=this,b=p,{X:x,Y:y,Z:k}=v,E=v.is0();b==null&&(b=E?qc:o.inv(k));let w=u(x*b),I=u(y*b),O=o.mul(k,b);if(E)return {x:Pe,y:K};if(O!==K)throw new Error("invZ \
425
- was invalid");return {x:w,y:I}}clearCofactor(){return a===K?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y:v}=this.toAffine(),b=o.toBytes(v);return b[b.length-1]|=p&K?128:0,b}toHex(){return Sr(this.toBytes())}toString(){
426
- return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let h=new kn(f,s.BITS);return s.BITS>=8&&f.BASE.precompute(8),Object.freeze(f.prototype),Object.freeze(f),f}var Sn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){
427
- this.ep=e;}static fromBytes(e){Ir();}static fromHex(e){Ir();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){
428
- return this.ep.toAffine(e)}toHex(){return Sr(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){
457
+ freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=_l(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
458
+ 048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,Object.freeze(this);}create(e){return U(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got\
459
+ "+typeof e);return J<=e&&e<this.ORDER}is0(e){return e===J}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&W)===W}neg(e){return U(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return U(
460
+ e*e,this.ORDER)}add(e,n){return U(e+n,this.ORDER)}sub(e,n){return U(e-n,this.ORDER)}mul(e,n){return U(e*n,this.ORDER)}pow(e,n){return Pl(this,e,n)}div(e,n){return U(e*Zs(n,this.ORDER),this.ORDER)}sqrN(e){
461
+ return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Zs(e,this.ORDER)}sqrt(e){let n=Qs.get(this);return n||Qs.set(this,n=Cl(this.ORDER)),n(this,e)}toBytes(e){return this.
462
+ isLE?Gs(e,this.BYTES):xo(e,this.BYTES)}fromBytes(e,n=false){q(e);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes\
463
+ : expected "+r+" bytes, got "+e.length);let c=new Uint8Array(o);c.set(e,i?0:c.length-e.length),e=c;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let u=i?Ce(e):
464
+ ko(e);if(a&&(u=U(u,s)),!n&&!this.isValid(u))throw new Error("invalid field element: outside of range 0..ORDER");return u}invertBatch(e){return Zn(this,e)}cmov(e,n,r){return vt(r,"condition"),r?n:e}};Object.
465
+ freeze(Yn.prototype);function Xn(t,e={}){return new Yn(t,e)}var Qn=BigInt(0),Po=BigInt(1);function ca(t,e){let n=e.negate();return t?n:e}function tr(t,e){let n=Zn(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function pa(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
466
+ throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ro(t,e){pa(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=Ys(t),s=BigInt(t);return {windows:n,windowSize:r,mask:i,maxNumber:o,
467
+ shiftBy:s}}function ua(t,e,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(t&o),u=t>>s;a>r&&(a-=i,u+=Po);let c=e*r,l=c+Math.abs(a)-1,d=a===0,f=a<0,m=e%2!==0;return {nextN:u,offset:l,isZero:d,
468
+ isNeg:f,isNegF:m,offsetF:c}}var Co=new WeakMap,fa=new WeakMap;function Io(t){return fa.get(t)||1}function la(t){if(t!==Qn)throw new Error("invalid wNAF")}var er=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
469
+ e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>Qn;)n&Po&&(r=r.add(o)),o=o.double(),n>>=Po;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Ro(n,this.bits),i=[],
470
+ s=e,a=s;for(let u=0;u<r;u++){a=s,i.push(a);for(let c=1;c<o;c++)a=a.add(s),i.push(a);s=a.double();}return i}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,
471
+ s=Ro(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:u,offset:c,isZero:l,isNeg:d,isNegF:f,offsetF:m}=ua(r,a,s);r=u,l?i=i.add(ca(f,n[m])):o=o.add(ca(d,n[c]));}return la(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.
472
+ ZERO){let i=Ro(e,this.bits);for(let s=0;s<i.windows&&r!==Qn;s++){let{nextN:a,offset:u,isZero:c,isNeg:l}=ua(r,s,i);if(r=a,!c){let d=n[u];o=o.add(l?d.negate():d);}}return la(r),o}getPrecomputes(e,n,r){let o=Co.
473
+ get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Co.set(n,o))),o}cached(e,n,r){let o=Io(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Io(
474
+ e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){pa(n,this.bits),fa.set(e,n),Co.delete(e);}hasCache(e){return Io(e)!==1}};function da(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return aa(e),e}else return Xn(t,{isLE:n})}function ma(t,e,n={},r){if(r===void 0&&(r=t==="edwar\
475
+ ds"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let u of ["p","n","h"]){let c=e[u];if(!(typeof c=="bigint"&&c>Qn))throw new Error(`CURVE.${u} must be positive bigint`)}
476
+ let o=da(e.p,n.Fp,r),i=da(e.n,n.Fn,r),a=["Gx","Gy","a","d"];for(let u of a)if(!o.isValid(e[u]))throw new Error(`CURVE.${u} must be valid field element of CURVE.Fp`);return e=Object.
477
+ freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function ha(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var ze=BigInt(0),K=BigInt(1),_o=BigInt(2),Dl=BigInt(8);function Ol(t,e,n,r){let o=t.sqr(n),i=t.sqr(r),s=t.add(t.mul(e.a,o),i),a=t.add(t.ONE,t.mul(e.d,t.mul(o,i)));return t.eql(s,a)}function ga(t,e={}){
478
+ let n=e,r=ma("edwards",t,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;et(n,{},{uvRatio:"function"});let u=_o<<BigInt(i.BYTES*8)-K,c=b=>o.create(b),l=n.uvRatio===void 0?(b,p)=>{try{return {isValid:!0,value:o.
479
+ sqrt(o.div(b,p))}}catch{return {isValid:false,value:ze}}}:n.uvRatio;if(!Ol(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(b,p,v=false){let g=v?K:ze;return wo("coordinate "+b,p,
480
+ g,u),p}function f(b){if(!(b instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(s.Gx,s.Gy,K,c(s.Gx*s.Gy));static ZERO=new m(ze,K,K,ze);static Fp=o;static Fn=i;X;Y;Z;T;constructor(p,v,g,y){
481
+ this.X=d("x",p),this.Y=d("y",v),this.Z=d("z",g,true),this.T=d("t",y),Object.freeze(this);}static CURVE(){return s}static fromAffine(p){if(p instanceof m)throw new Error("extended point not allowed");let{
482
+ x:v,y:g}=p||{};return d("x",v),d("y",g),new m(v,g,K,c(v*g))}static fromBytes(p,v=false){let g=o.BYTES,{a:y,d:k}=s;p=Zt(q(p,g,"point")),vt(v,"zip215");let x=Zt(p),T=p[g-1];x[g-1]=T&-129;let w=Ce(x),R=v?u:
483
+ o.ORDER;wo("point.y",w,ze,R);let D=c(w*w),O=c(D-K),_=c(k*D-y),{isValid:S,value:C}=l(O,_);if(!S)throw new Error("bad point: invalid y coordinate");let P=(C&K)===K,A=(T&128)!==0;if(!v&&C===ze&&A)throw new Error(
484
+ "bad point: x=0 and x_0=1");return A!==P&&(C=c(-C)),m.fromAffine({x:C,y:w})}static fromHex(p,v=false){return m.fromBytes(Hs(p),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,v=true){
485
+ return h.createCache(this,p),v||this.multiply(_o),this}assertValidity(){let p=this,{a:v,d:g}=s;if(p.is0())throw new Error("bad point: ZERO");let{X:y,Y:k,Z:x,T}=p,w=c(y*y),R=c(k*k),D=c(x*x),O=c(D*D),_=c(
486
+ w*v),S=c(D*c(_+R)),C=c(O+c(g*c(w*R)));if(S!==C)throw new Error("bad point: equation left != right (1)");let P=c(y*k),A=c(x*T);if(P!==A)throw new Error("bad point: equation left != right (2)")}equals(p){
487
+ f(p);let{X:v,Y:g,Z:y}=this,{X:k,Y:x,Z:T}=p,w=c(v*T),R=c(k*y),D=c(g*T),O=c(x*y);return w===R&&D===O}is0(){return this.equals(m.ZERO)}negate(){return new m(c(-this.X),this.Y,this.Z,c(-this.T))}double(){
488
+ let{a:p}=s,{X:v,Y:g,Z:y}=this,k=c(v*v),x=c(g*g),T=c(_o*c(y*y)),w=c(p*k),R=v+g,D=c(c(R*R)-k-x),O=w+x,_=O-T,S=w-x,C=c(D*_),P=c(O*S),A=c(D*S),L=c(_*O);return new m(C,P,L,A)}add(p){f(p);let{a:v,d:g}=s,{X:y,
489
+ Y:k,Z:x,T}=this,{X:w,Y:R,Z:D,T:O}=p,_=c(y*w),S=c(k*R),C=c(T*g*O),P=c(x*D),A=c((y+k)*(w+R)-_-S),L=P-C,$=P+C,B=c(S-v*_),z=c(A*L),Z=c($*B),I=c(A*B),ne=c(L*$);return new m(z,Z,ne,I)}subtract(p){return f(p),
490
+ this.add(p.negate())}multiply(p){if(!i.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:g}=h.cached(this,p,y=>tr(m,y));return tr(m,[v,g])[0]}multiplyUnsafe(p){
491
+ if(!i.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===ze?m.ZERO:this.is0()||p===K?this:h.unsafe(this,p,v=>tr(m,v))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){
492
+ return h.unsafe(this,s.n).is0()}toAffine(p){let v=this,g=p,{X:y,Y:k,Z:x}=v,T=v.is0();g==null&&(g=T?Dl:o.inv(x));let w=c(y*g),R=c(k*g),D=o.mul(x,g);if(T)return {x:ze,y:K};if(D!==K)throw new Error("invZ \
493
+ was invalid");return {x:w,y:R}}clearCofactor(){return a===K?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y:v}=this.toAffine(),g=o.toBytes(v);return g[g.length-1]|=p&K?128:0,g}toHex(){return yo(this.toBytes())}toString(){
494
+ return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let h=new er(m,i.BITS);return i.BITS>=8&&m.BASE.precompute(8),Object.freeze(m.prototype),Object.freeze(m),m}var nr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){
495
+ this.ep=e;}static fromBytes(e){To();}static fromHex(e){To();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){
496
+ return this.ep.toAffine(e)}toHex(){return yo(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){
429
497
  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.
430
- ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function si(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is r\
431
- equired');let r=e,o=n;Be(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=t,u=r.
432
- outputLen,l=2*a.BYTES;if(u!==void 0&&(ye(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let d=o.randomBytes===void 0?Ms:o.randomBytes,m=o.adjustScalarBytes===void 0?
433
- T=>T:o.adjustScalarBytes,f=o.domain===void 0?(T,R,D)=>{if(Ge(D,"phflag"),R.length||D)throw new Error("Contexts/pre-hash are not supported");return T}:o.domain;function h(T){return c.create(xe(T))}function g(T){
434
- let R=w.secretKey;U(T,w.secretKey,"secretKey");let D=U(r(T),2*R,"hashedSecretKey"),M=m(D.slice(0,R)),j=D.slice(R,2*R),$=h(M);return {head:M,prefix:j,scalar:$}}function p(T){let{head:R,prefix:D,scalar:M}=g(
435
- T),j=i.multiply(M),$=j.toBytes();return {head:R,prefix:D,scalar:M,point:j,pointBytes:$}}function v(T){return p(T).pointBytes}function b(T=Uint8Array.of(),...R){let D=ue(...R);return h(r(f(D,U(T,void 0,
436
- "context"),!!s)))}function x(T,R,D={}){T=U(T,void 0,"message"),s&&(T=s(T));let{prefix:M,scalar:j,pointBytes:$}=p(R),Y=b(D.context,M,T),oe=i.multiply(Y).toBytes(),P=b(D.context,oe,$,T),se=c.create(Y+P*
437
- j);if(!c.isValid(se))throw new Error("sign failed: invalid s");let B=ue(oe,c.toBytes(se));return U(B,w.signature,"result")}let y={zip215:o.zip215};function k(T,R,D,M=y){let{context:j}=M,$=M.zip215===void 0?
438
- !!y.zip215:M.zip215,Y=w.signature;T=U(T,Y,"signature"),R=U(R,void 0,"message"),D=U(D,w.publicKey,"publicKey"),$!==void 0&&Ge($,"zip215"),s&&(R=s(R));let oe=Y/2,P=T.subarray(0,oe),se=xe(T.subarray(oe,Y)),
439
- B,Se,de;try{B=t.fromBytes(D,$),Se=t.fromBytes(P,$),de=i.multiplyUnsafe(se);}catch{return false}if(!$&&B.isSmallOrder())return false;let pe=b(j,P,D,R);return Se.add(B.multiplyUnsafe(pe)).subtract(de).clearCofactor().
440
- is0()}let E=a.BYTES,w={secretKey:E,publicKey:E,signature:2*E,seed:E};function I(T){return T=T===void 0?d(w.seed):T,U(T,w.seed,"seed")}function O(T){return hn(T)&&T.length===w.secretKey}function C(T,R){
441
- try{return !!t.fromBytes(T,R===void 0?y.zip215:R)}catch{return false}}let _={getExtendedPublicKey:p,randomSecretKey:I,isValidSecretKey:O,isValidPublicKey:C,toMontgomery(T){let{y:R}=t.fromBytes(T),D=w.publicKey,
442
- M=D===32;if(!M&&D!==57)throw new Error("only defined for 25519 and 448");let j=M?a.div(K+R,K-R):a.div(R-K,R+K);return a.toBytes(j)},toMontgomerySecret(T){let R=w.secretKey;U(T,R);let D=r(T.subarray(0,
443
- R));return m(D).subarray(0,R)}};return Object.freeze(w),Object.freeze(_),Object.freeze({keygen:ri(I,v),getPublicKey:v,sign:x,verify:k,utils:_,Point:t,lengths:w})}var Wc=BigInt(0),we=BigInt(1),ai=BigInt(2);var Gc=BigInt(5),Yc=BigInt(8),Ye=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Fr={p:Ye,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Yc,
498
+ ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function ba(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is r\
499
+ equired');let r=e,o=n;et(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:u}=t,c=r.
500
+ outputLen,l=2*a.BYTES;if(c!==void 0&&(Re(c,"hash.outputLen"),c!==l))throw new Error(`hash.outputLen must be ${l}, got ${c}`);let d=o.randomBytes===void 0?Ws:o.randomBytes,f=o.adjustScalarBytes===void 0?
501
+ S=>S:o.adjustScalarBytes,m=o.domain===void 0?(S,C,P)=>{if(vt(P,"phflag"),C.length||P)throw new Error("Contexts/pre-hash are not supported");return S}:o.domain;function h(S){return u.create(Ce(S))}function b(S){
502
+ let C=w.secretKey;q(S,w.secretKey,"secretKey");let P=q(r(S),2*C,"hashedSecretKey"),A=f(P.slice(0,C)),L=P.slice(C,2*C),$=h(A);return {head:A,prefix:L,scalar:$}}function p(S){let{head:C,prefix:P,scalar:A}=b(
503
+ S),L=s.multiply(A),$=L.toBytes();return {head:C,prefix:P,scalar:A,point:L,pointBytes:$}}function v(S){return p(S).pointBytes}function g(S=Uint8Array.of(),...C){let P=ke(...C);return h(r(m(P,q(S,void 0,
504
+ "context"),!!i)))}function y(S,C,P={}){S=q(S,void 0,"message"),i&&(S=i(S));let{prefix:A,scalar:L,pointBytes:$}=p(C),B=g(P.context,A,S),z=s.multiply(B).toBytes(),Z=g(P.context,z,$,S),I=u.create(B+Z*L);
505
+ if(!u.isValid(I))throw new Error("sign failed: invalid s");let ne=ke(z,u.toBytes(I));return q(ne,w.signature,"result")}let k={zip215:o.zip215};function x(S,C,P,A=k){let{context:L}=A,$=A.zip215===void 0?
506
+ !!k.zip215:A.zip215,B=w.signature;S=q(S,B,"signature"),C=q(C,void 0,"message"),P=q(P,w.publicKey,"publicKey"),$!==void 0&&vt($,"zip215"),i&&(C=i(C));let z=B/2,Z=S.subarray(0,z),I=Ce(S.subarray(z,B)),ne,
507
+ De,ln;try{ne=t.fromBytes(P,$),De=t.fromBytes(Z,$),ln=s.multiplyUnsafe(I);}catch{return false}if(!$&&ne.isSmallOrder())return false;let Er=g(L,Z,P,C);return De.add(ne.multiplyUnsafe(Er)).subtract(ln).clearCofactor().
508
+ is0()}let T=a.BYTES,w={secretKey:T,publicKey:T,signature:2*T,seed:T};function R(S){return S=S===void 0?d(w.seed):S,q(S,w.seed,"seed")}function D(S){return Gn(S)&&S.length===w.secretKey}function O(S,C){
509
+ try{return !!t.fromBytes(S,C===void 0?k.zip215:C)}catch{return false}}let _={getExtendedPublicKey:p,randomSecretKey:R,isValidSecretKey:D,isValidPublicKey:O,toMontgomery(S){let{y:C}=t.fromBytes(S),P=w.publicKey,
510
+ A=P===32;if(!A&&P!==57)throw new Error("only defined for 25519 and 448");let L=A?a.div(K+C,K-C):a.div(C-K,C+K);return a.toBytes(L)},toMontgomerySecret(S){let C=w.secretKey;q(S,C);let P=r(S.subarray(0,
511
+ C));return f(P).subarray(0,C)}};return Object.freeze(w),Object.freeze(_),Object.freeze({keygen:ha(R,v),getPublicKey:v,sign:y,verify:x,utils:_,Point:t,lengths:w})}var Ll=BigInt(0),Pe=BigInt(1),ya=BigInt(2);var Nl=BigInt(5),jl=BigInt(8),yt=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Lo={p:yt,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:jl,
444
512
  a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
445
- c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Zc(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=Ye,a=t*t%
446
- s*t%s,c=re(a,ai,s)*a%s,u=re(c,we,s)*t%s,l=re(u,Gc,s)*u%s,d=re(l,e,s)*l%s,m=re(d,n,s)*d%s,f=re(m,r,s)*m%s,h=re(f,o,s)*f%s,g=re(h,o,s)*f%s,p=re(g,e,s)*l%s;return {pow_p_5_8:re(p,ai,s)*t%s,b2:a}}function Xc(t){
447
- return t[0]&=248,t[31]&=127,t[31]|=64,t}var Nr=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function zr(t,e){let n=Ye,r=z(e*e*e,n),o=z(r*r*e,n),s=Zc(t*o).pow_p_5_8,
448
- i=z(t*r*s,n),a=z(e*i*i,n),c=i,u=z(i*Nr,n),l=a===t,d=a===z(-t,n),m=a===z(-t*Nr,n);return l&&(i=c),(d||m)&&(i=u),ke(i,n)&&(i=z(-i,n)),{isValid:l||d,value:i}}var Oe=oi(Fr,{uvRatio:zr}),De=Oe.Fp,li=Oe.Fn;function Qc(t){return si(Oe,pn,Object.assign({adjustScalarBytes:Xc,zip215:true},t))}var di=Qc({});var jr=Nr;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var tu=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
449
- "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var ci=t=>zr(we,t),ou=BigInt("0x7\
450
- fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Br=t=>De.create(xe(t)&ou);var Ae=class t extends Sn{static BASE=new t(
451
- Oe.BASE);static ZERO=new t(Oe.ZERO);static Fp=De;static Fn=li;constructor(e){super(e);}static fromAffine(e){return new t(Oe.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoP\
452
- oint expected")}init(e){return new t(e)}static fromBytes(e){ne(e,32);let{a:n,d:r}=Fr,o=Ye,s=y=>De.create(y),i=Br(e);if(!js(De.toBytes(i),e)||ke(i,o))throw new Error("invalid ristretto255 encoding 1");
453
- let a=s(i*i),c=s(we+n*a),u=s(we-n*a),l=s(c*c),d=s(u*u),m=s(n*r*l-d),{isValid:f,value:h}=ci(s(m*d)),g=s(h*u),p=s(h*g*m),v=s((i+i)*g);ke(v,o)&&(v=s(-v));let b=s(c*p),x=s(v*b);if(!f||ke(x,o)||b===Wc)throw new Error(
454
- "invalid ristretto255 encoding 2");return new t(new Oe(v,b,we,x))}static fromHex(e){return t.fromBytes(yt(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,s=Ye,i=p=>De.create(p),a=i(i(r+n)*i(r-n)),c=i(e*n),
455
- u=i(c*c),{value:l}=ci(i(a*u)),d=i(l*a),m=i(l*c),f=i(d*m*o),h;if(ke(o*f,s)){let p=i(n*jr),v=i(e*jr);e=p,n=v,h=i(d*tu);}else h=m;ke(e*f,s)&&(n=i(-n));let g=i((r-n)*h);return ke(g,s)&&(g=i(-g)),De.toBytes(
456
- g)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:s}=e.ep,i=u=>De.create(u),a=i(n*s)===i(r*o),c=i(r*s)===i(n*o);return a||c}is0(){return this.equals(t.ZERO)}};Object.freeze(Ae.BASE);Object.freeze(
457
- Ae.ZERO);Object.freeze(Ae.prototype);Object.freeze(Ae);var pi=`-----BEGIN PUBLIC KEY-----
513
+ c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function $l(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=yt,a=t*t%
514
+ i*t%i,u=ge(a,ya,i)*a%i,c=ge(u,Pe,i)*t%i,l=ge(c,Nl,i)*c%i,d=ge(l,e,i)*l%i,f=ge(d,n,i)*d%i,m=ge(f,r,i)*f%i,h=ge(m,o,i)*m%i,b=ge(h,o,i)*m%i,p=ge(b,e,i)*l%i;return {pow_p_5_8:ge(p,ya,i)*t%i,b2:a}}function Fl(t){
515
+ return t[0]&=248,t[31]&=127,t[31]|=64,t}var Oo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function No(t,e){let n=yt,r=U(e*e*e,n),o=U(r*r*e,n),i=$l(t*o).pow_p_5_8,
516
+ s=U(t*r*i,n),a=U(e*s*s,n),u=s,c=U(s*Oo,n),l=a===t,d=a===U(-t,n),f=a===U(-t*Oo,n);return l&&(s=u),(d||f)&&(s=c),Ie(s,n)&&(s=U(-s,n)),{isValid:l||d,value:s}}var Ue=ga(Lo,{uvRatio:No}),Ve=Ue.Fp,wa=Ue.Fn;function Bl(t){return ba(Ue,Hn,Object.assign({adjustScalarBytes:Fl,zip215:true},t))}var Sa=Bl({});var Ao=Oo;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Vl=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
517
+ "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var ka=t=>No(Pe,t),Hl=BigInt("0x7\
518
+ fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Mo=t=>Ve.create(Ce(t)&Hl);var qe=class t extends nr{static BASE=new t(
519
+ Ue.BASE);static ZERO=new t(Ue.ZERO);static Fp=Ve;static Fn=wa;constructor(e){super(e);}static fromAffine(e){return new t(Ue.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoP\
520
+ oint expected")}init(e){return new t(e)}static fromBytes(e){he(e,32);let{a:n,d:r}=Lo,o=yt,i=k=>Ve.create(k),s=Mo(e);if(!Js(Ve.toBytes(s),e)||Ie(s,o))throw new Error("invalid ristretto255 encoding 1");
521
+ let a=i(s*s),u=i(Pe+n*a),c=i(Pe-n*a),l=i(u*u),d=i(c*c),f=i(n*r*l-d),{isValid:m,value:h}=ka(i(f*d)),b=i(h*c),p=i(h*b*f),v=i((s+s)*b);Ie(v,o)&&(v=i(-v));let g=i(u*p),y=i(v*g);if(!m||Ie(y,o)||g===Ll)throw new Error(
522
+ "invalid ristretto255 encoding 2");return new t(new Ue(v,g,Pe,y))}static fromHex(e){return t.fromBytes(Gt(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,i=yt,s=p=>Ve.create(p),a=s(s(r+n)*s(r-n)),u=s(e*n),
523
+ c=s(u*u),{value:l}=ka(s(a*c)),d=s(l*a),f=s(l*u),m=s(d*f*o),h;if(Ie(o*m,i)){let p=s(n*Ao),v=s(e*Ao);e=p,n=v,h=s(d*Vl);}else h=f;Ie(e*m,i)&&(n=s(-n));let b=s((r-n)*h);return Ie(b,i)&&(b=s(-b)),Ve.toBytes(
524
+ b)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:i}=e.ep,s=c=>Ve.create(c),a=s(n*i)===s(r*o),u=s(r*i)===s(n*o);return a||u}is0(){return this.equals(t.ZERO)}};Object.freeze(qe.BASE);Object.freeze(
525
+ qe.ZERO);Object.freeze(qe.prototype);Object.freeze(qe);var Ta=`-----BEGIN PUBLIC KEY-----
458
526
  MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
459
- -----END PUBLIC KEY-----`;function fi(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 $r(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.
460
- length%4?"=".repeat(4-e.length%4):"";return fi(e+n)}function iu(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=fi(e);return n.subarray(n.length-32)}var au=new TextEncoder,mi=new TextDecoder;
461
- function cu(t){return typeof t=="object"&&t!==null&&"keys"in t}function Ze(t){let e=t.trim(),n=/^(["'])([\s\S]*)\1$/.exec(e);return n&&(e=n[2].trim()),e=e.replace(/^bearer\s+/i,""),e.trim()}var uu=/^[A-Za-z0-9_-]+$/;
462
- function hi(t){let e=t.split(".");return e.length===3&&e.every(n=>uu.test(n))}function Vr(t){return t===""?"empty":hi(t)?"token":"malformed"}function Ur(t,e){if(!hi(t))return {ok:false,reason:"malformed t\
463
- oken"};let n=t.split("."),r=n[0],o=n[1],s=n[2],i;try{i=JSON.parse(mi.decode($r(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(cu(e)){let l=typeof i.kid=="string"?i.kid:e.defaultKid,
464
- d=e.keys[l];if(!d)return {ok:false,reason:`unknown key id "${l}"`};a=d;}else {if(!e)return {ok:false,reason:"no verification key"};a=e;}let c;try{if(c=iu(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
465
- return {ok:false,reason:"invalid public key"}}let u=false;try{u=di.verify($r(s),au.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return u?{ok:true,header:i,payloadBytes:$r(o)}:
466
- {ok:false,reason:"bad signature"}}function Xe(t,e){let n=Ur(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(mi.decode(
467
- n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function qr(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"\
468
- active":e<=r?"grace":"expired"}function Df(t,e,n={}){let r=Ze(t);if(Vr(r)==="empty")return {status:"none",reason:"empty"};let s=Xe(r,e);if(!s.signatureValid||!s.payload)return {status:"invalid",...s.reason?
469
- {reason:s.reason}:{}};let i=s.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),c=qr(i,a,n.revoked);return c==="revoked"?{status:c,payload:i,reason:"license revoked"}:{status:c,payload:i}}var gi="BVSALA-REVOC",lu=300,du=new TextDecoder;function bi(t,e,n={}){let r=u=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:u}),o=Ur(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
470
- if(o.header?.typ!==gi)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${gi})`);let s;try{s=JSON.parse(du.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof s.
471
- 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 a=n.
472
- nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??lu;return s.asOf>a+c?r(`asOf too far in the future (${s.asOf} > ${a+c})`):{ok:true,seq:s.seq,asOf:s.asOf,revoked:new Set(s.revoked)}}var Qe=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
527
+ -----END PUBLIC KEY-----`;function Ea(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 jo(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.
528
+ length%4?"=".repeat(4-e.length%4):"";return Ea(e+n)}function Kl(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Ea(e);return n.subarray(n.length-32)}var Gl=new TextEncoder,Ra=new TextDecoder;
529
+ function Jl(t){return typeof t=="object"&&t!==null&&"keys"in t}function kt(t){let e=t.trim(),n=/^(["'])([\s\S]*)\1$/.exec(e);return n&&(e=n[2].trim()),e=e.replace(/^bearer\s+/i,""),e.trim()}var Yl=/^[A-Za-z0-9_-]+$/;
530
+ function Ca(t){let e=t.split(".");return e.length===3&&e.every(n=>Yl.test(n))}function $o(t){return t===""?"empty":Ca(t)?"token":"malformed"}function Fo(t,e){if(!Ca(t))return {ok:false,reason:"malformed t\
531
+ oken"};let n=t.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(Ra.decode(jo(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(Jl(e)){let l=typeof s.kid=="string"?s.kid:e.defaultKid,
532
+ d=e.keys[l];if(!d)return {ok:false,reason:`unknown key id "${l}"`};a=d;}else {if(!e)return {ok:false,reason:"no verification key"};a=e;}let u;try{if(u=Kl(a),u.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
533
+ return {ok:false,reason:"invalid public key"}}let c=false;try{c=Sa.verify(jo(i),Gl.encode(`${r}.${o}`),u);}catch{return {ok:false,reason:"signature verification error"}}return c?{ok:true,header:s,payloadBytes:jo(o)}:
534
+ {ok:false,reason:"bad signature"}}function xt(t,e){let n=Fo(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(Ra.decode(
535
+ n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function Bo(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"\
536
+ active":e<=r?"grace":"expired"}function rg(t,e,n={}){let r=kt(t);if($o(r)==="empty")return {status:"none",reason:"empty"};let i=xt(r,e);if(!i.signatureValid||!i.payload)return {status:"invalid",...i.reason?
537
+ {reason:i.reason}:{}};let s=i.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),u=Bo(s,a,n.revoked);return u==="revoked"?{status:u,payload:s,reason:"license revoked"}:{status:u,payload:s}}var Ia="BVSALA-REVOC",Zl=300,Xl=new TextDecoder;function Pa(t,e,n={}){let r=c=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:c}),o=Fo(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
538
+ if(o.header?.typ!==Ia)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${Ia})`);let i;try{i=JSON.parse(Xl.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
539
+ seq!="number"||typeof i.asOf!="number"||!Array.isArray(i.revoked))return r("malformed revocation payload");let s=n.minSeq??0;if(i.seq<s)return r(`stale/rolled-back list (seq ${i.seq} < ${s})`);let a=n.
540
+ nowSeconds??Math.floor(Date.now()/1e3),u=n.maxSkewSeconds??Zl;return i.asOf>a+u?r(`asOf too far in the future (${i.asOf} > ${a+u})`):{ok:true,seq:i.seq,asOf:i.asOf,revoked:new Set(i.revoked)}}var wt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
473
541
  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.
474
- 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&&
475
- (this._asOf=e.asOf),r||o}};function Tn(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),s=Ze(t),i=Vr(s),a=i==="token"?Xe(s,e):{signatureValid:false,reason:i},c=a.signatureValid?a.payload:void 0,u=new Set(
476
- c?.features??[]),l=()=>{if(i==="empty")return "none";if(!c)return "invalid";let m=qr(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(m==="active"||m==="grace")){let f=c.expires_at+c.grace_days*
477
- 86400,h=Math.min(o,f),g=Math.max(n.revocation.lastContactAt,h);if(r()-g>n.maxStalenessSeconds)return "stale"}return m},d=()=>{let m=l();return m==="active"||m==="grace"};return {isEntitled:m=>d()&&u.has(
478
- m),isActive:()=>d(),status:l,reason:()=>c?void 0:a.reason,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}function vi(t,e,n){return Tn(t,e,{revocation:new Qe,...n?{now:n}:{}})}var et={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},yi=3,pu=12;function fu(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
479
- 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:
480
- 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 mu=10,En=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;warnedNoFetch=false;lastEtag=null;consecutive304=0;now(){
542
+ set}apply(e){if(e.seq<this._seq)return false;let n=this.set.size;for(let i of e.revoked)this.set.add(i);let r=this.set.size>n,o=e.seq>this._seq;return e.seq>this._seq&&(this._seq=e.seq),e.asOf>this._asOf&&
543
+ (this._asOf=e.asOf),r||o}};function rr(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=kt(t),s=$o(i),a=s==="token"?xt(i,e):{signatureValid:false,reason:s},u=a.signatureValid?a.payload:void 0,c=new Set(
544
+ u?.features??[]),l=()=>{if(s==="empty")return "none";if(!u)return "invalid";let f=Bo(u,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(f==="active"||f==="grace")){let m=u.expires_at+u.grace_days*
545
+ 86400,h=Math.min(o,m),b=Math.max(n.revocation.lastContactAt,h);if(r()-b>n.maxStalenessSeconds)return "stale"}return f},d=()=>{let f=l();return f==="active"||f==="grace"};return {isEntitled:f=>d()&&c.has(
546
+ f),isActive:()=>d(),status:l,reason:()=>u?void 0:a.reason,refreshAfter:()=>{if(u)return Math.min(u.expires_at,r()+86400)}}}function _a(t,e,n){return rr(t,e,{revocation:new wt,...n?{now:n}:{}})}var St={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Da=3,Ql=12;function ed(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
547
+ 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,i=o<0?t.pollIntervalSeconds:
548
+ o;n=Math.min(t.pollIntervalSeconds,Math.max(t.floorSeconds,i));}let r=1+(e()*2-1)*t.jitterRatio;return Math.max(t.floorSeconds,n*r)}var td=10,or=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;warnedNoFetch=false;lastEtag=null;consecutive304=0;now(){
481
549
  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();
482
550
  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.
483
- onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??et.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let s={accept:"applicati\
484
- on/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.
485
- now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=mu&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!i.
486
- ok)throw new Error(`revocations HTTP ${i.status}`);let a=i.headers.get("etag"),c=await i.json();if(!c.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let u=bi(c.list,this.opts.
487
- publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??et.maxSkewSeconds});if(!u.ok){let d=u.reason??"rejected";this.opts.onEvent?.({type:"rejected",
551
+ onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??St.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"applicati\
552
+ on/json"};this.lastEtag&&(i["if-none-match"]=this.lastEtag);try{let s=await e(this.opts.url,{signal:n.signal,headers:i});if(s.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.
553
+ now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=td&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.
554
+ ok)throw new Error(`revocations HTTP ${s.status}`);let a=s.headers.get("etag"),u=await s.json();if(!u.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let c=Pa(u.list,this.opts.
555
+ publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??St.maxSkewSeconds});if(!c.ok){let d=c.reason??"rejected";this.opts.onEvent?.({type:"rejected",
488
556
  reason:d}),this.avisar(`rechazada:${d}`,`[bv-sala] the revocation list does NOT verify (${d}). The last known-good list is kept, so revocations ALREADY known still apply, but new ones are not arriving\
489
- . Check ${this.opts.url}.`);return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let l=this.opts.snapshot.apply(u);this.opts.onEvent?.(l?{type:"applied",seq:u.seq,size:this.opts.snapshot.
490
- snapshot().size}:{type:"unchanged",seq:u.seq});}catch(i){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:i}),this.avisarFalloDeRed(i);}finally{clearTimeout(o),this.controller=null;}}callado(){
491
- return !!(this.opts.silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||F(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;let n=this.consecutiveFailures;
492
- if(n<yi||(n-yi)%pu!==0)return;let r=e instanceof Error?e.message:String(e);console.warn(`[bv-sala] could not reach the revocation server ${n} times in a row (${r}). The license KEEPS working and known\
557
+ . Check ${this.opts.url}.`);return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let l=this.opts.snapshot.apply(c);this.opts.onEvent?.(l?{type:"applied",seq:c.seq,size:this.opts.snapshot.
558
+ snapshot().size}:{type:"unchanged",seq:c.seq});}catch(s){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:s}),this.avisarFalloDeRed(s);}finally{clearTimeout(o),this.controller=null;}}callado(){
559
+ return !!(this.opts.silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||V(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;let n=this.consecutiveFailures;
560
+ if(n<Da||(n-Da)%Ql!==0)return;let r=e instanceof Error?e.message:String(e);console.warn(`[bv-sala] could not reach the revocation server ${n} times in a row (${r}). The license KEEPS working and known\
493
561
  revocations still apply, but NEW ones are not arriving. Check egress to ${this.opts.url}.`);}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){
494
- if(this.stopped)return;let e=fu({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??et.floorSeconds,pollIntervalSeconds:this.
495
- opts.pollIntervalSeconds??et.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??et.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??et.jitterRatio,...this.opts.random?{random:this.
562
+ if(this.stopped)return;let e=ed({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??St.floorSeconds,pollIntervalSeconds:this.
563
+ opts.pollIntervalSeconds??St.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??St.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??St.jitterRatio,...this.opts.random?{random:this.
496
564
  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.
497
- controller?.abort();}};var Tt=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;inflight=null;fallosSeguidos=0;constructor(e){this.options=e,this.now=e.now??(()=>Date.now()),this.flushIntervalMs=
565
+ controller?.abort();}};var Qt=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;inflight=null;fallosSeguidos=0;constructor(e){this.options=e,this.now=e.now??(()=>Date.now()),this.flushIntervalMs=
498
566
  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.
499
567
  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.
500
568
  flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async stopAndDrain(e){this.timer&&(clearInterval(this.timer),this.timer=void 0);let n=e??
501
- Math.ceil(this.maxBuffer/this.maxBatch)+4,r=0;for(let o=0;o<n&&this.buffer.length>0;o++){let s=this.buffer.length;if(await this.flush(),r=this.buffer.length>=s?r+1:0,r>=2)break}}async flush(){if(this.
569
+ Math.ceil(this.maxBuffer/this.maxBatch)+4,r=0;for(let o=0;o<n&&this.buffer.length>0;o++){let i=this.buffer.length;if(await this.flush(),r=this.buffer.length>=i?r+1:0,r>=2)break}}async flush(){if(this.
502
570
  inflight)return this.inflight;if(this.buffer.length!==0){this.inflight=this.hacerFlush();try{await this.inflight;}finally{this.inflight=null;}}}async hacerFlush(){let e=this.options.fetchImpl??globalThis.
503
- fetch;if(!e)return;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:`Bear\
504
- er ${this.options.serviceAccountKey}`,[zt]:`${this.options.surface??"sdk"}/${lt}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
505
- `the server responded ${o.status}`)):o.status===401||o.status===403?(F(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status} at ${this.options.url}. Check 'ser\
571
+ fetch;if(!e)return;let n=this.buffer.splice(0,this.maxBatch);try{let r=n.map(i=>this.toWire(i)),o=await e(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bear\
572
+ er ${this.options.serviceAccountKey}`,[hn]:`${this.options.surface??"sdk"}/${Se}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
573
+ `the server responded ${o.status}`)):o.status===401||o.status===403?(V(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status} at ${this.options.url}. Check 'ser\
506
574
  viceAccountKey' (rotated? revoked? from another organization?). Until it works, no usage is reported: the dashboard will say it sees no traffic and billable seats will show zero.`),this.options.onAuthError?.(
507
575
  o.status)):(this.fallosSeguidos++,this.avisarDeFallo(o.status===404||o.status===405?`HTTP ${o.status}: the reporting URL looks wrong`:`the server rejected the batch with HTTP ${o.status}`));}catch(r){this.
508
576
  fallosSeguidos++,this.requeue(n),this.avisarDeFallo(r instanceof Error?r.message:"network error");}}avisarDeFallo(e){if(this.options.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||
@@ -514,206 +582,217 @@ tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutput
514
582
  eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.cost.eliminatedInputFloorCost}:
515
583
  {},baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{},...n.cost.basis==="reference"&&n.cache.reference&&/^[A-Za-z0-9._:/-]{1,128}$/.
516
584
  test(n.cache.reference.requestId)&&Number.isInteger(n.cache.reference.at)?{referenceRequestId:n.cache.reference.requestId,referenceAt:n.cache.reference.at}:{},...n.attribution?.sessionId?{sessionId:n.
517
- attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function Rn(){return globalThis.process}function hu(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\
518
- ]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function gu(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??
519
- t.NETLIFY)}async function bu(){if(Rn()?.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 vu(t,e=bu){
520
- if(t.KUBERNETES_SERVICE_HOST||gu(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||hu(n)))return n}async function yu(){let t=Rn();if(!t||!t.env)return;let e=t.env,n=await vu(e),r=[t.platform,
521
- 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 xu=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
522
- ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function Hr(){let t=Rn()?.env;if(!t)
523
- return false;for(let e of xu){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function ku(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let i=await n.subtle.importKey("raw",
524
- r.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",i,r.encode(e));return [...new Uint8Array(a)].map(c=>c.toString(16).padStart(2,"0")).join("")}catch{}let o=2166136261,s=`${t}\
525
- |${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 Kr(t){let n=Rn()?.env?.BVSALA_SEAT_ID;if(n&&wu.test(n))return n;let r=await yu();
526
- if(!r)return;let o=await ku(t,r);if(o)return `m-${o.slice(0,32)}`}var wu=/^[A-Za-z0-9._:/-]{1,128}$/;var xi={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function ki(t){return {exactCache:t.exactCache??new Ut,semanticCache:t.semanticCache,singleflight:t.singleflight??new qt,resolvers:t.resolvers??jo(),router:t.router??new Ht,toolSelector:t.toolSelector??
527
- new Kt,formatSelector:t.formatSelector??new Yt({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new Zt,constraintBackends:t.constraintBackends??[]}}var Su=36e5,Tu=7*86400,Eu=3e4,Cn=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;avisadoDeCredencial=false;currentExpiresAt;currentOrg;constructor(e){this.opts=
528
- e,this.pollIntervalMs=e.pollIntervalMs??Su,this.refreshLeadSeconds=e.refreshLeadSeconds??Tu;let n=Xe(Ze(e.initialToken),e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.expires_at:
585
+ attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function ir(){return globalThis.process}function nd(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\
586
+ ]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function rd(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??
587
+ t.NETLIFY)}async function od(){if(ir()?.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 id(t,e=od){
588
+ if(t.KUBERNETES_SERVICE_HOST||rd(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||nd(n)))return n}async function sd(){let t=ir();if(!t||!t.env)return;let e=t.env,n=await id(e),r=[t.platform,
589
+ 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 ad=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
590
+ ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function zo(){let t=ir()?.env;if(!t)
591
+ return false;for(let e of ad){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function cd(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
592
+ r.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",s,r.encode(e));return [...new Uint8Array(a)].map(u=>u.toString(16).padStart(2,"0")).join("")}catch{}let o=2166136261,i=`${t}\
593
+ |${e}`;for(let s=0;s<i.length;s++)o^=i.charCodeAt(s),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function Vo(t){let n=ir()?.env?.BVSALA_SEAT_ID;if(n&&ud.test(n))return n;let r=await sd();
594
+ if(!r)return;let o=await cd(t,r);if(o)return `m-${o.slice(0,32)}`}var ud=/^[A-Za-z0-9._:/-]{1,128}$/;var Oa={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function Aa(t){return {exactCache:t.exactCache??new yn,semanticCache:t.semanticCache,singleflight:t.singleflight??new kn,resolvers:t.resolvers??Bi(),router:t.router??new xn,toolSelector:t.toolSelector??
595
+ new wn,formatSelector:t.formatSelector??new Rn({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new Cn,constraintBackends:t.constraintBackends??[]}}var ld=36e5,dd=7*86400,pd=3e4,sr=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;avisadoDeCredencial=false;currentExpiresAt;currentOrg;constructor(e){this.opts=
596
+ e,this.pollIntervalMs=e.pollIntervalMs??ld,this.refreshLeadSeconds=e.refreshLeadSeconds??dd;let n=xt(kt(e.initialToken),e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.expires_at:
529
597
  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=
530
598
  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.
531
599
  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??
532
- Eu);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:"applicatio\
600
+ pd);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:"applicatio\
533
601
  n/json"}});if(!o.ok)return (o.status===401||o.status===403||o.status===404)&&!this.avisadoDeCredencial&&(this.avisadoDeCredencial=!0,console.warn(`[bv-sala] automatic pickup of the renewed license is f\
534
602
  ailing with HTTP ${o.status} at ${this.opts.url}. Check 'serviceAccountKey' (rotated? from another organization?) and 'licenseServerUrl': until this works, the token will NOT renew itself and the SDK \
535
- will stop operating when the grace period ends.`)),!1;let s=await o.json();if(typeof s.token!="string")return !1;let i=Ze(s.token),a=Xe(i,this.opts.publicKey);return !a.signatureValid||!a.payload||a.payload.
603
+ will stop operating when the grace period ends.`)),!1;let i=await o.json();if(typeof i.token!="string")return !1;let s=kt(i.token),a=xt(s,this.opts.publicKey);return !a.signatureValid||!a.payload||a.payload.
536
604
  expires_at<=this.currentExpiresAt||this.currentOrg&&a.payload.org_id!==this.currentOrg||this.opts.revocados?.snapshot().has(a.payload.jti)||this.parado?!1:(this.currentExpiresAt=a.payload.expires_at,this.
537
- currentOrg=a.payload.org_id,this.opts.onNewToken(i),!0)}catch{return false}finally{clearTimeout(n),this.controller===e&&(this.controller=null),this.enVuelo=false;}}};var Ru={"gpt-4.1":false,"gpt-4.1-mini":false,"gpt-4.1-nano":false,"gpt-4o":false,"gpt-4o-mini":false,"gpt-4-turbo":false,"gpt-4":false,"gpt-3.5-turbo":false,"gpt-5":true,"gpt-5-codex":true,"gpt-5-mini":true,"gpt-5-nano":true,"gpt-5.\
605
+ currentOrg=a.payload.org_id,this.opts.onNewToken(s),!0)}catch{return false}finally{clearTimeout(n),this.controller===e&&(this.controller=null),this.enVuelo=false;}}};var fd={"gpt-4.1":false,"gpt-4.1-mini":false,"gpt-4.1-nano":false,"gpt-4o":false,"gpt-4o-mini":false,"gpt-4-turbo":false,"gpt-4":false,"gpt-3.5-turbo":false,"gpt-5":true,"gpt-5-codex":true,"gpt-5-mini":true,"gpt-5-nano":true,"gpt-5.\
538
606
  1-codex":true,"gpt-5.1-codex-max":true,"gpt-5.1-codex-mini":true,"gpt-5.1-thinking":true,"gpt-5.2":true,"gpt-5.2-codex":true,"gpt-5.3-codex":true,"gpt-5.4":true,"gpt-5.4-mini":true,"gpt-5.4-nano":true,"gpt-5.5":true,"gpt-5\
539
- .6-luna":true,"gpt-5.6-sol":true,"gpt-5.6-terra":true,o3:true,"o3-mini":true,"o3-pro":true,"o4-mini":true,"claude-opus-4-5":false,"claude-opus-4-6":false,"claude-opus-4-7":false,"claude-opus-4-8":false,"claude-opus-5":true,"clau\
540
- de-opus-4":false,"claude-sonnet-4-5":false,"claude-sonnet-4-6":false,"claude-sonnet-5":true,"claude-fable-5":true,"claude-fable-5-1":true,"claude-mythos-5-1":true,"claude-mythos-5":true,"claude-sonnet-4":false,"claude-haik\
541
- u-4-5":false,"claude-3-5-sonnet":false,"claude-3-5-haiku":false,"claude-3-opus":false,"claude-3-haiku":false,"gemini-3.7-flash":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini\
542
- -2.5-pro":true,"gemini-2.5-flash":true},Cu=new Set(["claude-opus-4-7","claude-opus-4-8"]),Iu=[/^o\d/,/^gpt-5/,/^gpt-oss/,/^gemini-(2\.5|[3-9])/,/^claude-[a-z]+-([5-9]|\d{2})/,/^grok-(3-mini|[4-9])/,/reason/,
543
- /think/,/(^|[-_.])r\d($|[-_.])/,/^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function wi(t){let e=t.lastIndexOf("/"),n=(e>=0?t.slice(e+1):t).toLowerCase();if(Iu.some(s=>s.test(n)))return "reaso\
544
- ning-model";let r=Vn(t);if(r===void 0)return "unclassified-model";let o=Ru[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(Cu.has(r))return "temperature-ignored"}var Jr={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},Si={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},_u=[["claude-fable-5-1",512],["claude-mytho\
545
- s-5-1",512],["claude-fable-5",512],["claude-mythos-5",512],["claude-opus-5",512],["claude-opus-4-7",2048],["claude-opus-4-6",4096],["claude-opus-4-5",4096],["claude-haiku-4-5",4096],["claude-3-5-haiku",
546
- 2048]];function Wr(t){for(let[e,n]of _u)if(t===e||t.startsWith(`${e}-`))return {...Si,minimumCacheTokens:n};return Si}var Gr={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1};var Ti={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function In(t,e,n,r){let o=r.minimumCacheTokens;if(o==null||t<o)return t;let s=Math.min(e,t),i=t-s,a=Math.min(1,Math.max(0,
547
- n)),c=a*s*r.cacheReadMultiplier+(1-a)*s*r.cacheWriteMultiplier;return i+c}function Yr(t){let e=In(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=In(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??
548
- 0),r=e-n,o=t.tier.minimumCacheTokens,i=o!=null&&t.originalTokens>=o&&t.compressedTokens<o,a;if(r<=0){let c=e<t.originalTokens;a=i?`compressing drops the prompt out of the cacheable tier (${t.compressedTokens}\
549
- < ${o}) and costs more than it saves`:c?`not compressing is cheaper: the provider's prefix cache already discounts this prompt (${e.toFixed(0)} vs ${n.toFixed(0)} equivalent tokens, at a ${(t.prefixHitRate*
550
- 100).toFixed(0)}% hit rate)`:"the saving does not cover the compressor's cost";}else i?a=`pays off even after losing the prefix cache (${(t.prefixHitRate*100).toFixed(0)}% hit rate)`:a="pays off and do\
551
- es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function Ei(t){let e=o=>Yr({...t,prefixHitRate:o}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,
552
- r=1;for(let o=0;o<40;o++){let s=(n+r)/2;e(s)>0?n=s:r=s;}return (n+r)/2}function Pu(t){let e=Ei({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(In(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.
553
- totalTokens?null:1)}var _n=class{exploracion;estados=new Map;constructor(e={}){this.exploracion=Math.max(1,e.exploracion??8);}costeDeExploracion(e,n){return this.exploracion*Math.max(0,n.cacheWriteMultiplier-
554
- 1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=Pu(n),o=this.estados.get(e),s=Du(o);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:r,observada:s}:r==null?
555
- {marcar:true,razon:"marking cannot lose money at this tier (no write premium)",umbral:r,observada:s}:o?.apagada?{marcar:false,razon:`prefix-cache marking OFF: measured hit rate ${tt(s)} did not reach the ${tt(
556
- r)} break-even, so marking was costing money`,umbral:r,observada:s}:o==null||o.marcadas<this.exploracion?{marcar:true,razon:`exploring the prefix cache (${o?.marcadas??0}/${this.exploracion}); hit rate \
557
- is only observable on requests that were marked`,umbral:r,observada:s}:s!=null&&s>r?{marcar:true,razon:`measured hit rate ${tt(s)} beats the ${tt(r)} break-even`,umbral:r,observada:s}:(o.apagada=true,{marcar:false,
558
- razon:`prefix-cache marking OFF: measured hit rate ${tt(s)} did not reach the ${tt(r)} break-even, so marking was costing money`,umbral:r,observada:s})}registrar(e,n){let r=this.estados.get(e)??{marcadas:0,
559
- tokensLeidos:0,tokensEscritos:0,apagada:false};r.marcadas+=1,r.tokensLeidos+=Math.max(0,n.cachedInputTokens??0),r.tokensEscritos+=Math.max(0,n.cacheWriteInputTokens??0),this.estados.set(e,r);}};function Du(t){
560
- if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function tt(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var Ri=.5;function Ou(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function Au(t){return 1-t}function Mu(t,e=Ri){return e-t}function Ci(t,e,n=Ri){
561
- if(!t||!e)return null;let r=Ou(t,e);if(r==null||!Number.isFinite(r))return null;let o=Au(r),s=Mu(r,n),i=s>0,a=c=>`${(c*100).toFixed(1)}%`;return {r,equilibrio:o,escaladoMaximo:s,viable:i,razon:i?`the c\
562
- heap model costs ${a(r)} of the strong one, so routing pays off while escalations stay under ${a(s)} (it stops saving money at ${a(o)})`:`the cheap model costs ${a(r)} of the strong one: even with zer\
563
- o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var Zr={"gpt-4":"gpt-4o","gpt-4-turbo":"gpt-4o-mini","gpt-4o":"gpt-4o-mini","gpt-4.1":"gpt-4.1-mini","cla\
564
- ude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-opus":"claude-3-haiku","claude-3-5-sonnet":"claude-3-5-haiku"};function Lu(t){return Object.keys(t).sort((e,n)=>n.length-e.
565
- length||e.localeCompare(n))}function Ii(t,e=Zr){if(!t)return null;let n=t.lastIndexOf("/"),r=n>=0?t.slice(0,n+1):"",o=n>=0?t.slice(n+1):t,s=e[t]??e[o]??Nu(o,e);return !s||s===o?null:r+s}function Nu(t,e){
566
- for(let n of Lu(e))if(t.startsWith(n)&&t.charAt(n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var Pn=class{exploracion;estados=new Map;constructor(e={}){this.exploracion=Math.max(1,e.exploracion??20);}costeDeExploracion(e){return this.exploracion*Math.max(0,e)}estado(e){return this.estados.get(
567
- e)}decidir(e,n){let r=this.estados.get(e),o=ju(r),s=r?.enrutadas??0,i=a=>a==null?"n/a":`${(a*100).toFixed(1)}%`;return r?.apagada?{enrutar:false,razon:`model cascade OFF for this workload: measured escal\
568
- ation rate ${i(o)} is at or above the ${i(n.equilibrio)} break-even, so routing was costing money`,observada:o,muestras:s}:s<this.exploracion?{enrutar:true,razon:`measuring this workload (${s}/${this.exploracion}\
569
- ); the escalation rate is only observable on requests that were actually routed`,observada:o,muestras:s}:o!=null&&o<n.equilibrio?{enrutar:true,razon:`measured escalation rate ${i(o)} stays under the ${i(
570
- n.equilibrio)} break-even (this is a MONEY check, not a quality one)`,observada:o,muestras:s}:(r&&(r.apagada=true),{enrutar:false,razon:`model cascade OFF for this workload: measured escalation rate ${i(o)}\
571
- is at or above the ${i(n.equilibrio)} break-even, so routing was costing money`,observada:o,muestras:s})}registrar(e,n){let r=this.estados.get(e)??{enrutadas:0,escaladas:0,apagada:false};r.enrutadas+=1,
572
- n&&(r.escaladas+=1),this.estados.set(e,r);}};function ju(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var Bu=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function Fu(t){return t?Xr(t)?"value-constrained":"structural":"none"}function Xr(t,e=0){if(e>12)return false;let n=t;
573
- for(let r of Bu)if(n[r]!==void 0)return true;if(t.properties){for(let r of Object.values(t.properties))if(Xr(r,e+1))return true}return !!(t.items&&Xr(t.items,e+1))}function _i(t){let e=Fu(t.schema),n=(t.tools??
607
+ .6-luna":true,"gpt-5.6-sol":true,"gpt-5.6-terra":true,"gpt-6-astra":true,"gpt-6-sol":true,"gpt-6-luna":true,o3:true,"o3-mini":true,"o3-pro":true,"o4-mini":true,"claude-opus-4-5":false,"claude-opus-4-6":false,"claude-opus-4-7":false,
608
+ "claude-opus-4-8":false,"claude-opus-5":true,"claude-opus-5-5":true,"claude-opus-4":false,"claude-sonnet-4-5":false,"claude-sonnet-4-6":false,"claude-sonnet-5":true,"claude-fable-5":true,"claude-fable-5-1":true,"claude-myt\
609
+ hos-5-1":true,"claude-mythos-5":true,"claude-sonnet-4":false,"claude-haiku-4-5":false,"claude-3-5-sonnet":false,"claude-3-5-haiku":false,"claude-3-opus":false,"claude-3-haiku":false,"gemini-3.8-flash":true,"gemini-3.7-flash":true,
610
+ "gemini-3.6-flash":true,"gemini-3.1-flash-lite":true,"gemini-3-flash-preview":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini-2.5-pro":true,"gemini-2.5-flash":true},md=new Set(
611
+ ["claude-opus-4-7","claude-opus-4-8"]),hd=[/^o\d/,/^gpt-5/,/^gpt-([6-9]|\d{2})/,/^gpt-oss/,/^gemini-(2\.5|[3-9])/,/^claude-[a-z]+-([5-9]|\d{2})/,/^grok-(3-mini|[4-9])/,/reason/,/think/,/(^|[-_.])r\d($|[-_.])/,
612
+ /^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Ma(t){let e=t.lastIndexOf("/"),n=(e>=0?t.slice(e+1):t).toLowerCase();if(hd.some(i=>i.test(n)))return "reasoning-model";let r=ut(t);if(r===void 0)
613
+ return "unclassified-model";let o=fd[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(md.has(r))return "temperature-ignored"}var Uo={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},La={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},gd=[["claude-fable-5-1",512],["claude-mytho\
614
+ s-5-1",512],["claude-fable-5",512],["claude-mythos-5",512],["claude-opus-5-5",512],["claude-opus-5",512],["claude-opus-4-7",2048],["claude-opus-4-6",4096],["claude-opus-4-5",4096],["claude-haiku-4-5",
615
+ 4096],["claude-3-5-haiku",2048]];function qo(t){for(let[e,n]of gd)if(t===e||t.startsWith(`${e}-`))return {...La,minimumCacheTokens:n};return La}var Ho={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1};var Na={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function ar(t,e,n,r){let o=r.minimumCacheTokens;if(o==null||t<o)return t;let i=Math.min(e,t),s=t-i,a=Math.min(1,Math.max(0,
616
+ n)),u=a*i*r.cacheReadMultiplier+(1-a)*i*r.cacheWriteMultiplier;return s+u}function Wo(t){let e=ar(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=ar(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??
617
+ 0),r=e-n,o=t.tier.minimumCacheTokens,s=o!=null&&t.originalTokens>=o&&t.compressedTokens<o,a;if(r<=0){let u=e<t.originalTokens;a=s?`compressing drops the prompt out of the cacheable tier (${t.compressedTokens}\
618
+ < ${o}) and costs more than it saves`:u?`not compressing is cheaper: the provider's prefix cache already discounts this prompt (${e.toFixed(0)} vs ${n.toFixed(0)} equivalent tokens, at a ${(t.prefixHitRate*
619
+ 100).toFixed(0)}% hit rate)`:"the saving does not cover the compressor's cost";}else s?a=`pays off even after losing the prefix cache (${(t.prefixHitRate*100).toFixed(0)}% hit rate)`:a="pays off and do\
620
+ es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function ja(t){let e=o=>Wo({...t,prefixHitRate:o}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,
621
+ r=1;for(let o=0;o<40;o++){let i=(n+r)/2;e(i)>0?n=i:r=i;}return (n+r)/2}function bd(t){let e=ja({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(ar(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.
622
+ totalTokens?null:1)}var cr=class{exploracion;estados=new Map;constructor(e={}){this.exploracion=Math.max(1,e.exploracion??8);}costeDeExploracion(e,n){return this.exploracion*Math.max(0,n.cacheWriteMultiplier-
623
+ 1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=bd(n),o=this.estados.get(e),i=vd(o);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:r,observada:i}:r==null?
624
+ {marcar:true,razon:"marking cannot lose money at this tier (no write premium)",umbral:r,observada:i}:o?.apagada?{marcar:false,razon:`prefix-cache marking OFF: measured hit rate ${Tt(i)} did not reach the ${Tt(
625
+ r)} break-even, so marking was costing money`,umbral:r,observada:i}:o==null||o.marcadas<this.exploracion?{marcar:true,razon:`exploring the prefix cache (${o?.marcadas??0}/${this.exploracion}); hit rate \
626
+ is only observable on requests that were marked`,umbral:r,observada:i}:i!=null&&i>r?{marcar:true,razon:`measured hit rate ${Tt(i)} beats the ${Tt(r)} break-even`,umbral:r,observada:i}:(o.apagada=true,{marcar:false,
627
+ razon:`prefix-cache marking OFF: measured hit rate ${Tt(i)} did not reach the ${Tt(r)} break-even, so marking was costing money`,umbral:r,observada:i})}registrar(e,n){let r=this.estados.get(e)??{marcadas:0,
628
+ tokensLeidos:0,tokensEscritos:0,apagada:false};r.marcadas+=1,r.tokensLeidos+=Math.max(0,n.cachedInputTokens??0),r.tokensEscritos+=Math.max(0,n.cacheWriteInputTokens??0),this.estados.set(e,r);}};function vd(t){
629
+ if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function Tt(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var $a=.5;function yd(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function kd(t){return 1-t}function xd(t,e=$a){return e-t}function Fa(t,e,n=$a){
630
+ if(!t||!e)return null;let r=yd(t,e);if(r==null||!Number.isFinite(r))return null;let o=kd(r),i=xd(r,n),s=i>0,a=u=>`${(u*100).toFixed(1)}%`;return {r,equilibrio:o,escaladoMaximo:i,viable:s,razon:s?`the c\
631
+ heap model costs ${a(r)} of the strong one, so routing pays off while escalations stay under ${a(i)} (it stops saving money at ${a(o)})`:`the cheap model costs ${a(r)} of the strong one: even with zer\
632
+ o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var Ko={"gpt-4":"gpt-4o","gpt-4-turbo":"gpt-4o-mini","gpt-4o":"gpt-4o-mini","gpt-4.1":"gpt-4.1-mini","cla\
633
+ ude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-opus":"claude-3-haiku","claude-3-5-sonnet":"claude-3-5-haiku"};function wd(t){return Object.keys(t).sort((e,n)=>n.length-e.
634
+ length||e.localeCompare(n))}function Ba(t,e=Ko){if(!t)return null;let n=t.lastIndexOf("/"),r=n>=0?t.slice(0,n+1):"",o=n>=0?t.slice(n+1):t,i=e[t]??e[o]??Sd(o,e);return !i||i===o?null:r+i}function Sd(t,e){
635
+ for(let n of wd(e))if(t.startsWith(n)&&t.charAt(n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var ur=class{exploracion;estados=new Map;constructor(e={}){this.exploracion=Math.max(1,e.exploracion??20);}costeDeExploracion(e){return this.exploracion*Math.max(0,e)}estado(e){return this.estados.get(
636
+ e)}decidir(e,n){let r=this.estados.get(e),o=Td(r),i=r?.enrutadas??0,s=a=>a==null?"n/a":`${(a*100).toFixed(1)}%`;return r?.apagada?{enrutar:false,razon:`model cascade OFF for this workload: measured escal\
637
+ ation rate ${s(o)} is at or above the ${s(n.equilibrio)} break-even, so routing was costing money`,observada:o,muestras:i}:i<this.exploracion?{enrutar:true,razon:`measuring this workload (${i}/${this.exploracion}\
638
+ ); the escalation rate is only observable on requests that were actually routed`,observada:o,muestras:i}:o!=null&&o<n.equilibrio?{enrutar:true,razon:`measured escalation rate ${s(o)} stays under the ${s(
639
+ n.equilibrio)} break-even (this is a MONEY check, not a quality one)`,observada:o,muestras:i}:(r&&(r.apagada=true),{enrutar:false,razon:`model cascade OFF for this workload: measured escalation rate ${s(o)}\
640
+ is at or above the ${s(n.equilibrio)} break-even, so routing was costing money`,observada:o,muestras:i})}registrar(e,n){let r=this.estados.get(e)??{enrutadas:0,escaladas:0,apagada:false};r.enrutadas+=1,
641
+ n&&(r.escaladas+=1),this.estados.set(e,r);}};function Td(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var Ed=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function Rd(t){return t?Go(t)?"value-constrained":"structural":"none"}function Go(t,e=0){if(e>12)return false;let n=t;
642
+ for(let r of Ed)if(n[r]!==void 0)return true;if(t.properties){for(let r of Object.values(t.properties))if(Go(r,e+1))return true}return !!(t.items&&Go(t.items,e+1))}function za(t){let e=Rd(t.schema),n=(t.tools??
574
643
  []).filter(r=>r.risk==="write"||r.risk==="destructive");return n.length>0?{elegible:false,fuerza:e,razon:`the request carries ${n.length} write/destructive tool(s); a cheaper model's choice of ACTION can\
575
644
  not be checked by an output contract, so the cascade never applies here`}:e==="none"?{elegible:false,fuerza:e,razon:"no output contract: the deterministic verifier would accept anything, which would repo\
576
645
  rt a perfect escalation rate over answers nobody checked. Declare `response.schema` to route"}:{elegible:true,fuerza:e,razon:e==="value-constrained"?"output contract carries value constraints, so wrong \
577
- content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function Qr(t){let e=[];if(e.push("non-empty"),t.texto.trim()==="")return {acepta:false,
646
+ content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function Jo(t){let e=[];if(e.push("non-empty"),t.texto.trim()==="")return {acepta:false,
578
647
  motivo:"the cheap model returned an empty answer",comprobaciones:e};if(e.push("final-answer"),t.pidioHerramientas)return {acepta:false,motivo:"the cheap model asked to run tools: that is an action, not a \
579
648
  final answer, and the output contract cannot check it",comprobaciones:e};if(e.push("not-truncated"),t.finishReason==="length")return {acepta:false,motivo:"the cheap model's answer was cut off by maxOutput\
580
649
  Tokens",comprobaciones:e};if(e.push("output-contract"),!t.schema)return {acepta:false,motivo:"no output contract to verify against",comprobaciones:e};let n;try{n=JSON.parse(t.texto);}catch{return {acepta:false,
581
- motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=ee(n,t.schema);return r.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
582
- acepta:false,motivo:`the cheap model's answer does not satisfy the output contract (${r.errors.slice(0,3).map(s=>`${s.path}: ${s.message}`).join("; ")})`,comprobaciones:e}}function Pi(t,e){let n,r;try{n=
583
- JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=Dn(n),s=Dn(r);return o.length===0&&s.length===0?{divergen:false,motivo:"no comparab\
584
- le facts (free prose only)"}:$u(o,s)?{divergen:false,motivo:"the hard values agree"}:{divergen:true,motivo:"both answers satisfy the contract but disagree on at least one hard value; this is the signature \
585
- of a false valid \u2014 it is a reason to look, never a verdict"}}var zu=40;function Dn(t,e=0,n=[]){if(e>12)return n;if(typeof t=="number"&&Number.isFinite(t))n.push(`n:${t}`);else if(typeof t=="boole\
586
- an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=zu&&n.push(`s:${r.toLowerCase()}`);}else if(Array.isArray(t))for(let r of t)Dn(r,e+1,n);else if(t&&typeof t=="objec\
587
- t")for(let r of Object.keys(t).sort())Dn(t[r],e+1,n);return n.sort()}function $u(t,e){if(t.length!==e.length)return false;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return false;return true}var Di="the layer measures both worlds against the same provider so that no baseline can be fabricated, keeps one ledger per lever, and refuses to publish a saving whose answer got worse along the way\
588
- , because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function Vu(t){if(t<=0)return "";let e=Di;for(;e.length<t;)e+=Di;return e.slice(
589
- 0,t)}function Uu(t){let e=t[0],n=-1;for(let r of t){let o=JSON.stringify(r)?.length??0;o>n&&(n=o,e=r);}return e}function eo(t){if(t.enum&&t.enum.length>0)return {valor:Uu(t.enum)};switch(t.type??(t.properties?
590
- "object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:Vu(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?
591
- {valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=eo(t.items);return n?{valor:Array.from({length:t.maxItems},()=>n.valor)}:void 0}case "ob\
592
- ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let s=eo(o);if(!s)return;n[r]=s.valor;}return {valor:n}}default:return}}function qu(t){let e=eo(
593
- t);return e?JSON.stringify(e.valor):null}function Oi(t,e){let n=qu(t);return n===null?null:e(n)}var On=16,Ai=64,Hu=8,Ku="measured live on the same triage contract, 8 paired reps each: gpt-4o-mini wrote 16 tokens MORE (-8.2% net) and gpt-4o wrote 3 tokens FEWER (+8.0% net)";function Mi(t,e,n,r={}){
594
- let o=r.minimumSavingsTokens??Hu,s;try{if(ro(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};s=so(t,0);}catch(C){return {applied:false,reason:C instanceof
595
- RangeError?"schema too deep or cyclic":"schema could not be compacted"}}if(s.renamed===0&&s.coded===0)return {applied:false,reason:"nothing to compact (no renameable keys, no codeable enums)"};let i=s.node;
596
- if(!i)return {applied:false,reason:"nothing to compact"};let a=C=>nt(C,i,true),c=C=>nt(C,i,false),u=Xu(t),l=Ju(t,s.compact,i,u);if(!l.ok)return {applied:false,reason:l.reason};let d=e(JSON.stringify(t)),m=e(JSON.stringify(
597
- s.compact)),f=d-m,h=Number.POSITIVE_INFINITY;for(let C of u){let _=e(JSON.stringify(C))-e(JSON.stringify(a(C)));_<h&&(h=_);}Number.isFinite(h)||(h=0);let g=C=>C/1e3*n.inputPer1k,p=C=>C/1e3*n.outputPer1k,
598
- v=g(o),b=n.outputPer1k>0?(o-f)*n.inputPer1k/n.outputPer1k:Number.NEGATIVE_INFINITY,x=Number.isFinite(b)?b.toFixed(1):"any",y=n.inputPer1k>0?`${(n.outputPer1k/n.inputPer1k).toFixed(1)}x`:"more than",k=r.
599
- evidencia;if(k==null)return {applied:false,reason:`no measured output delta for this model, so the codebook is not applied. Short field names change how much the model WRITES, and that is a property of th\
600
- e model, not of the schema: ${Ku}. Here the compact contract saves ${f} input tokens and output is billed ${y} input, so it only pays while the output delta stays above ${x} tokens. Measure yours (ben\
601
- chmarks/ab-live.ts) and pass it in`};let E=k.deltaTokens;if(E<0)return {applied:false,reason:`the measured output delta is ${E} tokens: this model writes MORE from a compact contract (${k.procedencia}). T\
602
- he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${y} input, so no schema is big enough to buy it back`};let w=g(f)+p(E),I=n.inputPer1k>0?w*1e3/
603
- n.inputPer1k:f,O=`+${E} tokens (${E>0?"the model wrote LESS":"no measured change"}), ${k.procedencia}`;return w<v?{applied:false,reason:`net saving $${w.toFixed(9)}/request is below the floor of ${o} inp\
604
- ut tokens ($${v.toFixed(9)}): the compact contract saves ${f} input tokens and the measured output delta is ${O}; break-even at ${x}`}:{applied:true,reason:`net saving $${w.toFixed(9)}/request (${I.toFixed(
605
- 1)} input tokens equivalent): the compact contract saves ${f} input tokens and the measured output delta is ${O}; break-even at ${x}`,plan:{compactSchema:s.compact,expand:c,compact:a,renamedKeys:s.renamed,
606
- codedEnumValues:s.coded,schemaTokensOriginal:d,schemaTokensCompact:m,modelledShapeSavingTokens:h,measuredOutputDeltaTokens:E,outputDeltaProvenance:k.procedencia,breakEvenOutputDeltaTokens:b,netSavingUsd:w}}}
607
- function Ju(t,e,n,r){for(let o of r){if(!ee(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let s=nt(o,n,true);if(!ee(s,e).valid)return {
608
- ok:false,reason:"compact witness does not validate against the compact schema"};if(!oo(nt(s,n,false),o))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function Li(t){return t.type==="ob\
609
- ject"||t.type==null&&t.properties!=null}function Ni(t){return t.type==="array"||t.type==null&&t.items!=null}function Wu(t){let e=t.enum;return !e||e.length===0||e.length>Ai||!e.every(n=>typeof n=="stri\
610
- ng")?null:e}function so(t,e){if(e>On)throw new RangeError("schema too deep");let n=Wu(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=ji(n,true);if(!r)return {compact:t,renamed:0,
611
- coded:0};let o=[...r].filter(([i,a])=>i!==a).length;if(o===0)return {compact:t,renamed:0,coded:0};let s=new Map;for(let[i,a]of r)s.set(a,i);return {compact:{...t,enum:n.map(i=>r.get(i))},node:{enumFwd:r,
612
- enumBack:s},renamed:0,coded:o}}return Li(t)?Gu(t,e):Ni(t)?Yu(t,e):{compact:t,renamed:0,coded:0}}function Gu(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};
613
- let r=0,o=0,s=new Map,i=new Map;for(let[m,f]of n){let h=so(f,e+1);i.set(m,h.compact),h.node&&s.set(m,h.node),r+=h.renamed,o+=h.coded;}let a=null;t.additionalProperties===false&&(a=ji(n.map(([m])=>m),false));
614
- let c={};for(let[m]of n)c[a?.get(m)??m]=i.get(m);let u={...t,properties:c};t.required&&(u.required=t.required.map(m=>a?.get(m)??m));let l={};if(a){let m=new Map;for(let[h,g]of a)m.set(g,h);let f=false;for(let[
615
- h,g]of a)h!==g&&(f=true);if(f){l.keysFwd=a,l.keysBack=m;for(let[h,g]of a)h!==g&&(r+=1);}}s.size>0&&(l.props=s);let d=!l.keysFwd&&!l.props;return {compact:u,...d?{}:{node:l},renamed:r,coded:o}}function Yu(t,e){
616
- if(!t.items)return {compact:t,renamed:0,coded:0};let n=so(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function ji(t,e){let n=[
617
- ...t].sort(),r=new Set,o=new Map;n.forEach((i,a)=>{let c=e?i.toUpperCase():i,u=i;for(let l=1;l<i.length;l++){let d=c.slice(0,l);if(!r.has(d)){u=d;break}}if(u===i){let l=a.toString(36);l.length<i.length&&
618
- !r.has(l)&&(u=l);}r.add(u),o.set(i,u);});let s=new Set(t);for(let[i,a]of o)if(a!==i&&s.has(a))return null;return o}function nt(t,e,n){let r=n?e.enumFwd:e.enumBack;if(r&&typeof t=="string")return r.get(t)??
619
- t;if(e.items&&Array.isArray(t))return t.map(s=>nt(s,e.items,n));let o=n?e.keysFwd:e.keysBack;if((o||e.props)&&Zu(t)){let s={};for(let[i,a]of Object.entries(t)){let c=o?.get(i)??i,u=n?i:c,l=e.props?.get(
620
- u);s[c]=l?nt(a,l,n):a;}return s}return t}function Zu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Xu(t){let e=Math.min(Ai,Math.max(1,to(t,0))),n=[];for(let r=0;r<e;r++)n.push(no(t,
621
- r,0));return n}function to(t,e){if(e>On)return 0;let n=t.enum?.length??0;for(let r of Object.values(t.properties??{}))n=Math.max(n,to(r,e+1));return t.items&&(n=Math.max(n,to(t.items,e+1))),n}function no(t,e,n){
622
- if(n>On)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(Li(t)){let r={};for(let[o,s]of Object.entries(t.properties??{}))r[o]=no(s,e,n+1);return r}if(Ni(t)){if(t.maxItems===
623
- 0)return [];let r=Math.max(1,t.minItems??1),o=t.maxItems!=null?Math.min(r,t.maxItems):r,s=t.items;return Array.from({length:o},()=>s?no(s,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";
650
+ motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=de(n,t.schema);return r.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
651
+ acepta:false,motivo:`the cheap model's answer does not satisfy the output contract (${r.errors.slice(0,3).map(i=>`${i.path}: ${i.message}`).join("; ")})`,comprobaciones:e}}function Va(t,e){let n,r;try{n=
652
+ JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=lr(n),i=lr(r);return o.length===0&&i.length===0?{divergen:false,motivo:"no comparab\
653
+ le facts (free prose only)"}:Id(o,i)?{divergen:false,motivo:"the hard values agree"}:{divergen:true,motivo:"both answers satisfy the contract but disagree on at least one hard value; this is the signature \
654
+ of a false valid \u2014 it is a reason to look, never a verdict"}}var Cd=40;function lr(t,e=0,n=[]){if(e>12)return n;if(typeof t=="number"&&Number.isFinite(t))n.push(`n:${t}`);else if(typeof t=="boole\
655
+ an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=Cd&&n.push(`s:${r.toLowerCase()}`);}else if(Array.isArray(t))for(let r of t)lr(r,e+1,n);else if(t&&typeof t=="objec\
656
+ t")for(let r of Object.keys(t).sort())lr(t[r],e+1,n);return n.sort()}function Id(t,e){if(t.length!==e.length)return false;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return false;return true}var Ua="the layer measures both worlds against the same provider so that no baseline can be fabricated, keeps one ledger per lever, and refuses to publish a saving whose answer got worse along the way\
657
+ , because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function Pd(t){if(t<=0)return "";let e=Ua;for(;e.length<t;)e+=Ua;return e.slice(
658
+ 0,t)}function _d(t){let e=t[0],n=-1;for(let r of t){let o=JSON.stringify(r)?.length??0;o>n&&(n=o,e=r);}return e}function Yo(t){if(t.enum&&t.enum.length>0)return {valor:_d(t.enum)};switch(t.type??(t.properties?
659
+ "object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:Pd(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?
660
+ {valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=Yo(t.items);return n?{valor:Array.from({length:t.maxItems},()=>n.valor)}:void 0}case "ob\
661
+ ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let i=Yo(o);if(!i)return;n[r]=i.valor;}return {valor:n}}default:return}}function Dd(t){let e=Yo(
662
+ t);return e?JSON.stringify(e.valor):null}function qa(t,e){let n=Dd(t);return n===null?null:e(n)}var dr=16,Ha=64,Od=8,Ad="measured live on the same triage contract, 8 paired reps each: gpt-4o-mini wrote 16 tokens MORE (-8.2% net) and gpt-4o wrote 3 tokens FEWER (+8.0% net)";function Wa(t,e,n,r={}){
663
+ let o=r.minimumSavingsTokens??Od,i;try{if(Qo(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};i=ti(t,0);}catch(O){return {applied:false,reason:O instanceof
664
+ RangeError?"schema too deep or cyclic":"schema could not be compacted"}}if(i.renamed===0&&i.coded===0)return {applied:false,reason:"nothing to compact (no renameable keys, no codeable enums)"};let s=i.node;
665
+ if(!s)return {applied:false,reason:"nothing to compact"};let a=O=>Et(O,s,true),u=O=>Et(O,s,false),c=Fd(t),l=Md(t,i.compact,s,c);if(!l.ok)return {applied:false,reason:l.reason};let d=e(JSON.stringify(t)),f=e(JSON.stringify(
666
+ i.compact)),m=d-f,h=Number.POSITIVE_INFINITY;for(let O of c){let _=e(JSON.stringify(O))-e(JSON.stringify(a(O)));_<h&&(h=_);}Number.isFinite(h)||(h=0);let b=O=>O/1e3*n.inputPer1k,p=O=>O/1e3*n.outputPer1k,
667
+ v=b(o),g=n.outputPer1k>0?(o-m)*n.inputPer1k/n.outputPer1k:Number.NEGATIVE_INFINITY,y=Number.isFinite(g)?g.toFixed(1):"any",k=n.inputPer1k>0?`${(n.outputPer1k/n.inputPer1k).toFixed(1)}x`:"more than",x=r.
668
+ evidencia;if(x==null)return {applied:false,reason:`no measured output delta for this model, so the codebook is not applied. Short field names change how much the model WRITES, and that is a property of th\
669
+ e model, not of the schema: ${Ad}. Here the compact contract saves ${m} input tokens and output is billed ${k} input, so it only pays while the output delta stays above ${y} tokens. Measure yours (ben\
670
+ chmarks/ab-live.ts) and pass it in`};let T=x.deltaTokens;if(T<0)return {applied:false,reason:`the measured output delta is ${T} tokens: this model writes MORE from a compact contract (${x.procedencia}). T\
671
+ he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${k} input, so no schema is big enough to buy it back`};let w=b(m)+p(T),R=n.inputPer1k>0?w*1e3/
672
+ n.inputPer1k:m,D=`+${T} tokens (${T>0?"the model wrote LESS":"no measured change"}), ${x.procedencia}`;return w<v?{applied:false,reason:`net saving $${w.toFixed(9)}/request is below the floor of ${o} inp\
673
+ ut tokens ($${v.toFixed(9)}): the compact contract saves ${m} input tokens and the measured output delta is ${D}; break-even at ${y}`}:{applied:true,reason:`net saving $${w.toFixed(9)}/request (${R.toFixed(
674
+ 1)} input tokens equivalent): the compact contract saves ${m} input tokens and the measured output delta is ${D}; break-even at ${y}`,plan:{compactSchema:i.compact,expand:u,compact:a,renamedKeys:i.renamed,
675
+ codedEnumValues:i.coded,schemaTokensOriginal:d,schemaTokensCompact:f,modelledShapeSavingTokens:h,measuredOutputDeltaTokens:T,outputDeltaProvenance:x.procedencia,breakEvenOutputDeltaTokens:g,netSavingUsd:w}}}
676
+ function Md(t,e,n,r){for(let o of r){if(!de(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let i=Et(o,n,true);if(!de(i,e).valid)return {
677
+ ok:false,reason:"compact witness does not validate against the compact schema"};if(!ei(Et(i,n,false),o))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function Ka(t){return t.type==="ob\
678
+ ject"||t.type==null&&t.properties!=null}function Ga(t){return t.type==="array"||t.type==null&&t.items!=null}function Ld(t){let e=t.enum;return !e||e.length===0||e.length>Ha||!e.every(n=>typeof n=="stri\
679
+ ng")?null:e}function ti(t,e){if(e>dr)throw new RangeError("schema too deep");let n=Ld(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=Ja(n,true);if(!r)return {compact:t,renamed:0,
680
+ coded:0};let o=[...r].filter(([s,a])=>s!==a).length;if(o===0)return {compact:t,renamed:0,coded:0};let i=new Map;for(let[s,a]of r)i.set(a,s);return {compact:{...t,enum:n.map(s=>r.get(s))},node:{enumFwd:r,
681
+ enumBack:i},renamed:0,coded:o}}return Ka(t)?Nd(t,e):Ga(t)?jd(t,e):{compact:t,renamed:0,coded:0}}function Nd(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};
682
+ let r=0,o=0,i=new Map,s=new Map;for(let[f,m]of n){let h=ti(m,e+1);s.set(f,h.compact),h.node&&i.set(f,h.node),r+=h.renamed,o+=h.coded;}let a=null;t.additionalProperties===false&&(a=Ja(n.map(([f])=>f),false));
683
+ let u={};for(let[f]of n)u[a?.get(f)??f]=s.get(f);let c={...t,properties:u};t.required&&(c.required=t.required.map(f=>a?.get(f)??f));let l={};if(a){let f=new Map;for(let[h,b]of a)f.set(b,h);let m=false;for(let[
684
+ h,b]of a)h!==b&&(m=true);if(m){l.keysFwd=a,l.keysBack=f;for(let[h,b]of a)h!==b&&(r+=1);}}i.size>0&&(l.props=i);let d=!l.keysFwd&&!l.props;return {compact:c,...d?{}:{node:l},renamed:r,coded:o}}function jd(t,e){
685
+ if(!t.items)return {compact:t,renamed:0,coded:0};let n=ti(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function Ja(t,e){let n=[
686
+ ...t].sort(),r=new Set,o=new Map;n.forEach((s,a)=>{let u=e?s.toUpperCase():s,c=s;for(let l=1;l<s.length;l++){let d=u.slice(0,l);if(!r.has(d)){c=d;break}}if(c===s){let l=a.toString(36);l.length<s.length&&
687
+ !r.has(l)&&(c=l);}r.add(c),o.set(s,c);});let i=new Set(t);for(let[s,a]of o)if(a!==s&&i.has(a))return null;return o}function Et(t,e,n){let r=n?e.enumFwd:e.enumBack;if(r&&typeof t=="string")return r.get(t)??
688
+ t;if(e.items&&Array.isArray(t))return t.map(i=>Et(i,e.items,n));let o=n?e.keysFwd:e.keysBack;if((o||e.props)&&$d(t)){let i={};for(let[s,a]of Object.entries(t)){let u=o?.get(s)??s,c=n?s:u,l=e.props?.get(
689
+ c);i[u]=l?Et(a,l,n):a;}return i}return t}function $d(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Fd(t){let e=Math.min(Ha,Math.max(1,Zo(t,0))),n=[];for(let r=0;r<e;r++)n.push(Xo(t,
690
+ r,0));return n}function Zo(t,e){if(e>dr)return 0;let n=t.enum?.length??0;for(let r of Object.values(t.properties??{}))n=Math.max(n,Zo(r,e+1));return t.items&&(n=Math.max(n,Zo(t.items,e+1))),n}function Xo(t,e,n){
691
+ if(n>dr)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(Ka(t)){let r={};for(let[o,i]of Object.entries(t.properties??{}))r[o]=Xo(i,e,n+1);return r}if(Ga(t)){if(t.maxItems===
692
+ 0)return [];let r=Math.max(1,t.minItems??1),o=t.maxItems!=null?Math.min(r,t.maxItems):r,i=t.items;return Array.from({length:o},()=>i?Xo(i,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";
624
693
  let r=Math.max(1,t.minLength??1),o=t.maxLength!=null?Math.min(r,t.maxLength):r;return "x".repeat(o)}case "number":case "integer":{let r=t.minimum??1;return t.maximum!=null&&r>t.maximum&&(r=t.maximum),t.type===
625
- "integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function ro(t,e){if(e>On)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.
626
- values(t.properties??{}))if(ro(n,e+1))return true;return !!(t.items&&ro(t.items,e+1))}function oo(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.
627
- 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(!oo(t[i],e[i]))return false;return true}let o=Object.keys(t),s=Object.keys(e);if(o.length!==s.length)
628
- return false;for(let i of o)if(!Object.prototype.hasOwnProperty.call(e,i)||!oo(t[i],e[i]))return false;return true}var Qu="2026-08-14",Bi={"gpt-4o-mini":{deltaTokens:-16,salidaDelBrazoA:72,contrato:"triage (6 fields, long enums)",pares:8},"gpt-4o":{deltaTokens:3,salidaDelBrazoA:75,contrato:"triage (6 fields, long \
629
- enums)",pares:8}},el=$n(Bi);function tl(t){return Bt(Bi,el,t)}var An=class t{deltas=new Map;static clave(e,n){return `${e}\0${n}`}recordar(e,n,r){this.deltas.set(t.clave(e,n),r);}resolver(e,n,r){if(r!=null&&
694
+ "integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function Qo(t,e){if(e>dr)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.
695
+ values(t.properties??{}))if(Qo(n,e+1))return true;return !!(t.items&&Qo(t.items,e+1))}function ei(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.
696
+ isArray(t),r=Array.isArray(e);if(n||r){if(!n||!r||t.length!==e.length)return false;for(let s=0;s<t.length;s++)if(!ei(t[s],e[s]))return false;return true}let o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)
697
+ return false;for(let s of o)if(!Object.prototype.hasOwnProperty.call(e,s)||!ei(t[s],e[s]))return false;return true}var Bd="2026-08-14",Ya={"gpt-4o-mini":{deltaTokens:-16,salidaDelBrazoA:72,contrato:"triage (6 fields, long enums)",pares:8},"gpt-4o":{deltaTokens:3,salidaDelBrazoA:75,contrato:"triage (6 fields, long \
698
+ enums)",pares:8}},zd=Dr(Ya);function Vd(t){return _r(Ya,zd,t)}var pr=class t{deltas=new Map;static clave(e,n){return `${e}\0${n}`}recordar(e,n,r){this.deltas.set(t.clave(e,n),r);}resolver(e,n,r){if(r!=null&&
630
699
  Number.isFinite(r))return this.recordar(e,n,r),{deltaTokens:r,origen:"caller",procedencia:`measured by the caller for this contract on ${e}`};let o=this.deltas.get(t.clave(e,n));if(o!=null)return {deltaTokens:o,
631
- origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let s=tl(e);return s?{deltaTokens:s.deltaTokens,origen:"catalogue",procedencia:`measured by Bi\
632
- Velio on ${e} (${Qu}, ${s.pares} paired reps, ${s.contrato}, ${s.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};var ao="[BiVelio Savings: an older tool result was trimmed here to lower the cost; the most recent results travel in full.]",nl=new TextEncoder;function rl(t){return nl.encode(t).length}function ol(t,e){if(!t)return null;let n=(e??"").trim();if(n===""||n==="{}"||n==="[]")return null;let r;try{let o=JSON.parse(n);if(o&&typeof o=="object"&&!Array.isArray(o)&&Object.keys(o).length===0)return null;
633
- r=io(o);}catch{r=n;}return `${t} ${r}`}function io(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(io).join(",")}]`:`{${Object.keys(t).sort().map(n=>`${JSON.stringify(
634
- n)}:${io(t[n])}`).join(",")}}`}function Fi(t){let e=new Map,n=new Map;for(let u of t)if(u.role==="assistant"&&u.toolCalls)for(let l of u.toolCalls)l.id&&(e.set(l.id,l.arguments),n.set(l.id,l.name));let r=[],
635
- o=new Map;for(let u=0;u<t.length;u++){let l=t[u];if(l.role!=="tool")continue;r.push(u);let d=(l.toolCallId?n.get(l.toolCallId):void 0)??l.name,m=l.toolCallId?e.get(l.toolCallId):void 0,f=ol(d,m);f!==null&&
636
- o.set(u,f);}let s=r.length?r[r.length-1]:-1,i=new Map;for(let u of r){let l=o.get(u);if(l===void 0)continue;let d=i.get(l);(d===void 0||u>d)&&i.set(l,u);}let a=[],c=0;for(let u of r){if(u===s)continue;let l=o.
637
- get(u);if(l===void 0||i.get(l)===u)continue;let d=rl(t[u].content);d<1024||(a.push(u),c+=d);}return {indices:a,bytesOriginales:c}}function zi(t,e){if(e.length===0)return t;let n=new Set(e);return t.map(
638
- (r,o)=>n.has(o)?{...r,content:ao}:r)}function co(t,e){if(e?.cacheTier)return e.cacheTier;let n=t.toLowerCase(),r=n.indexOf("/"),o=r>0?n.slice(0,r):"",s=r>=0?n.slice(r+1):n;return o==="openai"||o==="azure-openai"?Jr:o==="anthropic"?Wr(s):
639
- o==="google"||o==="google-vertex"?Gr:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(s)?Jr:s.startsWith("claude")?Wr(s):s.startsWith("gemini")?Gr:Ti}function $i(t){let e=t.prefix!=null,n=Yr({originalTokens:t.originalTokens,
700
+ origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let i=Vd(e);return i?{deltaTokens:i.deltaTokens,origen:"catalogue",procedencia:`measured by Bi\
701
+ Velio on ${e} (${Bd}, ${i.pares} paired reps, ${i.contrato}, ${i.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};var ri="[BiVelio Savings: an older tool result was trimmed here to lower the cost; the most recent results travel in full.]",Ud=new TextEncoder;function qd(t){return Ud.encode(t).length}function Hd(t,e){if(!t)return null;let n=(e??"").trim();if(n===""||n==="{}"||n==="[]")return null;let r;try{let o=JSON.parse(n);if(o&&typeof o=="object"&&!Array.isArray(o)&&Object.keys(o).length===0)return null;
702
+ r=ni(o);}catch{r=n;}return `${t} ${r}`}function ni(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(ni).join(",")}]`:`{${Object.keys(t).sort().map(n=>`${JSON.stringify(
703
+ n)}:${ni(t[n])}`).join(",")}}`}function Za(t){let e=new Map,n=new Map;for(let c of t)if(c.role==="assistant"&&c.toolCalls)for(let l of c.toolCalls)l.id&&(e.set(l.id,l.arguments),n.set(l.id,l.name));let r=[],
704
+ o=new Map;for(let c=0;c<t.length;c++){let l=t[c];if(l.role!=="tool")continue;r.push(c);let d=(l.toolCallId?n.get(l.toolCallId):void 0)??l.name,f=l.toolCallId?e.get(l.toolCallId):void 0,m=Hd(d,f);m!==null&&
705
+ o.set(c,m);}let i=r.length?r[r.length-1]:-1,s=new Map;for(let c of r){let l=o.get(c);if(l===void 0)continue;let d=s.get(l);(d===void 0||c>d)&&s.set(l,c);}let a=[],u=0;for(let c of r){if(c===i)continue;let l=o.
706
+ get(c);if(l===void 0||s.get(l)===c)continue;let d=qd(t[c].content);d<1024||(a.push(c),u+=d);}return {indices:a,bytesOriginales:u}}function Xa(t,e){if(e.length===0)return t;let n=new Set(e);return t.map(
707
+ (r,o)=>n.has(o)?{...r,content:ri}:r)}function oi(t,e){if(e?.cacheTier)return e.cacheTier;let n=t.toLowerCase(),r=n.indexOf("/"),o=r>0?n.slice(0,r):"",i=r>=0?n.slice(r+1):n;return o==="openai"||o==="azure-openai"?Uo:o==="anthropic"?qo(i):
708
+ o==="google"||o==="google-vertex"?Ho:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(i)?Uo:i.startsWith("claude")?qo(i):i.startsWith("gemini")?Ho:Na}function Qa(t){let e=t.prefix!=null,n=Wo({originalTokens:t.originalTokens,
640
709
  compressedTokens:t.compressedTokens,stablePrefixTokens:t.prefix?.stableTokens??0,prefixHitRate:t.prefix?.hitRate??0,tier:t.tier,...t.compressorCostTokens!=null?{compressorCostTokens:t.compressorCostTokens}:
641
710
  {}});if(e)return n;let r=t.tier.minimumCacheTokens;return r!=null&&t.originalTokens>=r&&t.compressedTokens<r?{...n,comprimir:false,razon:`compressing would drop the prompt out of the cacheable tier (${t.
642
- compressedTokens} < ${r}) and nobody has measured the prefix hit rate, so it cannot be claimed to pay for itself. Declare it in \`compressionEconomics.prefix\` to unlock the full decision`}:n}function Ui(t){let e=l=>l/1e3*t.precio.inputPer1k,n=l=>l/1e3*t.precio.outputPer1k,r=e(t.promptTokens+t.descriptoresLigeros)+n(t.salidaDelSondeo),o=e(t.promptTokens+t.esquemasCompletos)+n(t.salidaFinal),
643
- s=r+e(t.promptTokens+t.esquemasDeLaSegunda)+n(t.salidaFinal),i=o-s,a=r,c=i>0&&i>=a,u;return i<=0?u=`discovery costs more than it saves: the prompt (${t.promptTokens} tokens) is paid twice and the sche\
644
- mas avoided (${t.esquemasCompletos-t.esquemasDeLaSegunda}) do not cover it`:c?u=`${t.esquemasCompletos-t.esquemasDeLaSegunda} schema tokens avoided in the worst case, enough to pay for the repeated pr\
645
- ompt and the probe`:u="the gain does not cover the cost of degrading: if the probe does not choose, the request goes out unchanged with every schema and the probe is pure cost",{aplicar:c,costeDeUnaLlamada:o,
646
- costeDeDosLlamadas:s,ganancia:i,perdidaSiDegrada:a,razon:u}}function qi(t){let n=(t.description??(Array.isArray(t.intents)?t.intents.join("; "):"")).trim().split(/\r?\n/,1)[0]??"",r=n.length>Vi?n.slice(
647
- 0,Vi-1).trimEnd()+"\u2026":n;return {id:t.id,intents:t.intents,risk:t.risk,...r?{description:r}:{}}}var Vi=200;function Hi(t,e,n){let r=new Map(e.map(c=>[c.id,c])),o=[],s=[],i=new Set;for(let c of t){let u=r.
648
- get(c);if(!u){s.push(c);continue}o.includes(u.id)||(o.push(u.id),u.risk==="read"&&i.size<Math.max(0,n)&&i.add(u.id));}return {tools:e.filter(c=>c.risk!=="read"||i.has(c.id)),reconocidos:o,ignorados:s}}function Ki(t,e){
649
- let n=0,r=[];for(let o of t)o.risk==="read"?r.push(o.tokens):n+=o.tokens;r.sort((o,s)=>s-o);for(let o of r.slice(0,Math.max(0,e)))n+=o;return n}var il=2;function uo(t){return G(ae({messages:t.messages,structuredData:t.structuredData??null,tools:t.tools??[],schema:t.response?.schema??null}))}function Ji(t){return t.temperature===0}var Me=t=>typeof t==
650
- "number"&&Number.isInteger(t)&&t>=0;function al(t,e){if(Me(t.reasoningTokens)){if(!e)return t.reasoningTokens;if(Me(e.reasoningTokens))return t.reasoningTokens+e.reasoningTokens}}function Wi(t){if(t.contadorSimulado)
651
- return "simulated-provider";let e=t.usoPrimario;if(!e||e.complete===false||!Me(e.inputTokens)||e.inputTokens<=0||!Me(e.outputTokens))return "no-usage";let n=t.usoReparacion;if(n&&(n.complete===false||!Me(n.outputTokens)))
652
- return "no-usage";if(t.eliminatedInput!==0||t.compressedInput!==0||t.elididoLocal!==0||Math.abs(t.sentLocalSinSondeo-t.baselineInput)>il)return "layer-changed-request";if(t.codebookAplicado)return "codeb\
711
+ compressedTokens} < ${r}) and nobody has measured the prefix hit rate, so it cannot be claimed to pay for itself. Declare it in \`compressionEconomics.prefix\` to unlock the full decision`}:n}function tc(t){let e=l=>l/1e3*t.precio.inputPer1k,n=l=>l/1e3*t.precio.outputPer1k,r=e(t.promptTokens+t.descriptoresLigeros)+n(t.salidaDelSondeo),o=e(t.promptTokens+t.esquemasCompletos)+n(t.salidaFinal),
712
+ i=r+e(t.promptTokens+t.esquemasDeLaSegunda)+n(t.salidaFinal),s=o-i,a=r,u=s>0&&s>=a,c;return s<=0?c=`discovery costs more than it saves: the prompt (${t.promptTokens} tokens) is paid twice and the sche\
713
+ mas avoided (${t.esquemasCompletos-t.esquemasDeLaSegunda}) do not cover it`:u?c=`${t.esquemasCompletos-t.esquemasDeLaSegunda} schema tokens avoided in the worst case, enough to pay for the repeated pr\
714
+ ompt and the probe`:c="the gain does not cover the cost of degrading: if the probe does not choose, the request goes out unchanged with every schema and the probe is pure cost",{aplicar:u,costeDeUnaLlamada:o,
715
+ costeDeDosLlamadas:i,ganancia:s,perdidaSiDegrada:a,razon:c}}function nc(t){let n=(t.description??(Array.isArray(t.intents)?t.intents.join("; "):"")).trim().split(/\r?\n/,1)[0]??"",r=n.length>ec?n.slice(
716
+ 0,ec-1).trimEnd()+"\u2026":n;return {id:t.id,intents:t.intents,risk:t.risk,...r?{description:r}:{}}}var ec=200;function rc(t,e,n){let r=new Map(e.map(u=>[u.id,u])),o=[],i=[],s=new Set;for(let u of t){let c=r.
717
+ get(u);if(!c){i.push(u);continue}o.includes(c.id)||(o.push(c.id),c.risk==="read"&&s.size<Math.max(0,n)&&s.add(c.id));}return {tools:e.filter(u=>u.risk!=="read"||s.has(u.id)),reconocidos:o,ignorados:i}}function oc(t,e){
718
+ let n=0,r=[];for(let o of t)o.risk==="read"?r.push(o.tokens):n+=o.tokens;r.sort((o,i)=>i-o);for(let o of r.slice(0,Math.max(0,e)))n+=o;return n}var Kd=2;function ii(t){return Y(ve({messages:t.messages,structuredData:t.structuredData??null,tools:t.tools??[],schema:t.response?.schema??null}))}function ic(t){return t.temperature===0}var He=t=>typeof t==
719
+ "number"&&Number.isInteger(t)&&t>=0;function Gd(t,e){if(He(t.reasoningTokens)){if(!e)return t.reasoningTokens;if(He(e.reasoningTokens))return t.reasoningTokens+e.reasoningTokens}}function sc(t){if(t.contadorSimulado)
720
+ return "simulated-provider";let e=t.usoPrimario;if(!e||e.complete===false||!He(e.inputTokens)||e.inputTokens<=0||!He(e.outputTokens))return "no-usage";let n=t.usoReparacion;if(n&&(n.complete===false||!He(n.outputTokens)))
721
+ return "no-usage";if(t.eliminatedInput!==0||t.compressedInput!==0||t.elididoLocal!==0||Math.abs(t.sentLocalSinSondeo-t.baselineInput)>Kd)return "layer-changed-request";if(t.codebookAplicado)return "codeb\
653
722
  ook";if(t.tokensDelSondeo!==0||t.sondeoAplicado)return "tool-discovery";if(t.hayEsquema&&(!t.esquemaNativo||t.esquemaPorPrompt))return "schema-in-prompt";if(t.hayEsquema&&!t.esquemaEnFormatoNativo)return "\
654
- schema-not-verbatim";if(t.hayEsquema&&!t.esquemaEstricto)return "schema-not-strict";if(t.modeloServido!==t.modeloPedido)return "cheaper-model-served";if(!t.cacheable)return "not-cacheable";let r=en(t.tierServido),
655
- o=r?.conDescuento&&r.factor!=null&&r.factor>0&&r.factor<1?r.factor:void 0,s=al(e,n);return {v:2,requestId:t.requestId,at:t.at,model:t.modeloPedido,inputTokens:e.inputTokens,outputTokens:n?Math.min(e.outputTokens,
656
- n.outputTokens):e.outputTokens,...o!==void 0?{tierFactor:o}:{},layerInsertions:Math.max(0,t.mensajesDeLaCapa)+Math.max(0,t.piezasDelAdaptador)+(t.hayEsquema?1:0),...s!==void 0?{reasoningTokens:s}:{},requestFingerprint:t.
657
- huella(),textSha256:G(t.textoServido)}}var Mn=t=>typeof t=="string"&&t.length>0;function Gi(t){if(t==null||typeof t!="object")return "absent";let e=t.reference;if(e==null)return "absent";if(typeof e!="o\
658
- bject"||Array.isArray(e))return "malformed";let n=e,r=n.tierFactor,o=n.reasoningTokens;return n.v===2&&typeof n.inputTokens=="number"&&Number.isInteger(n.inputTokens)&&n.inputTokens>0&&Me(n.outputTokens)&&
659
- typeof n.at=="number"&&Number.isFinite(n.at)&&(r===void 0||typeof r=="number"&&r>0&&r<1)&&Me(n.layerInsertions)&&(o===void 0||Me(o))&&Mn(n.requestId)&&Mn(n.model)&&Mn(n.requestFingerprint)&&Mn(n.textSha256)?
723
+ schema-not-verbatim";if(t.hayEsquema&&!t.esquemaEstricto)return "schema-not-strict";if(t.modeloServido!==t.modeloPedido)return "cheaper-model-served";if(!t.cacheable)return "not-cacheable";let r=eo(t.tierServido),
724
+ o=r?.conDescuento&&r.factor!=null&&r.factor>0&&r.factor<1?r.factor:void 0,i=Gd(e,n);return {v:2,requestId:t.requestId,at:t.at,model:t.modeloPedido,inputTokens:e.inputTokens,outputTokens:n?Math.min(e.outputTokens,
725
+ n.outputTokens):e.outputTokens,...o!==void 0?{tierFactor:o}:{},layerInsertions:Math.max(0,t.mensajesDeLaCapa)+Math.max(0,t.piezasDelAdaptador)+(t.hayEsquema?1:0),...i!==void 0?{reasoningTokens:i}:{},requestFingerprint:t.
726
+ huella(),textSha256:Y(t.textoServido)}}var fr=t=>typeof t=="string"&&t.length>0;function ac(t){if(t==null||typeof t!="object")return "absent";let e=t.reference;if(e==null)return "absent";if(typeof e!="o\
727
+ bject"||Array.isArray(e))return "malformed";let n=e,r=n.tierFactor,o=n.reasoningTokens;return n.v===2&&typeof n.inputTokens=="number"&&Number.isInteger(n.inputTokens)&&n.inputTokens>0&&He(n.outputTokens)&&
728
+ typeof n.at=="number"&&Number.isFinite(n.at)&&(r===void 0||typeof r=="number"&&r>0&&r<1)&&He(n.layerInsertions)&&(o===void 0||He(o))&&fr(n.requestId)&&fr(n.model)&&fr(n.requestFingerprint)&&fr(n.textSha256)?
660
729
  {v:2,requestId:n.requestId,at:n.at,model:n.model,inputTokens:n.inputTokens,outputTokens:n.outputTokens,...r!==void 0?{tierFactor:r}:{},layerInsertions:n.layerInsertions,...o!==void 0?{reasoningTokens:o}:
661
- {},requestFingerprint:n.requestFingerprint,textSha256:n.textSha256,...typeof n.cacheKey=="string"?{cacheKey:n.cacheKey}:{}}:"malformed"}function cl(t,e){if(!e.determinista)return "sampled";if(e.salidaDelModelo!==
662
- void 0)return e.salidaDelModelo;if(t.reasoningTokens===void 0)return "reasoning-not-reported";if(t.reasoningTokens!==0)return "reasoning-reported"}function Yi(t,e){if(e.textoServidoSha256!==t.textSha256)
730
+ {},requestFingerprint:n.requestFingerprint,textSha256:n.textSha256,...typeof n.cacheKey=="string"?{cacheKey:n.cacheKey}:{}}:"malformed"}function Jd(t,e){if(!e.determinista)return "sampled";if(e.salidaDelModelo!==
731
+ void 0)return e.salidaDelModelo;if(t.reasoningTokens===void 0)return "reasoning-not-reported";if(t.reasoningTokens!==0)return "reasoning-reported"}function cc(t,e){if(e.textoServidoSha256!==t.textSha256)
663
732
  return {ok:false,reason:"witness"};if(e.claveLeida!==void 0&&t.cacheKey!==e.claveLeida)return {ok:false,reason:"witness"};if(t.model!==e.modeloPedido||e.modeloServido!==e.modeloPedido)return {ok:false,reason:"mod\
664
733
  el-mismatch"};let n=e.ahoraMs-t.at;if(!(n>=-3e5&&n<=2592e6))return {ok:false,reason:"expired"};if(e.huella!==t.requestFingerprint)return {ok:false,reason:"different-request"};if(!e.calidadOk)return {ok:false,reason:"\
665
734
  quality"};let r=e.precio,o=r?.cachedInputPer1k;if(!r||typeof o!="number"||!Number.isFinite(o)||!(o>0)||!Number.isFinite(r.inputPer1k)||o>r.inputPer1k||typeof r.outputPer1k!="number"||!Number.isFinite(
666
- r.outputPer1k)||r.outputPer1k<0)return {ok:false,reason:"no-cached-price"};let s=t.inputTokens-8*t.layerInsertions;if(!(s>0))return {ok:false,reason:"no-credit"};let i=typeof e.topeDeSalida=="number"&&Number.
667
- isFinite(e.topeDeSalida)?Math.max(0,e.topeDeSalida):Number.POSITIVE_INFINITY,a=cl(t,e),c=a===void 0?Math.floor(.95*Math.min(t.outputTokens,i)):0,u=Math.min(1,t.tierFactor??1,e.diferible?es:1);return {ok:true,
668
- ...a!==void 0?{outputNotCredited:a}:{},credit:{requestId:t.requestId,at:t.at,inputTokens:t.inputTokens,outputTokens:t.outputTokens,creditedInputTokens:s,creditedOutputTokens:c,cachedInputPer1k:o,outputPer1k:r.
669
- outputPer1k,tierFactor:u}}}var Et={done:true,value:void 0},Rt=class{handle;sumidero;now;inicio;controlador=new AbortController;resolver;rechazar;cola=[];esperas=[];cerrada=false;errorPendiente=null;consumidorSalio=false;iterado=false;_abortado=false;vivo=false;proveedorTerminado=false;terminado=false;primerEventoAt;quitarEscucha;constructor(e,n){
670
- this.now=e,this.inicio=e();let r,o,s=new Promise((a,c)=>{r=a,o=c;});s.catch(()=>{}),this.resolver=r,this.rechazar=o;let i=this;if(this.sumidero={senal:this.controlador.signal,texto(a){i.recibirTexto(a);},
671
- proveedorTermino(){i.proveedorTerminado=true;},sirvioEnVivo:false},this.handle={result:s,abort:a=>this.abort(a),[Symbol.asyncIterator]:()=>this.iterador()},n)if(n.aborted)this.abort(n.reason);else {let a=()=>this.
735
+ r.outputPer1k)||r.outputPer1k<0)return {ok:false,reason:"no-cached-price"};let i=t.inputTokens-8*t.layerInsertions;if(!(i>0))return {ok:false,reason:"no-credit"};let s=typeof e.topeDeSalida=="number"&&Number.
736
+ isFinite(e.topeDeSalida)?Math.max(0,e.topeDeSalida):Number.POSITIVE_INFINITY,a=Jd(t,e),u=a===void 0?Math.floor(.95*Math.min(t.outputTokens,s)):0,c=Math.min(1,t.tierFactor??1,e.diferible?ss:1);return {ok:true,
737
+ ...a!==void 0?{outputNotCredited:a}:{},credit:{requestId:t.requestId,at:t.at,inputTokens:t.inputTokens,outputTokens:t.outputTokens,creditedInputTokens:i,creditedOutputTokens:u,cachedInputPer1k:o,outputPer1k:r.
738
+ outputPer1k,tierFactor:c}}}var en={done:true,value:void 0},tn=class{handle;sumidero;now;inicio;controlador=new AbortController;resolver;rechazar;cola=[];esperas=[];cerrada=false;errorPendiente=null;consumidorSalio=false;iterado=false;_abortado=false;vivo=false;proveedorTerminado=false;terminado=false;primerEventoAt;quitarEscucha;constructor(e,n){
739
+ this.now=e,this.inicio=e();let r,o,i=new Promise((a,u)=>{r=a,o=u;});i.catch(()=>{}),this.resolver=r,this.rechazar=o;let s=this;if(this.sumidero={senal:this.controlador.signal,texto(a){s.recibirTexto(a);},
740
+ proveedorTermino(){s.proveedorTerminado=true;},sirvioEnVivo:false},this.handle={result:i,abort:a=>this.abort(a),[Symbol.asyncIterator]:()=>this.iterador()},n)if(n.aborted)this.abort(n.reason);else {let a=()=>this.
672
741
  abort(n.reason);n.addEventListener("abort",a,{once:true}),this.quitarEscucha=()=>n.removeEventListener("abort",a);}}get abortado(){return this._abortado}entrarEnVivo(){this.vivo=true;}completar(e,n){if(this.
673
- terminado)return;let r=e.toolCalls?.length??0,o=this.primerEventoAt??(n.vivo&&r>0?this.now():void 0),s=n.vivo?{delivery:"live",...o!==void 0?{firstEventMs:o-this.inicio}:{}}:{delivery:"whole",...n.motivo?
674
- {wholeReason:n.motivo}:{}},i={...e,report:{...e.report,streaming:s}};if(this.resolver(i),!this._abortado){!n.vivo&&i.text!==""&&this.encolar({type:"text",delta:i.text});for(let a of i.toolCalls??[])this.
675
- encolar({type:"tool_call",call:a});this.encolar({type:"done",result:i});}this.cerrar(),this.acabar();}fallar(e){this.terminado||(this.rechazar(e),this._abortado?this.cerrar():this.fallarCola(e),this.acabar());}acabar(){
742
+ terminado)return;let r=e.toolCalls?.length??0,o=this.primerEventoAt??(n.vivo&&r>0?this.now():void 0),i=n.vivo?{delivery:"live",...o!==void 0?{firstEventMs:o-this.inicio}:{}}:{delivery:"whole",...n.motivo?
743
+ {wholeReason:n.motivo}:{}},s={...e,report:{...e.report,streaming:i}};if(this.resolver(s),!this._abortado){!n.vivo&&s.text!==""&&this.encolar({type:"text",delta:s.text});for(let a of s.toolCalls??[])this.
744
+ encolar({type:"tool_call",call:a});this.encolar({type:"done",result:s});}this.cerrar(),this.acabar();}fallar(e){this.terminado||(this.rechazar(e),this._abortado?this.cerrar():this.fallarCola(e),this.acabar());}acabar(){
676
745
  this.terminado=true,this.quitarEscucha?.(),this.quitarEscucha=void 0;}abort(e){this.terminado||this._abortado||(this._abortado=true,this.cola.length=0,this.cerrar(),this.vivo&&!this.proveedorTerminado&&this.
677
746
  controlador.abort(e));}recibirTexto(e){e===""||this._abortado||this.terminado||(this.primerEventoAt===void 0&&(this.primerEventoAt=this.now()),this.encolar({type:"text",delta:e}));}encolar(e){if(this.cerrada)
678
- return;let n=this.esperas.shift();n?n.resolve({done:false,value:e}):this.cola.push(e);}cerrar(){this.cerrada=true;for(let e of this.esperas.splice(0))e.resolve(Et);}fallarCola(e){this.cerrada=true;let[n,...r]=this.
679
- esperas.splice(0);if(n){n.reject(e);for(let o of r)o.resolve(Et);}else this.errorPendiente={valor:e};}siguiente(){if(this.consumidorSalio)return Promise.resolve(Et);let e=this.cola.shift();if(e)return Promise.
680
- resolve({done:false,value:e});if(this.errorPendiente){let{valor:n}=this.errorPendiente;return this.errorPendiente=null,Promise.reject(n)}return this.cerrada?Promise.resolve(Et):new Promise((n,r)=>{this.esperas.
747
+ return;let n=this.esperas.shift();n?n.resolve({done:false,value:e}):this.cola.push(e);}cerrar(){this.cerrada=true;for(let e of this.esperas.splice(0))e.resolve(en);}fallarCola(e){this.cerrada=true;let[n,...r]=this.
748
+ esperas.splice(0);if(n){n.reject(e);for(let o of r)o.resolve(en);}else this.errorPendiente={valor:e};}siguiente(){if(this.consumidorSalio)return Promise.resolve(en);let e=this.cola.shift();if(e)return Promise.
749
+ resolve({done:false,value:e});if(this.errorPendiente){let{valor:n}=this.errorPendiente;return this.errorPendiente=null,Promise.reject(n)}return this.cerrada?Promise.resolve(en):new Promise((n,r)=>{this.esperas.
681
750
  push({resolve:n,reject:r});})}iterador(){if(this.iterado)throw new Error("[bvsala] a SavingsStream can be iterated only once");return this.iterado=true,{next:()=>this.siguiente(),return:()=>(this.abort(),
682
- this.consumidorSalio=true,this.cola.length=0,Promise.resolve(Et))}}};var le=class extends Error{requestSent;constructor(e){super(e?"[bvsala] stream aborted: the provider request was cancelled before its final usage; nothing was cached or recorded":"[bvsala] stream abor\
683
- ted before any provider request was sent"),this.name="StreamAbortedError",this.requestSent=e;}};function Ln(t){if(t==null)return {activo:false,motivo:"ausente"};if(typeof t!="object")return {activo:false,motivo:"invalido"};let e=t.sampleRate;if(typeof e!="number"||!Number.isFinite(e)||e<0||e>1)return {activo:false,
751
+ this.consumidorSalio=true,this.cola.length=0,Promise.resolve(en))}}};function Yd(t,e){switch(t){case "deterministic":return "deterministic";case "exact":return "exact_cache";case "semantic":return "semantic_cache";case "singleflight":return "coalesced";default:return e?.origen===
752
+ "fail_open"?"fail_open":"provider"}}function Zd(t){if(!t||t.mode!=="shadow"&&t.mode!=="on")return;if(t.mode==="shadow")return {mode:"shadow",gate:t.verifier,outcome:"not_applied",...t.divergedOnSample!==
753
+ void 0?{sampleDiverged:t.divergedOnSample}:{}};let e=t.servedModel!==t.requestedModel?"accepted":t.escalated===true?"escalated":"not_routed";return {mode:"on",gate:t.verifier,outcome:e}}function uc(t){let e=t.
754
+ hechos,n=Yd(t.cacheResult,e),r={source:n};if(t.hayEsquema)if(t.structurallyValid===null)r.schema={outcome:"not_applicable",decodeTimeConstraint:t.backend!=="none",errorCount:0};else {let i=e?.validacion,
755
+ s=i?.errores??(t.structurallyValid?0:1);r.schema={outcome:t.structurallyValid?"passed":"failed",decodeTimeConstraint:t.backend!=="none",errorCount:s,...i?.desenvuelto?{unwrapped:true}:{}};}if(n==="provid\
756
+ er"&&e?.reparacion&&(r.repair={...e.reparacion}),n==="provider"||n==="fail_open"){let i=e?.final,s=i?.topeDelLlamante;r.truncation={truncated:i?.finishReason==="length",...i?.finishReason!==void 0?{finishReason:i.
757
+ finishReason}:{},capSetByCaller:s!=null,...s!=null?{outputLimit:s}:{}};}if(n==="exact_cache")r.cacheMatch={kind:"exact",...t.ageMs!==void 0?{ageMs:t.ageMs}:{}};else if(n==="semantic_cache"&&e?.semantico){
758
+ let i=e.semantico;r.cacheMatch={kind:"semantic",ageMs:i.ageMs,similarity:i.similarity,similarityFloor:i.similarityFloor,acceptFloor:i.acceptFloor,...i.verifierRan?{verifierScore:i.verifierScore}:{},embedder:i.
759
+ embedder,factGuard:"passed"};}let o=Zd(t.cascada);return o&&(r.cascade=o),r}function lc(t){return {source:"coalesced",sharedFrom:t==null?"provider":t.source==="coalesced"?t.sharedFrom??"provider":t.source,
760
+ ...t?.schema?{schema:{...t.schema}}:{},...t?.repair?{repair:{...t.repair}}:{},...t?.truncation?{truncation:{...t.truncation}}:{},...t?.cacheMatch?{cacheMatch:{...t.cacheMatch}}:{},...t?.cascade?{cascade:{
761
+ ...t.cascade}}:{}}}var pe=class extends Error{requestSent;constructor(e){super(e?"[bvsala] stream aborted: the provider request was cancelled before its final usage; nothing was cached or recorded":"[bvsala] stream abor\
762
+ ted before any provider request was sent"),this.name="StreamAbortedError",this.requestSent=e;}};function mr(t){if(t==null)return {activo:false,motivo:"ausente"};if(typeof t!="object")return {activo:false,motivo:"invalido"};let e=t.sampleRate;if(typeof e!="number"||!Number.isFinite(e)||e<0||e>1)return {activo:false,
684
763
  motivo:"invalido"};let n=t.maxCheckCostUsd;if(n!==void 0&&(typeof n!="number"||!Number.isFinite(n)||n<=0))return {activo:false,motivo:"invalido"};if(e===0)return {activo:false,motivo:"cero"};let r=typeof t.onCheck==
685
- "function"?t.onCheck:void 0,o=typeof t.waitUntil=="function"?t.waitUntil:void 0;return {activo:true,tasa:e,...n!==void 0?{tope:n}:{},...r?{onCheck:r}:{},...o?{waitUntil:o}:{}}}function ul(t){let e=t*100,
686
- n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function Zi(t){let e=ul(t);return `[bvsala] Verification sampling is ON \
764
+ "function"?t.onCheck:void 0,o=typeof t.waitUntil=="function"?t.waitUntil:void 0;return {activo:true,tasa:e,...n!==void 0?{tope:n}:{},...r?{onCheck:r}:{},...o?{waitUntil:o}:{}}}function Xd(t){let e=t*100,
765
+ n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function dc(t){let e=Xd(t);return `[bvsala] Verification sampling is ON \
687
766
  (sampleRate ${t}): about ${e} of eligible requests are sent a second time, unoptimized, to your own provider \u2014 in the background, after your answer is returned \u2014 and the second answer is discarded. Yo\
688
767
  u pay your provider for those calls: roughly ${e} of what that traffic would cost without the layer. The pairs appear under Proof \u203A Your bench in your dashboard; they are informational and never enter\
689
- your statement or any commission.`}function Xi(t){let e;try{let n=t?.sampleRate;e=typeof n=="string"?JSON.stringify(n):String(n);}catch{e="an unreadable value";}return `[bvsala] \`verification.sampleRate\
690
- \` must be a number from 0 to 1 and \`verification.maxCheckCostUsd\`, when set, a positive number (got sampleRate ${e}); verification sampling is OFF.`}var Qi="[bvsala] Verification sampling is set, b\
768
+ your statement or any commission.`}function pc(t){let e;try{let n=t?.sampleRate;e=typeof n=="string"?JSON.stringify(n):String(n);}catch{e="an unreadable value";}return `[bvsala] \`verification.sampleRate\
769
+ \` must be a number from 0 to 1 and \`verification.maxCheckCostUsd\`, when set, a positive number (got sampleRate ${e}); verification sampling is OFF.`}var fc="[bvsala] Verification sampling is set, b\
691
770
  ut its pairs have nowhere to go: set `serviceAccountKey` and `licenseServerUrl` (with metering on) to see them in your dashboard \u2014 a custom `meteringUrl` is followed only when it ends in `/api/meterin\
692
- g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",ea="[bvsala] verification sampling hit an internal error and skipped a request; your\
693
- request was not affected.";function ta(t){let e=t.messages.map(n=>({...n}));return t.structuredData!==void 0&&e.push({role:"user",content:JSON.stringify(t.structuredData)}),{model:t.model,messages:e,...t.tools&&t.tools.length>0?
771
+ g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",mc="[bvsala] verification sampling hit an internal error and skipped a request; your\
772
+ request was not affected.";function hc(t){let e=t.messages.map(n=>({...n}));return t.structuredData!==void 0&&e.push({role:"user",content:JSON.stringify(t.structuredData)}),{model:t.model,messages:e,...t.tools&&t.tools.length>0?
694
773
  {tools:[...t.tools]}:{},...t.response?.schema?{schema:t.response.schema}:{},...t.response?.maxOutputTokens!=null?{maxOutputTokens:t.response.maxOutputTokens}:{},...t.temperature!==void 0?{temperature:t.
695
- temperature}:{},...t.seed!==void 0?{seed:t.seed}:{}}}function na(t){let{request:e,result:n,via:r}=t,o=n.report;if(r==="fail-open")return {excluida:"fail_open"};if(e.savings?.verification===false)return {excluida:"opted_out"};let s=n.finishReason;return s==="\
696
- length"?{excluida:"truncated"}:s!==void 0&&s!=="stop"&&s!=="tool_calls"?{excluida:"incomplete"}:o.constraints.structurallyValid===false||o.qualityStatus==="rejected"?{excluida:"contract_failed"}:o.cost.basis===
774
+ temperature}:{},...t.seed!==void 0?{seed:t.seed}:{}}}function gc(t){let{request:e,result:n,via:r}=t,o=n.report;if(r==="fail-open")return {excluida:"fail_open"};if(e.savings?.verification===false)return {excluida:"opted_out"};let i=n.finishReason;return i==="\
775
+ length"?{excluida:"truncated"}:i!==void 0&&i!=="stop"&&i!=="tool_calls"?{excluida:"incomplete"}:o.constraints.structurallyValid===false||o.qualityStatus==="rejected"?{excluida:"contract_failed"}:o.cost.basis===
697
776
  "unmeasured"?{excluida:"unmeasured"}:o.calls.actualRetrieval>0?{excluida:"retrieval"}:t.precio(e.model)===void 0||t.precio(o.model)===void 0?{excluida:"no_price"}:t.tope!==void 0&&o.cost.baselineEstimate>
698
777
  t.tope?{excluida:"over_cap"}:o.calls.avoidedLlm>0?{estrato:"avoided_call"}:o.model!==e.model?{estrato:"cheaper_model"}:o.tokens.eliminatedInput>0?{estrato:"tokens_removed"}:o.tokens.compressedInput>0?
699
- {estrato:"tokens_compressed"}:{estrato:"unchanged"}}function ra(t,e){if(!(e>0))return false;if(e>=1)return true;let n=G(`${t}:verification-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function oa(t,e){let n=t.inputTokens,r=Math.min(t.cachedInputTokens??0,n),o=e.cachedInputPer1k??e.inputPer1k,s=Math.max(0,n-r)/1e3*e.inputPer1k+r/1e3*o+t.outputTokens/1e3*e.outputPer1k;return Math.round(
700
- s*1e10)/1e10}var ll=32,dl=6e5;function pl(t){return new Date(t).toISOString().slice(0,10)}var Nn=class{tasa;tope;onCheck;waitUntil;provider;precio;contrato;now;sumidero;avisar;enVuelo=new Set;cerrado=false;constructor(e){
778
+ {estrato:"tokens_compressed"}:{estrato:"unchanged"}}function bc(t,e){if(!(e>0))return false;if(e>=1)return true;let n=Y(`${t}:verification-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function vc(t,e){let n=t.inputTokens,r=Math.min(t.cachedInputTokens??0,n),o=e.cachedInputPer1k??e.inputPer1k,i=Math.max(0,n-r)/1e3*e.inputPer1k+r/1e3*o+t.outputTokens/1e3*e.outputPer1k;return Math.round(
779
+ i*1e10)/1e10}var Qd=32,ep=6e5;function tp(t){return new Date(t).toISOString().slice(0,10)}var hr=class{tasa;tope;onCheck;waitUntil;provider;precio;contrato;now;sumidero;avisar;enVuelo=new Set;cerrado=false;constructor(e){
701
780
  this.tasa=e.ajustes.tasa,this.tope=e.ajustes.tope,this.onCheck=e.ajustes.onCheck,this.waitUntil=e.ajustes.waitUntil,this.provider=e.provider,this.precio=e.precio,this.contrato=e.contrato,this.now=e.now,
702
- this.sumidero=e.sumidero,this.avisar=e.avisar;}get copiasEnVuelo(){return this.enVuelo.size}decidir(e,n,r){if(this.cerrado)return n;try{let o=n.report,s=ra(o.requestId,this.tasa),i=na({request:e,result:n,
703
- via:r,precio:this.precio,...this.tope!==void 0?{tope:this.tope}:{}}),a;if(s&&"estrato"in i){let l=this.precio(e.model);if(!l)throw new Error("price vanished between classification and launch");a={peticion:ta(
704
- e),precios:l,estrato:i.estrato};}let c=this.now();this.sumidero.contar?.(pl(c),"estrato"in i?i.estrato:i.excluida),a&&this.lanzar(e,n,c,a);let u="estrato"in i?{sampled:s,stratum:i.estrato}:{sampled:s,excluded:i.
705
- excluida};return {...n,report:{...o,verification:u}}}catch{return this.avisar("verificacion-fallo-interno",ea),n}}cerrar(){this.cerrado=true;let e=[...this.enVuelo];this.enVuelo.clear();for(let n of e)if(!n.
706
- decidido){n.decidido=true,n.reloj&&clearTimeout(n.reloj);try{n.abortar.abort();}catch{}this.registrar({...n.base,outcome:"abandoned"}),n.terminar();}}lanzar(e,n,r,o){let s=n.report,i=o.precios,a={requestId:s.
707
- requestId,at:r,stratum:o.estrato,requestedModel:e.model,servedModel:s.model,cacheResult:s.cache.result,optimized:{cost:s.cost.actual,inputTokens:s.tokens.actualInput,cachedInputTokens:s.tokens.providerCachedInput??
708
- 0,outputTokens:s.tokens.actualOutput},prices:{inputPer1k:i.inputPer1k,...i.cachedInputPer1k!==void 0?{cachedInputPer1k:i.cachedInputPer1k}:{},outputPer1k:i.outputPer1k}};if(this.enVuelo.size>=ll){this.
709
- registrar({...a,outcome:"dropped"});return}let c=()=>{},u=new Promise(d=>{c=d;}),l={base:a,abortar:new AbortController,decidido:false,reloj:void 0,terminar:c};if(this.enVuelo.add(l),l.reloj=setTimeout(()=>{
710
- try{l.abortar.abort();}catch{}this.resolverVuelo(l,{...a,outcome:"check_failed"});},dl),l.reloj.unref?.(),setTimeout(()=>{if(l.decidido)return;let d;try{d=Promise.resolve(this.provider.generate(o.peticion,
711
- {signal:l.abortar.signal}));}catch(m){d=Promise.reject(m);}d.then(m=>{let f;try{f=this.checkDeLaRespuesta(a,o.peticion,m,i);}catch{f={...a,outcome:"check_failed"};}this.resolverVuelo(l,f);},()=>{this.resolverVuelo(
712
- l,{...a,outcome:"check_failed"});});},0),this.waitUntil)try{this.waitUntil(u.catch(()=>{}));}catch{}}checkDeLaRespuesta(e,n,r,o){let s=r?.usage,i=s?.inputTokens,a=s?.outputTokens,c=s?.cachedInputTokens??
713
- 0,u=f=>typeof f=="number"&&Number.isSafeInteger(f)&&f>=0;if(!s||s.complete===false||!u(i)||!u(a)||!u(c)||i===0&&a===0)return {...e,outcome:"check_unmeasured"};let l=Math.min(c,i),d=r.finishReason,m=typeof d==
714
- "string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost:oa({inputTokens:i,outputTokens:a,cachedInputTokens:l},o),inputTokens:i,cachedInputTokens:l,outputTokens:a,...m!==
715
- void 0?{finishReason:m}:{},contract:this.contrato(n,r)}}}async resolverVuelo(e,n){if(!e.decidido){if(e.decidido=true,e.reloj&&clearTimeout(e.reloj),this.enVuelo.delete(e),this.registrar(n),this.enVuelo.
716
- size===0)try{await this.sumidero.enReposo();}catch{}e.terminar();}}registrar(e){try{this.sumidero.encolar(e);}catch{}if(this.onCheck)try{this.onCheck(e);}catch{}}};var lo=true,ua=new WeakSet;function fl(t){typeof t=="object"&&t!==null&&ua.add(t);}function aa(t){return typeof t=="object"&&t!==null&&ua.has(t)}function ca(t,e){switch(t){case "none":return ml();case "inv\
781
+ this.sumidero=e.sumidero,this.avisar=e.avisar;}get copiasEnVuelo(){return this.enVuelo.size}decidir(e,n,r){if(this.cerrado)return n;try{let o=n.report,i=bc(o.requestId,this.tasa),s=gc({request:e,result:n,
782
+ via:r,precio:this.precio,...this.tope!==void 0?{tope:this.tope}:{}}),a;if(i&&"estrato"in s){let l=this.precio(e.model);if(!l)throw new Error("price vanished between classification and launch");a={peticion:hc(
783
+ e),precios:l,estrato:s.estrato};}let u=this.now();this.sumidero.contar?.(tp(u),"estrato"in s?s.estrato:s.excluida),a&&this.lanzar(e,n,u,a);let c="estrato"in s?{sampled:i,stratum:s.estrato}:{sampled:i,excluded:s.
784
+ excluida};return {...n,report:{...o,verification:c}}}catch{return this.avisar("verificacion-fallo-interno",mc),n}}cerrar(){this.cerrado=true;let e=[...this.enVuelo];this.enVuelo.clear();for(let n of e)if(!n.
785
+ decidido){n.decidido=true,n.reloj&&clearTimeout(n.reloj);try{n.abortar.abort();}catch{}this.registrar({...n.base,outcome:"abandoned"}),n.terminar();}}lanzar(e,n,r,o){let i=n.report,s=o.precios,a={requestId:i.
786
+ requestId,at:r,stratum:o.estrato,requestedModel:e.model,servedModel:i.model,cacheResult:i.cache.result,optimized:{cost:i.cost.actual,inputTokens:i.tokens.actualInput,cachedInputTokens:i.tokens.providerCachedInput??
787
+ 0,outputTokens:i.tokens.actualOutput},prices:{inputPer1k:s.inputPer1k,...s.cachedInputPer1k!==void 0?{cachedInputPer1k:s.cachedInputPer1k}:{},outputPer1k:s.outputPer1k}};if(this.enVuelo.size>=Qd){this.
788
+ registrar({...a,outcome:"dropped"});return}let u=()=>{},c=new Promise(d=>{u=d;}),l={base:a,abortar:new AbortController,decidido:false,reloj:void 0,terminar:u};if(this.enVuelo.add(l),l.reloj=setTimeout(()=>{
789
+ try{l.abortar.abort();}catch{}this.resolverVuelo(l,{...a,outcome:"check_failed"});},ep),l.reloj.unref?.(),setTimeout(()=>{if(l.decidido)return;let d;try{d=Promise.resolve(this.provider.generate(o.peticion,
790
+ {signal:l.abortar.signal}));}catch(f){d=Promise.reject(f);}d.then(f=>{let m;try{m=this.checkDeLaRespuesta(a,o.peticion,f,s);}catch{m={...a,outcome:"check_failed"};}this.resolverVuelo(l,m);},()=>{this.resolverVuelo(
791
+ l,{...a,outcome:"check_failed"});});},0),this.waitUntil)try{this.waitUntil(c.catch(()=>{}));}catch{}}checkDeLaRespuesta(e,n,r,o){let i=r?.usage,s=i?.inputTokens,a=i?.outputTokens,u=i?.cachedInputTokens??
792
+ 0,c=m=>typeof m=="number"&&Number.isSafeInteger(m)&&m>=0;if(!i||i.complete===false||!c(s)||!c(a)||!c(u)||s===0&&a===0)return {...e,outcome:"check_unmeasured"};let l=Math.min(u,s),d=r.finishReason,f=typeof d==
793
+ "string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost:vc({inputTokens:s,outputTokens:a,cachedInputTokens:l},o),inputTokens:s,cachedInputTokens:l,outputTokens:a,...f!==
794
+ void 0?{finishReason:f}:{},contract:this.contrato(n,r)}}}async resolverVuelo(e,n){if(!e.decidido){if(e.decidido=true,e.reloj&&clearTimeout(e.reloj),this.enVuelo.delete(e),this.registrar(n),this.enVuelo.
795
+ size===0)try{await this.sumidero.enReposo();}catch{}e.terminar();}}registrar(e){try{this.sumidero.encolar(e);}catch{}if(this.onCheck)try{this.onCheck(e);}catch{}}};var si=true,Tc=new WeakSet;function np(t){typeof t=="object"&&t!==null&&Tc.add(t);}function xc(t){return typeof t=="object"&&t!==null&&Tc.has(t)}function wc(t,e){switch(t){case "none":return rp();case "inv\
717
796
  alid":return e==="malformed"?"BiVelio license key is not a license token (malformed): a BiVelio license key looks like `xxxx.yyyy.zzzz` \u2014 three dot-separated base64url segments, several hundred charac\
718
797
  ters long \u2014 did you paste the `bvk_` service-account key by mistake? That one goes in `serviceAccountKey`; the license key is the other value on https://savings.bivelio.com/dashboard/install (license \
719
798
  status: invalid)":"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\
@@ -721,288 +800,419 @@ status: invalid)":"BiVelio license key is not valid (it does not verify). Check
721
800
  lling status at https://savings.bivelio.com/dashboard/account or write to support@bivelio.com (license status: revoked)";case "stale":return "BiVelio could not confirm your license with the control plan\
722
801
  e 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. (license\
723
802
  status: stale)";case "expired":case "grace":return `BiVelio license is not active. Renew your subscription at https://savings.bivelio.com/dashboard/account (license status: ${t})`;default:return `BiVelio\
724
- license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function ml(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 t\
803
+ license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function rp(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 t\
725
804
  he signed token from your subscription, verified offline. This published package has no unlicensed mode. Copy your key and a ready-to-paste snippet at https://savings.bivelio.com/dashboard/install (li\
726
- cense status: none)"}function hl(){return "licenseGate must implement isActive(): a gate that cannot prove the license is live is refused. In this published package an injected gate is not a licensing \
727
- path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var jn=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new _n;verjaDeCascada;memoriaDelCodebook=new An;referenciasDeLider=new WeakMap;comprobador;constructor(e,n={}){
728
- this.config=e,this.deps=ki(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>dt()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.verjaDeCascada=new Pn(e.modelCascade?.
729
- exploration!=null?{exploracion:e.modelCascade.exploration}:{});let r=Ln(e.verification);this.comprobador=r.activo&&n.verificacion?new Nn({ajustes:r,provider:e.provider,precio:o=>this.precioConocido(o),
730
- contrato:(o,s)=>gl(o,s),now:this.now,sumidero:n.verificacion,avisar:(o,s)=>this.avisar(o,s)}):void 0;}conVerificacion(e,n,r){return this.comprobador?this.comprobador.decidir(e,n,r):n}cerrarVerificacion(){
731
- this.comprobador?.cerrar();}async generate(e){this.assertLicensed();let n={llamadas:0,falloDelProveedor:false,sinContador:0},r;try{r=await this.generateOptimized(e,n);}catch(o){if(o instanceof Ce||this.config.
732
- failOpen===false||n.falloDelProveedor||n.llamadas>0||aa(o))throw o;return this.conVerificacion(e,await this.failOpenDirect(e,o),"fail-open")}return this.conVerificacion(e,r,"optimizado")}generateStream(e,n={},r){
733
- let o;try{o=new Rt(this.now,n?.signal);}catch(s){let i=new Rt(this.now);return i.fallar(s),i.handle}return this.ejecutarStream(e,o,r),o.handle}async ejecutarStream(e,n,r){try{if(r&&await r,n.abortado)throw new le(
734
- !1);let o=this.motivoDeEntregaEntera(e);if(o){let a=await this.generate(e);n.completar(a,{vivo:!1,motivo:o});return}this.assertLicensed(),n.entrarEnVivo();let s={llamadas:0,falloDelProveedor:!1,sinContador:0},
735
- i;try{i=await this.generateOptimized(e,s,n.sumidero);}catch(a){if(a instanceof Ce||a instanceof le)throw a;if(n.sumidero.senal.aborted)throw new le(s.llamadas>0);if(this.config.failOpen===!1||s.falloDelProveedor||
736
- s.llamadas>0||aa(a))throw a;let c=this.conVerificacion(e,await this.failOpenDirect(e,a),"fail-open");n.completar(c,{vivo:!1,motivo:"fail-open"});return}i=this.conVerificacion(e,i,"optimizado"),n.completar(
737
- i,n.sumidero.sirvioEnVivo?{vivo:!0}:{vivo:!1,motivo:"shortcut"});}catch(o){n.fallar(o);}}motivoDeEntregaEntera(e){return e.response?.schema!=null?"output-contract":e.savings?.deferrable===true?"deferrable":
738
- typeof this.config.provider.generateStream!="function"?"provider-without-streaming":null}async llamarProveedor(e,n){n.llamadas+=1;let r;try{r=await this.config.provider.generate(e);}catch(o){throw n.falloDelProveedor=
739
- true,o}return r.usage.complete===false&&(n.sinContador+=1),r}async llamarProveedorEnStream(e,n,r){if(r.senal.aborted)throw new le(n.llamadas>0);n.llamadas+=1;let o="",s;try{for await(let i of this.config.provider.
740
- generateStream(e,{signal:r.senal})){if(r.senal.aborted)break;if(i.type==="text")i.delta!==""&&(o+=i.delta,r.texto(i.delta));else if(i.type==="done"){s=i.response;break}}}catch(i){throw r.senal.aborted?
741
- new le(true):(n.falloDelProveedor=true,i)}if(!s)throw r.senal.aborted?new le(true):(n.falloDelProveedor=true,new Error(`provider "${this.config.provider.id}" stream ended without a final response`));return r.
742
- proveedorTermino(),s.usage.complete===false&&(n.sinContador+=1),s.text!==o&&(this.avisar(`stream-texto-distinto:${this.config.provider.id}`,`[bvsala] provider "${this.config.provider.id}" streamed text t\
743
- hat differs from its final response; the streamed text is what the caller received, so it is what is reported and cached. Its generateStream must end with a done whose response.text equals the concate\
744
- nated deltas.`),s=is(s,{...s,text:o})),r.sirvioEnVivo=true,s}decidirMarcadoDeCache(e,n,r,o,s,i,a){let c={marcar:false,huella:"",mensajesDePrefijo:0,cacheWriteMultiplier:1},u=Tl(n,this.config.compressionEconomics);
745
- if(!u)return a.record("prefix-cache","skipped",{reason:`no cache read discount for model "${n}" (unrecognised provider, or a declared tier that does not discount reads): not claiming a cacheable prefi\
746
- x`}),c;if(!o.setIsStable)return a.record("prefix-cache","skipped",{reason:"the tool SET is selected per request; tools render first, so the prefix cannot hit. Pruning wins here (it is a measured savin\
747
- g); pass the tools you want fixed."}),c;if(s)return a.record("prefix-cache","skipped",{reason:"savings.toolDiscovery is on: which schemas travel is decided by a non-deterministic probe, so the tool bl\
748
- ock \u2014 which renders first \u2014 varies across requests that would share a prefix fingerprint. Marking would pay the 1.25x write premium for a prefix that cannot hit. Turn tool discovery off to reclaim the\
749
- prefix cache."}),c;if(i<=0)return c;let l=r.slice(0,i),d=this.tokensFor(this.assemblePromptText(l,o.tools),e),m=this.tokensFor(this.assemblePromptText(r,o.tools),e),f=G(ae({model:n,tools:(o.tools??[]).
750
- map(g=>g.id),prefijo:l.map(g=>`${g.role}:${g.content}`)})),h=this.verjaDeCache.decidir(f,{totalTokens:m,stablePrefixTokens:d,tier:u});return a.record("prefix-cache",h.marcar?"marked":"skipped",{reason:h.
751
- razon,stablePrefixTokens:d,breakEvenHitRate:h.umbral,observedHitRate:h.observada}),h.marcar?{marcar:true,huella:f,mensajesDePrefijo:i,cacheWriteMultiplier:u.cacheWriteMultiplier}:c}decidirCascada(e,n,r,o){
752
- let s=r.modelCascade??"off",i={modo:"off",modeloPedido:e.model,modeloServido:e.model,candidato:null,enruta:false,elegible:false,razon:"the model cascade is off",fuerza:"none",bucket:"",economia:null,observada:null,
753
- muestras:0,precioBarato:null,tasaDeMuestreo:0};if(s==="off")return i;let a=_i({schema:e.response?.schema,tools:e.tools}),c=Ii(e.model,this.config.modelCascade?.pairs??Zr),u=this.precioConocido(e.model),
754
- l=c?this.precioConocido(c):void 0,d=Ci(l,u),m=G(ae({tenant:n.tenantId,scope:n.authorizationScope,contract:n.contractId,schema:n.schemaVersion,fuerte:e.model,barato:c,tools:n.toolsetHash})),f=this.verjaDeCascada.
755
- estado(m),h={modo:s,modeloPedido:e.model,modeloServido:e.model,candidato:c,enruta:false,elegible:false,razon:a.razon,fuerza:a.fuerza,bucket:m,economia:d,observada:f&&f.enrutadas>0?f.escaladas/f.enrutadas:null,
756
- muestras:f?.enrutadas??0,precioBarato:l??null,tasaDeMuestreo:0},g=b=>(o.record("model-cascade",s==="on"?"not routed":"not eligible",{reason:b}),{...h,razon:b});if(!a.elegible)return g(a.razon);if(!c)return g(
757
- `no cheaper model is paired with "${e.model}"; declare one in createSavingsLayer({ modelCascade: { pairs } }) if your provider has one`);if(!d){let b=[...this.precioConocido(e.model)?[]:[e.model],...l?
758
- []:[c]];return g(`no known price for ${b.map(x=>`"${x}"`).join(" or ")||"this pair"}, so the arithmetic that decides whether routing pays cannot be run. The illustrative default price is deliberately \
759
- NOT used here: it would approve a pair nobody has priced. Pass \`costModels\` for both models to enable the cascade for them`)}if(!d.viable)return g(d.razon);let p=Math.min(1,Math.max(0,this.config.modelCascade?.
760
- shadowSampleRate??0));if(s==="shadow")return o.record("model-cascade","shadow",{candidateModel:c,costRatio:d.r,breakEvenEscalationRate:d.equilibrio,verifier:a.fuerza,workload:m,note:"measuring only: t\
761
- he request goes to the model you asked for. The escalation rate is not a quality score \u2014 a well-formed answer with wrong content passes the verifier."}),{...h,elegible:true,razon:a.razon,tasaDeMuestreo:p};
762
- let v=this.verjaDeCascada.decidir(m,d);return v.enrutar?(this.avisar(`cascada:${e.model}->${c}`,`[bv-sala] model cascade ON: requests for "${e.model}" may be answered by "${c}" when a deterministic ga\
763
- te accepts the answer. The gate checks the SHAPE of the answer against your output contract, never its meaning, so a well-formed answer with wrong content is served and counted as a success. report.mo\
764
- del always names the model that answered, and report.qualityStatus reads "bounded_degradation".`),o.record("model-cascade","routed",{candidateModel:c,costRatio:d.r,breakEvenEscalationRate:d.equilibrio,
765
- observedEscalationRate:v.observada,verifier:a.fuerza,workload:m,reason:v.razon}),{...h,modeloServido:c,enruta:true,elegible:true,razon:v.razon,observada:v.observada,muestras:v.muestras,tasaDeMuestreo:0}):
766
- (o.record("model-cascade","off (gate)",{reason:v.razon,observedEscalationRate:v.observada,breakEvenEscalationRate:d.equilibrio}),{...h,elegible:true,razon:v.razon,observada:v.observada,muestras:v.muestras})}devOpen(){
767
- 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,r=typeof e.
768
- reason=="function"?e.reason():void 0;throw new Ce(ca(n,r),n)}throw e?new Ce(hl(),"invalid"):new Ce(ca("none"),"none")}avisar(e,n){this.config.silenceWarnings||F(e,n);}avisarDeTruncado(e,n,r,o,s){let i=e.
769
- response?.maxOutputTokens,a=Pt(e)||"(no contractId)",c=s?" The layer has NOTED it: the next requests for this contract will carry their value limits written into the prompt, which is the only thing th\
770
- at can fix it without touching your cap. If it still gets cut off, the task does not fit the contract: widen the schema and raise the cap with it.":"",u=o===null?" The schema does not bound the respon\
771
- se (no `maxLength`/`maxItems`), so there is no way to know in advance how much it needs: bound it and the cap stops being a guess.":i==null?` The contract allows ~${o} tokens and this request declares\
772
- no cap, so the cut came from a PROVIDER cap (the Anthropic API requires \`max_tokens\` and the adapter sends 4096 by default). Declare \`maxOutputTokens\` and the cut stops being a surprise.`:o>i?` T\
773
- he contract allows responses of up to ~${o} tokens with this model (what its \`maxLength\`/\`maxItems\` permit) and the cap is ${i}: no response that uses what the schema itself permits fits. A cap ca\
774
- librated with another model is NOT inherited \u2014 the schema bounds CHARACTERS, which are the same everywhere, and the cap bounds TOKENS, which differ per tokenizer.`:` The contract allows ~${o} tok\
775
- ens and the cap is ${i}, so the cap is not the problem: this model is writing more than its own schema permits (no structured mode enforces \`maxLength\`).${c}`;this.avisar(`salida-truncada:${a}:${n}`,
776
- `[bvsala] The response was cut off after exhausting \`maxOutputTokens\`${i!=null?` (${i})`:""} with model ${n} and contract "${a}": the provider returned finish_reason "length" and ${r} output tokens,\
777
- so the JSON does not validate. NOT retried: with the same cap it would be cut off again, a paid call for the same failure.${u}`);}avisarDePalancasSinConfigurar(e){this.config.silenceWarnings||((e.compression===
778
- true||e.compression==="auto")&&!this.config.compressor&&this.avisar("palanca-sin-compresor","[bv-sala] `savings.compression` was requested but this layer has no compressor, so NOTHING is compressed: the\
779
- long context travels and is paid in full. In the report, `report.compression` is ABSENT and `tokens.eliminatedInput` is 0 \u2014 the same as when there was nothing to compress. The compressor is a sidecar\
780
- because it adds latency and compute that only you should decide to pay for: plug it in with `createSavingsLayer({ compressor })`, any object with `compress({ text })`. If your plan does not include `\
781
- long_context_compression`, that feature is needed too. The rest of the layer keeps saving as usual."),e.semanticCache&&!this.deps.semanticCache&&this.avisar("palanca-sin-cache-semantica",'[bv-sala] `s\
782
- avings.semanticCache` was requested but this layer has no semantic cache, so every rephrased question will come out `cache: "miss"` and be paid to the provider again. It is not on by default because i\
783
- t needs an embedder, which is your own cost and provider: plug it in with `createSavingsLayer({ semanticCache: new InMemorySemanticCache({ embed }) })`. The exact cache and the rest of the layer keep \
784
- working.'));}async generateOptimized(e,n={llamadas:0,falloDelProveedor:false,sinContador:0},r=null){this.assertLicensed();let o=new bt(this.now),s=new He,i=Xn(e),a=er(i),c=e.savings??{};this.avisarDePalancasSinConfigurar(
785
- c);let u=this.decidirCascada(e,i,c,o),l=this.costModelFor(u.modeloServido);o.record("canonicalize","done",{tenant:i.tenantId,contract:i.contractId}),o.record("policy",a.reasons.join("; ")||"no restric\
786
- tions",{allowExactCache:a.allowExactCache,allowSemanticCache:a.allowSemanticCache});let d=this.tokensFor(this.assembleBaselinePrompt(e),e),m=e.response?.maxOutputTokens??256,f,h=()=>f??=uo(e);if(s.baselineInput=
787
- d,s.baselineOutput=m,s.baselineTools=e.tools?.length??0,c.deterministicResolvers!==false){let b=this.deps.resolvers.try(i);if(b)return s.avoidCall(d,this.tokensFor(b.text,e)),o.record("resolver",b.resolver,
788
- {avoided:true}),this.finish(e,i,{text:b.text,data:b.data,storedAtMs:this.now()},"deterministic",s,l,o,It(),_t(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(u,{servedModel:e.model}))}let g=Qn(
789
- i,{servedModel:u.modeloServido});if(a.allowExactCache&&c.exactCache!==false){let b=await this.deps.exactCache.get(g);if(b){let x=this.creditoPorReferencia(Gi(b.meta),{request:e,cascada:u,toggles:c,huella:h,
790
- texto:b.text,claveLeida:g,calidad:()=>{let y=e.response?.schema;return !y||ee(b.data,y).valid}});return x.ok?s.avoidCallByReference(x.credit):(s.avoidCall(d,this.tokensFor(b.text,e)),s.referenceRejected=
791
- x.reason),o.record("exact-cache","hit",{ageMs:this.now()-b.storedAtMs,basis:x.ok?"reference":"estimated",...x.ok?{}:{referenceRejected:x.reason},...x.ok&&x.outputNotCredited?{outputNotCredited:x.outputNotCredited}:
792
- {}}),this.finish(e,i,b,"exact",s,l,o,It(),_t(),this.now()-b.storedAtMs,void 0,void 0,void 0,void 0,this.informeDeCascada(u))}o.record("exact-cache","miss");}let p=Do(i,{servedModel:u.modeloServido,deferrable:c.
793
- deferrable===true,toolDiscovery:c.toolDiscovery===true,...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{}}),v=async()=>{try{return await this.expensivePath(n,e,i,a,c,s,l,
794
- o,g,d,u,r)}catch(b){throw (n.falloDelProveedor||n.llamadas>0)&&fl(b),b}};if(a.allowSingleflight&&c.singleflight!==false){if(r){let y=this.deps.singleflight,k=typeof y.join=="function"?y.join(p):void 0;if(k){
795
- let E=await k;return o.record("singleflight","coalesced",{key:p}),this.asCoalescedFollower(E,d,this.tokensFor(E.text??"",e),l,e)}return o.record("singleflight","skipped (streaming: a streamed request \
796
- never leads)"),v()}let{value:b,coalesced:x}=await this.deps.singleflight.run(p,v);if(x){o.record("singleflight","coalesced",{key:p});let y=this.creditoPorReferencia(this.referenciasDeLider.get(b)??"ab\
797
- sent",{request:e,cascada:u,toggles:c,huella:h,texto:b.text??"",claveLeida:void 0,calidad:()=>b.report.constraints.structurallyValid!==false&&b.report.qualityStatus!=="rejected"});return this.asCoalescedFollower(
798
- b,d,this.tokensFor(b.text??"",e),l,e,y)}return b}return v()}async expensivePath(e,n,r,o,s,i,a,c,u,l,d,m){let f=this.entitled("semantic_cache");if(o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&
799
- !f&&c.record("semantic-cache","degraded: feature not licensed (free tier)"),o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&f){let S=await this.deps.semanticCache.find(r);if(S)return i.
800
- avoidCall(l,this.tokensFor(S.record.answer.text,n)),c.record("semantic-cache","hit",{confidence:S.confidence,similarity:S.similarity}),this.finish(n,r,S.record.answer,"semantic",i,a,c,It(),_t(),S.ageMs,
801
- S.confidence,void 0,void 0,void 0,this.informeDeCascada(d,{servedModel:n.model}));c.record("semantic-cache","miss");}let h=s.router===false,g=h?It():this.deps.router.classify(r);c.record("router",g.executionClass,
802
- {confidence:g.confidence,reason:g.reason});let p=h?this.deps.toolSelector.passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,g.executionClass,r.toolsetHash);if(i.actualTools=p.
803
- tools.length,p.droppedIds.length){let S=new Set(p.droppedIds),A=(n.tools??[]).filter(L=>S.has(L.id)).reduce((L,q)=>L+this.tokensFor(po(q),n),0);i.eliminate(A),c.record("tool-selector",p.reason,{dropped:p.
804
- droppedIds,eliminatedTokens:A});}i.baselineRetrieval=this.config.retriever?g.rounds:0;let v=await Fo({execution:g.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.maxRounds??g.rounds,maxDocuments:n.
805
- retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});i.actualRetrieval=v.rounds,v.retrievedCount>0&&c.
806
- record("retrieval",`kept ${v.keptCount}/${v.retrievedCount}`,{rounds:v.rounds});let b=_t(),x=[...n.messages],y=mo(n.messages),k=false,E=v.docs.length>0?{role:"system",content:`Retrieved context \u2014 answer \
807
- using only this evidence and cite sources by [id]:
805
+ cense status: none)"}function op(){return "licenseGate must implement isActive(): a gate that cannot prove the license is live is refused. In this published package an injected gate is not a licensing \
806
+ path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var gr=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new cr;verjaDeCascada;memoriaDelCodebook=new pr;referenciasDeLider=new WeakMap;noReproducibles=new WeakSet;comprobador;constructor(e,n={}){
807
+ this.config=e,this.deps=Aa(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>jt()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.verjaDeCascada=new ur(e.modelCascade?.
808
+ exploration!=null?{exploracion:e.modelCascade.exploration}:{});let r=mr(e.verification);this.comprobador=r.activo&&n.verificacion?new hr({ajustes:r,provider:e.provider,precio:o=>this.precioConocido(o),
809
+ contrato:(o,i)=>ip(o,i),now:this.now,sumidero:n.verificacion,avisar:(o,i)=>this.avisar(o,i)}):void 0;}conVerificacion(e,n,r){return this.comprobador?this.comprobador.decidir(e,n,r):n}cerrarVerificacion(){
810
+ this.comprobador?.cerrar();}async generate(e){this.assertLicensed(),e=this.conPalancasPorDefecto(e);let n={llamadas:0,falloDelProveedor:false,sinContador:0},r;try{r=await this.generateOptimized(e,n);}catch(o){
811
+ if(o instanceof $e||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||xc(o))throw o;return this.conVerificacion(e,await this.failOpenDirect(e,o),"fail-open")}return this.conVerificacion(e,
812
+ r,"optimizado")}generateStream(e,n={},r){let o;try{o=new tn(this.now,n?.signal);}catch(i){let s=new tn(this.now);return s.fallar(i),s.handle}return this.ejecutarStream(e,o,r),o.handle}async ejecutarStream(e,n,r){
813
+ try{if(r&&await r,n.abortado)throw new pe(!1);e=this.conPalancasPorDefecto(e);let o=this.motivoDeEntregaEntera(e);if(o){let a=await this.generate(e);n.completar(a,{vivo:!1,motivo:o});return}this.assertLicensed(),
814
+ n.entrarEnVivo();let i={llamadas:0,falloDelProveedor:!1,sinContador:0},s;try{s=await this.generateOptimized(e,i,n.sumidero);}catch(a){if(a instanceof $e||a instanceof pe)throw a;if(n.sumidero.senal.aborted)
815
+ throw new pe(i.llamadas>0);if(this.config.failOpen===!1||i.falloDelProveedor||i.llamadas>0||xc(a))throw a;let u=this.conVerificacion(e,await this.failOpenDirect(e,a),"fail-open");n.completar(u,{vivo:!1,
816
+ motivo:"fail-open"});return}s=this.conVerificacion(e,s,"optimizado"),n.completar(s,n.sumidero.sirvioEnVivo?{vivo:!0}:{vivo:!1,motivo:"shortcut"});}catch(o){n.fallar(o);}}conPalancasPorDefecto(e){let n=this.
817
+ config.priceLevers;if(!n)return e;let r=e.savings,o=n.deferrable===true&&r?.deferrable===void 0,i=n.standalone===true&&r?.standalone===void 0;return !o&&!i?e:{...e,savings:{...r??{},...o?{deferrable:true}:{},
818
+ ...i?{standalone:true}:{}}}}motivoDeEntregaEntera(e){return e.response?.schema!=null?"output-contract":e.savings?.deferrable===true?"deferrable":typeof this.config.provider.generateStream!="function"?"pro\
819
+ vider-without-streaming":null}async llamarProveedor(e,n){n.llamadas+=1;let r;try{r=await this.config.provider.generate(e);}catch(o){throw n.falloDelProveedor=true,o}return r.usage.complete===false&&(n.sinContador+=
820
+ 1),r}async llamarProveedorEnStream(e,n,r){if(r.senal.aborted)throw new pe(n.llamadas>0);n.llamadas+=1;let o="",i;try{for await(let s of this.config.provider.generateStream(e,{signal:r.senal})){if(r.senal.
821
+ aborted)break;if(s.type==="text")s.delta!==""&&(o+=s.delta,r.texto(s.delta));else if(s.type==="done"){i=s.response;break}}}catch(s){throw r.senal.aborted?new pe(true):(n.falloDelProveedor=true,s)}if(!i)throw r.
822
+ senal.aborted?new pe(true):(n.falloDelProveedor=true,new Error(`provider "${this.config.provider.id}" stream ended without a final response`));return r.proveedorTermino(),i.usage.complete===false&&(n.sinContador+=
823
+ 1),i.text!==o&&(this.avisar(`stream-texto-distinto:${this.config.provider.id}`,`[bvsala] provider "${this.config.provider.id}" streamed text that differs from its final response; the streamed text is \
824
+ what the caller received, so it is what is reported and cached. Its generateStream must end with a done whose response.text equals the concatenated deltas.`),i=gs(i,{...i,text:o})),r.sirvioEnVivo=true,i}decidirMarcadoDeCache(e,n,r,o,i,s,a){
825
+ let u=e.savings?.standalone===true&&Ut(n,Ht(this.config.provider))?ds(n):null,c=u!==null,l={marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:c},d=mp(n,this.config.
826
+ compressionEconomics);if(!d)return a.record("prefix-cache","skipped",{reason:`no cache read discount for model "${n}" (unrecognised provider, or a declared tier that does not discount reads): not clai\
827
+ ming a cacheable prefix`}),l;if(!o.setIsStable)return a.record("prefix-cache","skipped",{reason:"the tool SET is selected per request; tools render first, so the prefix cannot hit. Pruning wins here (\
828
+ it is a measured saving); pass the tools you want fixed."}),l;if(i)return a.record("prefix-cache","skipped",{reason:"savings.toolDiscovery is on: which schemas travel is decided by a non-deterministic\
829
+ probe, so the tool block \u2014 which renders first \u2014 varies across requests that would share a prefix fingerprint. Marking would pay the 1.25x write premium for a prefix that cannot hit. Turn tool discov\
830
+ ery off to reclaim the prefix cache."}),l;if(s<=0)return l;let f=r.slice(0,s),m=this.tokensFor(this.assemblePromptText(f,o.tools),e),h=this.tokensFor(this.assemblePromptText(r,o.tools),e),b=Y(ve({model:n,
831
+ tools:(o.tools??[]).map(g=>g.id),prefijo:f.map(g=>`${g.role}:${g.content}`)})),p=c?`${b}|explicit`:b,v=this.verjaDeCache.decidir(p,{totalTokens:h,stablePrefixTokens:m,tier:u??d});return a.record("pref\
832
+ ix-cache",v.marcar?"marked":"skipped",{reason:v.razon,stablePrefixTokens:m,breakEvenHitRate:v.umbral,observedHitRate:v.observada,...c?{mode:"explicit"}:{}}),v.marcar?{marcar:true,huella:b,claveDeVerja:p,
833
+ mensajesDePrefijo:s,cacheWriteMultiplier:d.cacheWriteMultiplier,explicita:c}:l}decidirCascada(e,n,r,o,i=this.now()){let s=r.modelCascade??"off",a={modo:"off",modeloPedido:e.model,modeloServido:e.model,
834
+ candidato:null,enruta:false,elegible:false,razon:"the model cascade is off",fuerza:"none",bucket:"",economia:null,observada:null,muestras:0,precioBarato:null,tasaDeMuestreo:0};if(s==="off")return a;let u=za(
835
+ {schema:e.response?.schema,tools:e.tools}),c=Ba(e.model,this.config.modelCascade?.pairs??Ko),l=this.precioConocido(e.model,i),d=c?this.precioConocido(c,i):void 0,f=Fa(d,l),m=Y(ve({tenant:n.tenantId,scope:n.
836
+ authorizationScope,contract:n.contractId,schema:n.schemaVersion,fuerte:e.model,barato:c,tools:n.toolsetHash})),h=this.verjaDeCascada.estado(m),b={modo:s,modeloPedido:e.model,modeloServido:e.model,candidato:c,
837
+ enruta:false,elegible:false,razon:u.razon,fuerza:u.fuerza,bucket:m,economia:f,observada:h&&h.enrutadas>0?h.escaladas/h.enrutadas:null,muestras:h?.enrutadas??0,precioBarato:d??null,tasaDeMuestreo:0},p=y=>(o.
838
+ record("model-cascade",s==="on"?"not routed":"not eligible",{reason:y}),{...b,razon:y});if(!u.elegible)return p(u.razon);if(!c)return p(`no cheaper model is paired with "${e.model}"; declare one in cr\
839
+ eateSavingsLayer({ modelCascade: { pairs } }) if your provider has one`);if(!f){let y=[...this.precioConocido(e.model,i)?[]:[e.model],...d?[]:[c]];return p(`no known price for ${y.map(k=>`"${k}"`).join(
840
+ " or ")||"this pair"}, so the arithmetic that decides whether routing pays cannot be run. The illustrative default price is deliberately NOT used here: it would approve a pair nobody has priced. Pass \
841
+ \`costModels\` for both models to enable the cascade for them`)}if(!f.viable)return p(f.razon);let v=Math.min(1,Math.max(0,this.config.modelCascade?.shadowSampleRate??0));if(s==="shadow")return o.record(
842
+ "model-cascade","shadow",{candidateModel:c,costRatio:f.r,breakEvenEscalationRate:f.equilibrio,verifier:u.fuerza,workload:m,note:"measuring only: the request goes to the model you asked for. The escala\
843
+ tion rate is not a quality score \u2014 a well-formed answer with wrong content passes the verifier."}),{...b,elegible:true,razon:u.razon,tasaDeMuestreo:v};let g=this.verjaDeCascada.decidir(m,f);return g.
844
+ enrutar?(this.avisar(`cascada:${e.model}->${c}`,`[bv-sala] model cascade ON: requests for "${e.model}" may be answered by "${c}" when a deterministic gate accepts the answer. The gate checks the SHAPE\
845
+ of the answer against your output contract, never its meaning, so a well-formed answer with wrong content is served and counted as a success. report.model always names the model that answered, and re\
846
+ port.qualityStatus reads "bounded_degradation".`),o.record("model-cascade","routed",{candidateModel:c,costRatio:f.r,breakEvenEscalationRate:f.equilibrio,observedEscalationRate:g.observada,verifier:u.fuerza,
847
+ workload:m,reason:g.razon}),{...b,modeloServido:c,enruta:true,elegible:true,razon:g.razon,observada:g.observada,muestras:g.muestras,tasaDeMuestreo:0}):(o.record("model-cascade","off (gate)",{reason:g.razon,
848
+ observedEscalationRate:g.observada,breakEvenEscalationRate:f.equilibrio}),{...b,elegible:true,razon:g.razon,observada:g.observada,muestras:g.muestras})}devOpen(){return false}assertLicensed(){if(this.devOpen())
849
+ 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,r=typeof e.reason=="function"?e.reason():void 0;throw new $e(
850
+ wc(n,r),n)}throw e?new $e(op(),"invalid"):new $e(wc("none"),"none")}avisar(e,n){this.config.silenceWarnings||V(e,n);}avisarDeTruncado(e,n,r,o,i){let s=e.response?.maxOutputTokens,a=sn(e)||"(no contract\
851
+ Id)",u=i?" The layer has NOTED it: the next requests for this contract will carry their value limits written into the prompt, which is the only thing that can fix it without touching your cap. If it s\
852
+ till gets cut off, the task does not fit the contract: widen the schema and raise the cap with it.":"",c=o===null?" The schema does not bound the response (no `maxLength`/`maxItems`), so there is no w\
853
+ ay to know in advance how much it needs: bound it and the cap stops being a guess.":s==null?` The contract allows ~${o} tokens and this request declares no cap, so the cut came from a PROVIDER cap (th\
854
+ e Anthropic API requires \`max_tokens\` and the adapter sends 4096 by default). Declare \`maxOutputTokens\` and the cut stops being a surprise.`:o>s?` The contract allows responses of up to ~${o} toke\
855
+ ns with this model (what its \`maxLength\`/\`maxItems\` permit) and the cap is ${s}: no response that uses what the schema itself permits fits. A cap calibrated with another model is NOT inherited \u2014 t\
856
+ he schema bounds CHARACTERS, which are the same everywhere, and the cap bounds TOKENS, which differ per tokenizer.`:` The contract allows ~${o} tokens and the cap is ${s}, so the cap is not the proble\
857
+ m: this model is writing more than its own schema permits (no structured mode enforces \`maxLength\`).${u}`;this.avisar(`salida-truncada:${a}:${n}`,`[bvsala] The response was cut off after exhausting \
858
+ \`maxOutputTokens\`${s!=null?` (${s})`:""} with model ${n} and contract "${a}": the provider returned finish_reason "length" and ${r} output tokens, so the JSON does not validate. NOT retried: with th\
859
+ e same cap it would be cut off again, a paid call for the same failure.${c}`);}avisarDePalancasSinConfigurar(e){this.config.silenceWarnings||((e.compression===true||e.compression==="auto")&&!this.config.
860
+ compressor&&this.avisar("palanca-sin-compresor","[bv-sala] `savings.compression` was requested but this layer has no compressor, so NOTHING is compressed: the long context travels and is paid in full.\
861
+ In the report, `report.compression` is ABSENT and `tokens.eliminatedInput` is 0 \u2014 the same as when there was nothing to compress. The compressor is a sidecar because it adds latency and compute that \
862
+ only you should decide to pay for: plug it in with `createSavingsLayer({ compressor })`, any object with `compress({ text })`. If your plan does not include `long_context_compression`, that feature is\
863
+ needed too. The rest of the layer keeps saving as usual."),e.semanticCache&&!this.deps.semanticCache&&this.avisar("palanca-sin-cache-semantica",'[bv-sala] `savings.semanticCache` was requested but th\
864
+ is layer has no semantic cache, so every rephrased question will come out `cache: "miss"` and be paid to the provider again. It is not on by default because it needs an embedder, which is your own cos\
865
+ t and provider: plug it in with `createSavingsLayer({ semanticCache: new InMemorySemanticCache({ embed }) })`. The exact cache and the rest of the layer keep working.'));}async generateOptimized(e,n={llamadas:0,
866
+ falloDelProveedor:false,sinContador:0},r=null){this.assertLicensed();let o=new Wt(this.now),i=new dt,s=Br(e),a=vn(s),u=e.savings??{};this.avisarDePalancasSinConfigurar(u),u.semanticCache&&u.semanticCache!==
867
+ "include-agentic"&&this.deps.semanticCache&&Sc(s,a)&&this.avisar("semantica-agentica-apagada",'[bv-sala] `savings.semanticCache` is on, but this request is agentic (it declares tools, carries tool cal\
868
+ ls or results, or holds more than one user turn), so the semantic cache was neither consulted nor written for it. That is the default: two runs of an agent loop can differ only in what a tool returned\
869
+ , and the guard under the similarity score cannot see that. The exact cache is unaffected. To include agentic requests, set `savings.semanticCache: "include-agentic"` after measuring it on your own tr\
870
+ affic.');let c=this.now(),l=this.decidirCascada(e,s,u,o,c),d=this.costModelFor(l.modeloServido,c);o.record("canonicalize","done",{tenant:s.tenantId,contract:s.contractId}),o.record("policy",a.reasons.
871
+ join("; ")||"no restrictions",{allowExactCache:a.allowExactCache,allowSemanticCache:a.allowSemanticCache});let f=this.tokensFor(this.assembleBaselinePrompt(e),e),m=e.response?.maxOutputTokens??256,h,b=()=>h??=
872
+ ii(e);if(i.baselineInput=f,i.baselineOutput=m,i.baselineTools=e.tools?.length??0,u.deterministicResolvers!==false){let y=this.deps.resolvers.try(s);if(y)return i.avoidCall(f,this.tokensFor(y.text,e)),o.record(
873
+ "resolver",y.resolver,{avoided:true}),this.finish(e,s,{text:y.text,data:y.data,storedAtMs:this.now()},"deterministic",i,d,o,rn(),on(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(l,{servedModel:e.
874
+ model}))}let p=zr(s,{servedModel:l.modeloServido});if(a.allowExactCache&&u.exactCache!==false){let y=await this.deps.exactCache.get(p);if(y){let k=this.creditoPorReferencia(ac(y.meta),{request:e,cascada:l,
875
+ toggles:u,huella:b,texto:y.text,claveLeida:p,calidad:()=>{let x=e.response?.schema;return !x||de(y.data,x).valid}});return k.ok?i.avoidCallByReference(k.credit):(i.avoidCall(f,this.tokensFor(y.text,e)),
876
+ i.referenceRejected=k.reason),o.record("exact-cache","hit",{ageMs:this.now()-y.storedAtMs,basis:k.ok?"reference":"estimated",...k.ok?{}:{referenceRejected:k.reason},...k.ok&&k.outputNotCredited?{outputNotCredited:k.
877
+ outputNotCredited}:{}}),this.finish(e,s,y,"exact",i,d,o,rn(),on(),this.now()-y.storedAtMs,void 0,void 0,void 0,void 0,this.informeDeCascada(l))}o.record("exact-cache","miss");}let v=Mi(s,{servedModel:l.
878
+ modeloServido,deferrable:u.deferrable===true,toolDiscovery:u.toolDiscovery===true,...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{}}),g=async()=>{try{return await this.expensivePath(
879
+ n,e,s,a,u,i,d,o,p,f,l,r,c)}catch(y){throw (n.falloDelProveedor||n.llamadas>0)&&np(y),y}};if(a.allowSingleflight&&u.singleflight!==false){if(r){let x=this.deps.singleflight,T=typeof x.join=="function"?x.join(
880
+ v):void 0;if(T){let w=await T;return this.noReproducibles.has(w)?(o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),g()):(o.record("singleflight","coalesced",{key:v}),this.
881
+ asCoalescedFollower(w,f,this.tokensFor(w.text??"",e),d,e))}return o.record("singleflight","skipped (streaming: a streamed request never leads)"),g()}let{value:y,coalesced:k}=await this.deps.singleflight.
882
+ run(v,g);if(k&&this.noReproducibles.has(y))return o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),g();if(k){o.record("singleflight","coalesced",{key:v});let x=this.creditoPorReferencia(
883
+ this.referenciasDeLider.get(y)??"absent",{request:e,cascada:l,toggles:u,huella:b,texto:y.text??"",claveLeida:void 0,calidad:()=>y.report.constraints.structurallyValid!==false&&y.report.qualityStatus!=="r\
884
+ ejected"});return this.asCoalescedFollower(y,f,this.tokensFor(y.text??"",e),d,e,x)}return y}return g()}async expensivePath(e,n,r,o,i,s,a,u,c,l,d,f,m){let h=this.entitled("semantic_cache");if(i.semanticCache&&
885
+ i.semanticCache!=="include-agentic"&&this.deps.semanticCache&&Sc(r,o)&&u.record("semantic-cache",'skipped: agentic traffic (default); set savings.semanticCache: "include-agentic" to include it'),o.allowSemanticCache&&
886
+ i.semanticCache&&this.deps.semanticCache&&!h&&u.record("semantic-cache","degraded: feature not included in this license"),o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache&&h){let E=await this.
887
+ deps.semanticCache.find(r);if(E)return s.avoidCall(l,this.tokensFor(E.record.answer.text,n)),u.record("semantic-cache","hit",{confidence:E.confidence,similarity:E.similarity}),this.finish(n,r,E.record.
888
+ answer,"semantic",s,a,u,rn(),on(),E.ageMs,E.confidence,void 0,void 0,void 0,this.informeDeCascada(d,{servedModel:n.model}),void 0,void 0,void 0,{semantico:E});u.record("semantic-cache","miss");}let b=i.
889
+ router===false,p=b?rn():this.deps.router.classify(r);u.record("router",p.executionClass,{confidence:p.confidence,reason:p.reason});let v=b?this.deps.toolSelector.passthrough(n.tools):this.deps.toolSelector.
890
+ select(r.normalizedText,n.tools,p.executionClass,r.toolsetHash);if(s.actualTools=v.tools.length,v.droppedIds.length){let E=new Set(v.droppedIds),M=(n.tools??[]).filter(F=>E.has(F.id)).reduce((F,H)=>F+
891
+ this.tokensFor(ai(H),n),0);s.eliminate(M),u.record("tool-selector",v.reason,{dropped:v.droppedIds,eliminatedTokens:M});}s.baselineRetrieval=this.config.retriever?p.rounds:0;let g=await Vi({execution:p.
892
+ executionClass,query:r.normalizedText,maxRounds:n.retrieval?.maxRounds??p.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.
893
+ reranker?{reranker:this.config.reranker}:{}});s.actualRetrieval=g.rounds,g.retrievedCount>0&&u.record("retrieval",`kept ${g.keptCount}/${g.retrievedCount}`,{rounds:g.rounds});let y=on(),k=[...n.messages],
894
+ x=ui(n.messages),T=false,w=g.docs.length>0?{role:"system",content:`Retrieved context \u2014 answer using only this evidence and cite sources by [id]:
808
895
 
809
- `+v.docs.map((S,A)=>`[${S.source??S.id??`doc${A+1}`}]
810
- ${S.text}`).join(`
896
+ `+g.docs.map((E,M)=>`[${E.source??E.id??`doc${M+1}`}]
897
+ ${E.text}`).join(`
811
898
 
812
- `)}:null,w=Pt(n),I=n.response?.maxOutputTokens!=null?Math.floor(n.response.maxOutputTokens*3.2):null,O=this.contratosQueIncumplen.has(w)?fo(n.response?.schema,"",I):"";if(O&&Dt(x,{role:"system",content:`\
813
- JSON limits (not API-enforced): ${O}`}),n.structuredData!==void 0){let S=JSON.stringify(n.structuredData),A=this.tokensFor(S,n);if(s.serialization!==false){b=this.deps.formatSelector.choose(n.structuredData,
814
- {model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let L=this.tokensFor(b.encoded+b.instruction,n);i.compress(A,L),Dt(x,{role:"system",content:(b.instruction?b.instruction+`
815
- `:"")+b.encoded}),c.record("serialization",b.chosen,{reason:b.reason,jsonTokens:A,chosenTokens:L});}else Dt(x,{role:"system",content:S}),c.record("serialization","json-compact",{reason:"format selector\
816
- disabled; sent compact JSON"});}if(E&&Dt(x,E),(s.compression===true||s.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let S=this.config.compressionEconomics??
817
- {},A=co(n.model,S),L={compressorCostTokens:S.compressorCostTokens??0,...S.minimumContextTokens!=null?{minimumContextTokens:S.minimumContextTokens}:{},...S.minimumNetTokens!=null?{minimumNetTokens:S.minimumNetTokens}:
818
- {}},q=0,N=0;for(let V of x)V.role==="system"?q+=1:N+=this.tokensFor(V.content,n);let Ee=this.tokensFor(this.assemblePromptText(x,p.tools),n),fe=lr({...L,contextTokens:N,projectedEliminable:N}),te=0,me=0,
819
- at=false,he=fe.reason;if(fe.compress){let V=[];for(let ge of x){if(ge.role==="system"){V.push(ge);continue}let ct=this.tokensFor(ge.content,n),ut=await this.config.compressor.compress({text:ge.content}),
820
- wo=!ut.skipped&&ut.fidelityPassed&&Yo(ge.content,ut.compressed),So=wo?this.tokensFor(ut.compressed,n):ct;wo&&So<ct?(V.push({...ge,content:ut.compressed}),te+=ct,me+=So):V.push(ge);}let ko=this.tokensFor(
821
- this.assemblePromptText(V,p.tools),n),Q=lr({...L,contextTokens:N,projectedEliminable:te-me}),zn=$i({originalTokens:Ee,compressedTokens:ko,tier:A,...S.prefix?{prefix:S.prefix}:{},compressorCostTokens:L.
822
- compressorCostTokens});me>=te?he="no fidelity-passed net reduction":Q.compress?zn.comprimir?(at=true,he=zn.razon,k=V.slice(0,y).some((ge,ct)=>ge.content!==x[ct]?.content),x=V,i.compress(te,me)):he=zn.razon:
823
- he=Q.reason;}at||(te=0,me=0),c.record("compression",at?"applied":"skipped",{reason:he,before:te,after:me,contextTokens:N,promptTokens:Ee,cacheTierMinimum:A.minimumCacheTokens,protectedSystemMessages:q,
824
- prefixRewritten:k}),i.compressionReport={originalTokens:te,compressedTokens:me,protectedSpans:q,fidelityPassed:true};}if(s.elision!==false&&o.allowElision&&this.entitled("tool_result_elision")){let S=Fi(x);
825
- if(S.indices.length>0){let A=this.tokensFor(ao,n),L=0;for(let q of S.indices){let N=this.tokensFor(x[q].content,n);L+=Math.max(0,N-A);}(S.indices.some(q=>q<y)&&(k=true),x=zi(x,S.indices),i.eliminate(
826
- L),i.elididoLocal+=L),c.record("elision","applied",{elided:S.indices.length,eliminatedTokens:L,grossBytes:S.bytesOriginales,live:lo});}else c.record("elision","skipped",{reason:"no old/larg\
827
- e tool_result over the age\xD7size threshold"});}let C=n.response?.schema,_=C&&s.outputCodebook===true?Mi(C,S=>this.tokensFor(S,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,Pt(n),s.outputCodebookMeasuredOutputDeltaTokens)}):
828
- null;_&&c.record("output-codebook",_.applied?"applied":"skipped",{reason:_.reason,..._.applied?{renamedKeys:_.plan.renamedKeys,codedEnumValues:_.plan.codedEnumValues,schemaTokensOriginal:_.plan.schemaTokensOriginal,
829
- schemaTokensCompact:_.plan.schemaTokensCompact,modelledShapeSavingTokens:_.plan.modelledShapeSavingTokens,measuredOutputDeltaTokens:_.plan.measuredOutputDeltaTokens,outputDeltaProvenance:_.plan.outputDeltaProvenance,
830
- breakEvenOutputDeltaTokens:_.plan.breakEvenOutputDeltaTokens,netSavingUsd:_.plan.netSavingUsd,pricedForModel:d.modeloServido}:{}});let T=_?.applied?_.plan.compactSchema:C,R=T?Go(d.modeloServido,T,this.
831
- deps.constraintBackends):{backend:"none",reason:"no output contract"};c.record("constraints",R.backend,{reason:R.reason});let D=this.decidirMarcadoDeCache(n,d.modeloServido,x,p,s.toolDiscovery===true,k?
832
- mo(x,true):y,c),M=this.now();if(m?.senal.aborted)throw new le(e.llamadas>0);let j=await this.descubrirHerramientas(e,n,s,p.tools,x,i,a,c),$=j.tools;i.actualTools=$.length;let Y={messages:x,...$.length?{
833
- tools:$}:{},...T?{schema:T}:{},...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:
834
- {},...s.deferrable?{deferrable:true}:{},constraintBackend:R.backend},oe={model:d.modeloServido,...Y,...D.marcar?{stablePrefixMessages:D.mensajesDePrefijo,promptCacheKey:D.huella}:{}},P=m?await this.llamarProveedorEnStream(
835
- oe,e,m):await this.llamarProveedor(oe,e);i.actualLlm+=1;let se=S=>{if(!_?.applied)return S;let A=ze(S);return A.ok?JSON.stringify(_.plan.expand(A.value)):S},B=se(P.text),Se=P.usage,de=false;if(d.enruta){
836
- let S=Qr({texto:B,schema:C,finishReason:P.finishReason,pidioHerramientas:(P.toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!S.acepta),c.record("model-cascade",S.acepta?"accepted":"es\
837
- calating",{servedModel:d.modeloServido,reason:S.motivo,checks:S.comprobaciones}),S.acepta||(de=true,i.cascadeAttempt(P.usage,d.precioBarato??a),i.actualLlm+=1,P=await this.llamarProveedor({model:n.model,
838
- ...Y},e),B=se(P.text));}let pe=de?n.model:d.modeloServido,$e=de?this.costModelFor(n.model):a;i.actualInput+=P.usage.inputTokens,i.actualOutput+=P.usage.outputTokens;let go=P.usage,ma=P.servedServiceTier,
839
- ha=P.structuredNatively===true,At=ss(P),bo;_?.applied&&c.record("output-codebook",ze(P.text).ok?"expanded":"not-expanded (response was not JSON)",ze(P.text).ok?{localOutputTokensCompact:this.tokensFor(P.
840
- text,n),localOutputTokensExpanded:this.tokensFor(B,n),creditedLedger:"none",note:"local count of the served answer in both shapes; not credited to any ledger"}:{}),C&&R.backend==="provider-native"&&P.
841
- structuredNatively===false&&(R={backend:"none",reason:"provider did not enforce the contract natively; the schema travelled in the prompt and the layer is the only validator"},c.record("constraints","non\
842
- e",{downgradedFrom:"provider-native",reason:R.reason})),i.sentInputLocal=this.tokensFor(this.assemblePromptText(x,$),n),i.removedInputLocal=Math.max(0,l-i.sentInputLocal-i.elididoLocal);let ga=i.sentInputLocal;
843
- i.sentInputLocal+=j.tokensLocalesDelSondeo,i.estimatorExact=this.estimatorEsExacto(n),P.usage.cachedInputTokens&&i.providerCached(P.usage.cachedInputTokens),D.marcar&&Se.complete===false?c.record("prefix\
844
- -cache","not measured: the provider reported no usage for this call"):D.marcar&&(i.cacheWritePremium(Se.cacheWriteInputTokens??0,D.cacheWriteMultiplier,d.precioBarato??a),this.verjaDeCache.registrar(D.
845
- huella,Se),c.record("prefix-cache","measured",{cacheRead:Se.cachedInputTokens??0,cacheWritePremiumTokens:Se.cacheWriteInputTokens??0}));let Ve=null;if(d.modo==="shadow"&&d.elegible&&d.candidato&&d.precioBarato&&
846
- wl(u,d.tasaDeMuestreo))try{let S=await this.llamarProveedor({model:d.candidato,...Y},e);i.actualLlm+=1;let A=i.extraCostUsd;i.cascadeAttempt(S.usage,d.precioBarato);let L=se(S.text),q=Qr({texto:L,schema:C,
847
- finishReason:S.finishReason,pidioHerramientas:(S.toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!q.acepta);let N=q.acepta?Pi(L,B):null;Ve={coste:i.extraCostUsd-A,divergio:N?N.divergen:
848
- null},c.record("model-cascade",q.acepta?"sample accepted":"sample escalated",{candidateModel:d.candidato,reason:q.motivo,sampleCost:Ve.coste,...N?{diverged:N.divergen,divergence:N.motivo}:{},note:"mea\
849
- surement only: this answer was NEVER served. The escalation rate it feeds is a money figure, not a quality one"});}catch(S){c.record("model-cascade","sample failed (measurement only; the answer is unaf\
850
- fected)",{error:S instanceof Error?S.message:String(S)});}let Mt=B,Ue=true,ot=(P.toolCalls?.length??0)>0;if(ot&&(Ue=null,C&&c.record("validation","n/a: model requested tool calls (the output contract app\
851
- lies to the final answer)")),C&&!ot){let S=ze(B),A=S.ok?ee(S.value,C):{valid:false,errors:[{path:"$",message:"not valid JSON"}]};S.ok&&S.rescatado!=null&&A.valid&&(B=S.rescatado,c.record("validation","re\
852
- scued-locally",{reason:"the model wrapped valid JSON in prose or a markdown fence; it was extracted locally instead of paying a repair call"})),!A.valid&&Sl(A.errors)&&this.contratosQueIncumplen.add(Pt(
853
- n));let L=P.finishReason==="length",q=!A.valid&&A.errors.some(N=>/not a valid regular expression/.test(N.message));if(!A.valid&&q)c.record("validation","repair-skipped",{reason:"schema defect (uncompi\
854
- lable pattern); no output can satisfy it, a retry is a wasted call",errors:A.errors}),this.avisar("esquema-roto","[bvsala] The response contract has a `pattern` that is not a valid regex, so no respon\
855
- se can satisfy it. NOT retried (it would be a paid call for the same failure). Fix the schema's `pattern`.");else if(!A.valid&&L){let N=Oi(C,te=>this.tokensFor(te,n)),Ee=n.response?.maxOutputTokens??null,
856
- fe=N!==null&&Ee!=null&&N<=Ee;fe&&this.contratosQueIncumplen.add(Pt(n)),c.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same cap would truncate aga\
857
- in",maxOutputTokens:n.response?.maxOutputTokens??null,outputTokens:P.usage.outputTokens,model:pe,...N!==null?{schemaAllowsTokens:N}:{},learnedValueLimits:fe}),this.avisarDeTruncado(n,pe,P.usage.outputTokens,
858
- N,fe);}else if(!A.valid&&R.backend==="none"){let N=A.errors.slice(0,5).map(Q=>`- ${Q.path}: ${Q.message}`).join(`
859
- `),Ee=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
899
+ `)}:null,R=sn(n),D=n.response?.maxOutputTokens!=null?Math.floor(n.response.maxOutputTokens*3.2):null,O=this.contratosQueIncumplen.has(R)?ci(n.response?.schema,"",D):"";if(O&&an(k,{role:"system",content:`\
900
+ JSON limits (not API-enforced): ${O}`}),n.structuredData!==void 0){let E=JSON.stringify(n.structuredData),M=this.tokensFor(E,n);if(i.serialization!==false){y=this.deps.formatSelector.choose(n.structuredData,
901
+ {model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let F=this.tokensFor(y.encoded+y.instruction,n);s.compress(M,F),an(k,{role:"system",content:(y.instruction?y.instruction+`
902
+ `:"")+y.encoded}),u.record("serialization",y.chosen,{reason:y.reason,jsonTokens:M,chosenTokens:F});}else an(k,{role:"system",content:E}),u.record("serialization","json-compact",{reason:"format selector\
903
+ disabled; sent compact JSON"});}if(w&&an(k,w),(i.compression===true||i.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let E=this.config.compressionEconomics??
904
+ {},M=oi(n.model,E),F={compressorCostTokens:E.compressorCostTokens??0,...E.minimumContextTokens!=null?{minimumContextTokens:E.minimumContextTokens}:{},...E.minimumNetTokens!=null?{minimumNetTokens:E.minimumNetTokens}:
905
+ {}},H=0,X=0;for(let oe of k)oe.role==="system"?H+=1:X+=this.tokensFor(oe.content,n);let le=this.tokensFor(this.assemblePromptText(k,v.tools),n),Me=Zr({...F,contextTokens:X,projectedEliminable:X}),te=0,
906
+ fe=0,At=false,Je=Me.reason;if(Me.compress){let oe=[];for(let we of k){if(we.role==="system"){oe.push(we);continue}let Mt=this.tokensFor(we.content,n),Lt=await this.config.compressor.compress({text:we.content}),
907
+ Ti=!Lt.skipped&&Lt.fidelityPassed&&Qi(we.content,Lt.compressed),Ei=Ti?this.tokensFor(Lt.compressed,n):Mt;Ti&&Ei<Mt?(oe.push({...we,content:Lt.compressed}),te+=Mt,fe+=Ei):oe.push(we);}let me=this.tokensFor(
908
+ this.assemblePromptText(oe,v.tools),n),Cr=Zr({...F,contextTokens:X,projectedEliminable:te-fe}),ie=Qa({originalTokens:le,compressedTokens:me,tier:M,...E.prefix?{prefix:E.prefix}:{},compressorCostTokens:F.
909
+ compressorCostTokens});fe>=te?Je="no fidelity-passed net reduction":Cr.compress?ie.comprimir?(At=true,Je=ie.razon,T=oe.slice(0,x).some((we,Mt)=>we.content!==k[Mt]?.content),k=oe,s.compress(te,fe)):Je=ie.
910
+ razon:Je=Cr.reason;}At||(te=0,fe=0),u.record("compression",At?"applied":"skipped",{reason:Je,before:te,after:fe,contextTokens:X,promptTokens:le,cacheTierMinimum:M.minimumCacheTokens,protectedSystemMessages:H,
911
+ prefixRewritten:T}),s.compressionReport={originalTokens:te,compressedTokens:fe,protectedSpans:H,fidelityPassed:true};}if(i.elision!==false&&o.allowElision&&this.entitled("tool_result_elision")){let E=Za(k);
912
+ if(E.indices.length>0){let M=this.tokensFor(ri,n),F=0;for(let H of E.indices){let X=this.tokensFor(k[H].content,n);F+=Math.max(0,X-M);}(E.indices.some(H=>H<x)&&(T=true),k=Xa(k,E.indices),s.eliminate(
913
+ F),s.elididoLocal+=F),u.record("elision","applied",{elided:E.indices.length,eliminatedTokens:F,grossBytes:E.bytesOriginales,live:si});}else u.record("elision","skipped",{reason:"no old/larg\
914
+ e tool_result over the age\xD7size threshold"});}let _=n.response?.schema,S=_&&i.outputCodebook===true?Wa(_,E=>this.tokensFor(E,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,sn(n),i.outputCodebookMeasuredOutputDeltaTokens)}):
915
+ null;S&&u.record("output-codebook",S.applied?"applied":"skipped",{reason:S.reason,...S.applied?{renamedKeys:S.plan.renamedKeys,codedEnumValues:S.plan.codedEnumValues,schemaTokensOriginal:S.plan.schemaTokensOriginal,
916
+ schemaTokensCompact:S.plan.schemaTokensCompact,modelledShapeSavingTokens:S.plan.modelledShapeSavingTokens,measuredOutputDeltaTokens:S.plan.measuredOutputDeltaTokens,outputDeltaProvenance:S.plan.outputDeltaProvenance,
917
+ breakEvenOutputDeltaTokens:S.plan.breakEvenOutputDeltaTokens,netSavingUsd:S.plan.netSavingUsd,pricedForModel:d.modeloServido}:{}});let C=S?.applied?S.plan.compactSchema:_,P=C?Xi(d.modeloServido,C,this.
918
+ deps.constraintBackends):{backend:"none",reason:"no output contract"};u.record("constraints",P.backend,{reason:P.reason});let A=this.decidirMarcadoDeCache(n,d.modeloServido,k,v,i.toolDiscovery===true,T?
919
+ ui(k,true):x,u),L=this.now();if(f?.senal.aborted)throw new pe(e.llamadas>0);let $=await this.descubrirHerramientas(e,n,i,v.tools,k,s,a,u),B=$.tools;s.actualTools=B.length;let z={messages:k,...B.length?{
920
+ tools:B}:{},...C?{schema:C}:{},...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:
921
+ {},...i.deferrable?{deferrable:true}:{},...A.explicita?{explicitCacheWrites:true}:{},constraintBackend:P.backend},Z={model:d.modeloServido,...z,...A.marcar?{stablePrefixMessages:A.mensajesDePrefijo,promptCacheKey:A.
922
+ huella}:{}},I,ne=false,De={...e};try{I=f?await this.llamarProveedorEnStream(Z,e,f):await this.llamarProveedor(Z,e);}catch(E){if(!this.respaldaFaltaDeCapacidad(i,E,f))throw E;Object.assign(e,De),ne=true,u.record(
923
+ "deferred-tier","capacity-fallback",{error:E instanceof Error?E.message.slice(0,200):String(E),reason:'the cheaper tier had no capacity; repeated once at the standard tier and price, as configured wit\
924
+ h priceLevers.onCapacityError: "standard"'});let{deferrable:M,...F}=Z;I=await this.llamarProveedor(F,e);}let ln=Ln(I),Er=I.servedServiceTier;s.actualLlm+=1;let dn=E=>{if(!S?.applied)return E;let M=nt(E);
925
+ return M.ok?JSON.stringify(S.plan.expand(M.value)):E},ee=dn(I.text),st=I.usage,Ke=false;if(d.enruta){let E=Jo({texto:ee,schema:_,finishReason:I.finishReason,pidioHerramientas:(I.toolCalls?.length??0)>0});
926
+ this.verjaDeCascada.registrar(d.bucket,!E.acepta),u.record("model-cascade",E.acepta?"accepted":"escalating",{servedModel:d.modeloServido,reason:E.motivo,checks:E.comprobaciones}),E.acepta||(Ke=true,s.cascadeAttempt(
927
+ I.usage,d.precioBarato??a,A.marcar&&A.cacheWriteMultiplier>1?1:Vt(d.modeloServido)),s.actualLlm+=1,I=await this.llamarProveedor({model:n.model,...z},e),ee=dn(I.text));}let xe=Ke?n.model:d.modeloServido,
928
+ It=Ke?this.costModelFor(n.model,m):a;s.actualInput+=I.usage.inputTokens,s.actualOutput+=I.usage.outputTokens;let zc=I.usage,Vc=I.servedServiceTier,Uc=I.structuredNatively===true,pn=Ln(I),yi;S?.applied&&
929
+ u.record("output-codebook",nt(I.text).ok?"expanded":"not-expanded (response was not JSON)",nt(I.text).ok?{localOutputTokensCompact:this.tokensFor(I.text,n),localOutputTokensExpanded:this.tokensFor(ee,
930
+ n),creditedLedger:"none",note:"local count of the served answer in both shapes; not credited to any ledger"}:{}),_&&P.backend==="provider-native"&&I.structuredNatively===false&&(P={backend:"none",reason:"\
931
+ provider did not enforce the contract natively; the schema travelled in the prompt and the layer is the only validator"},u.record("constraints","none",{downgradedFrom:"provider-native",reason:P.reason})),
932
+ s.sentInputLocal=this.tokensFor(this.assemblePromptText(k,B),n),s.removedInputLocal=Math.max(0,l-s.sentInputLocal-s.elididoLocal);let qc=s.sentInputLocal;s.sentInputLocal+=$.tokensLocalesDelSondeo,s.estimatorExact=
933
+ this.estimatorEsExacto(n),I.usage.cachedInputTokens&&s.providerCached(I.usage.cachedInputTokens);let ki=Vt(xe),Hc=!Ke&&A.marcar&&A.cacheWriteMultiplier>1;ki>1&&!Hc&&(I.usage.cacheWriteInputTokens??0)>
934
+ 0&&s.providerCacheWritePremium(I.usage.cacheWriteInputTokens??0,ki,It),A.marcar&&st.complete===false?u.record("prefix-cache","not measured: the provider reported no usage for this call"):A.marcar&&(s.cacheWritePremium(
935
+ st.cacheWriteInputTokens??0,A.cacheWriteMultiplier,d.precioBarato??a),this.verjaDeCache.registrar(A.claveDeVerja,st),u.record("prefix-cache","measured",{cacheRead:st.cachedInputTokens??0,cacheWritePremiumTokens:st.
936
+ cacheWriteInputTokens??0}));let at=null;if(d.modo==="shadow"&&d.elegible&&d.candidato&&d.precioBarato&&pp(c,d.tasaDeMuestreo))try{let E=await this.llamarProveedor({model:d.candidato,...z},e);s.actualLlm+=
937
+ 1;let M=s.extraCostUsd;s.cascadeAttempt(E.usage,d.precioBarato,Vt(d.candidato));let F=dn(E.text),H=Jo({texto:F,schema:_,finishReason:E.finishReason,pidioHerramientas:(E.toolCalls?.length??0)>0});this.
938
+ verjaDeCascada.registrar(d.bucket,!H.acepta);let X=H.acepta?Va(F,ee):null;at={coste:s.extraCostUsd-M,divergio:X?X.divergen:null},u.record("model-cascade",H.acepta?"sample accepted":"sample escalated",
939
+ {candidateModel:d.candidato,reason:H.motivo,sampleCost:at.coste,...X?{diverged:X.divergen,divergence:X.motivo}:{},note:"measurement only: this answer was NEVER served. The escalation rate it feeds is \
940
+ a money figure, not a quality one"});}catch(E){u.record("model-cascade","sample failed (measurement only; the answer is unaffected)",{error:E instanceof Error?E.message:String(E)});}let fn=ee,ct=true,Oe={},
941
+ Pt=(I.toolCalls?.length??0)>0;if(Pt&&(ct=null,_&&u.record("validation","n/a: model requested tool calls (the output contract applies to the final answer)")),_&&!Pt){let E=nt(ee),M=E.ok?de(E.value,_):{
942
+ valid:false,errors:[{path:"$",message:"not valid JSON"}]},F=false;E.ok&&E.rescatado!=null&&M.valid&&(ee=E.rescatado,F=true,u.record("validation","rescued-locally",{reason:"the model wrapped valid JSON in pros\
943
+ e or a markdown fence; it was extracted locally instead of paying a repair call"})),!M.valid&&fp(M.errors)&&this.contratosQueIncumplen.add(sn(n));let H=I.finishReason==="length",X=!M.valid&&M.errors.some(
944
+ le=>/not a valid regular expression/.test(le.message));if(!M.valid&&X)u.record("validation","repair-skipped",{reason:"schema defect (uncompilable pattern); no output can satisfy it, a retry is a waste\
945
+ d call",errors:M.errors}),this.avisar("esquema-roto","[bvsala] The response contract has a `pattern` that is not a valid regex, so no response can satisfy it. NOT retried (it would be a paid call for \
946
+ the same failure). Fix the schema's `pattern`."),Oe.reparacion={outcome:"skipped",skipReason:"schema_defect"};else if(!M.valid&&H){let le=qa(_,fe=>this.tokensFor(fe,n)),Me=n.response?.maxOutputTokens??
947
+ null,te=le!==null&&Me!=null&&le<=Me;te&&this.contratosQueIncumplen.add(sn(n)),u.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same cap would trunc\
948
+ ate again",maxOutputTokens:n.response?.maxOutputTokens??null,outputTokens:I.usage.outputTokens,model:xe,...le!==null?{schemaAllowsTokens:le}:{},learnedValueLimits:te}),this.avisarDeTruncado(n,xe,I.usage.
949
+ outputTokens,le,te),Oe.reparacion={outcome:"skipped",skipReason:"output_truncated"};}else if(!M.valid&&P.backend==="none"){let le=M.errors.slice(0,5).map(ie=>`- ${ie.path}: ${ie.message}`).join(`
950
+ `),Me=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
860
951
 
861
952
  Previous reply:
862
- ${B}
953
+ ${ee}
863
954
 
864
955
  Problems found:
865
- ${N}
956
+ ${le}
866
957
 
867
- Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],fe=this.tokensFor(this.assemblePromptText(Ee),n),te=i.sentInputLocal>0?i.actualInput/i.sentInputLocal:1,me=Math.
868
- round(te*fe),at=Math.min(P.usage.outputTokens,n.response?.maxOutputTokens??Number.POSITIVE_INFINITY),he=me/1e3*$e.inputPer1k+at/1e3*$e.outputPer1k,V=this.config.skipRepairAboveBaseline?i.estimateCost(
869
- $e):void 0;if(V!=null&&V.baselineEstimate>0&&V.actual+he>V.baselineEstimate&&V!=null)c.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the inva\
870
- lid answer is served as-is and reported as invalid",errors:A.errors,baselineUsd:V.baselineEstimate,actualUsd:V.actual,repairEstimateUsd:he}),this.avisar("reparacion-mas-cara-que-el-baseline",`[bvsala]\
871
- The answer did not satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${V.baselineEstimate}, already spent ~$${V.actual}\
872
- , repair ~$${he.toFixed(6)}). The repair was skipped and the invalid answer is returned with \`constraints.structurallyValid: false\` \u2014 check it before using it. This combination is usually a request ca\
873
- rrying both tools and an output contract; see the adapter warning for the cheaper shapes.`);else {i.retries=1,c.record("validation","repair-attempt",{errors:A.errors}),P=await this.llamarProveedor({model:pe,
874
- messages:Ee,schema:C,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),bo=P.usage,i.actualLlm+=1,i.actualInput+=P.usage.inputTokens,i.actualOutput+=P.usage.outputTokens,
875
- i.repairOutput+=P.usage.outputTokens,i.repairInput+=P.usage.inputTokens,i.sentInputLocal+=fe,B=P.text;let Q=ze(B);A=Q.ok?ee(Q.value,C):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},Q.ok&&(Mt=
876
- Q.value,Q.rescatado!=null&&A.valid&&(B=Q.rescatado));}}else S.ok&&(Mt=S.value);Ue=A.valid,c.record("validation",Ue?"valid":"invalid");}let ba=this.now()-M,va=yl(Mt),st={text:B,data:Mt,rendered:va,storedAtMs:this.
877
- now()},Te=this.informeDeDiferido(s,P,$e);Te&&c.record("deferred-tier",Te.credited?"credited":"not-credited",{...Te.requestedTier?{requestedTier:Te.requestedTier}:{},...Te.servedTier?{servedTier:Te.servedTier}:
878
- {},creditedLedger:"none",reason:Te.reason});let ya=j.aplicado,vo=P.finishReason==="length",it=Ue!==false&&!ot&&!ya&&!vo,yo=this.generateId(),Z;try{Z=Wi({contadorSimulado:dr(this.config.provider),usoPrimario:go,
879
- usoReparacion:bo,tierServido:ma,eliminatedInput:i.eliminatedInput,compressedInput:i.compressedInput,elididoLocal:i.elididoLocal,sentLocalSinSondeo:ga,baselineInput:l,codebookAplicado:_?.applied===!0,tokensDelSondeo:j.
880
- tokensLocalesDelSondeo,sondeoAplicado:j.aplicado,hayEsquema:C!=null,esquemaNativo:ha,esquemaEnFormatoNativo:At?.esquemaEnFormatoNativo===!0&&T===C,esquemaEstricto:At?.esquemaEstricto===!0,esquemaPorPrompt:At?.
881
- esquemaPorPrompt===!0,piezasDelAdaptador:At?.piezasDelAdaptador??0,modeloPedido:n.model,modeloServido:pe,cacheable:it,mensajesDeLaCapa:x.length-n.messages.length,requestId:yo,at:this.now(),textoServido:B,
882
- huella:()=>uo(n)});}catch{Z="fingerprint-failed";}let xo=it&&o.allowExactCache&&s.exactCache!==false;typeof Z=="object"?c.record("reference","written",{inputTokens:Z.inputTokens,outputTokens:Z.outputTokens,
883
- layerInsertions:Z.layerInsertions,...Z.reasoningTokens!==void 0?{reasoningTokens:Z.reasoningTokens}:{},exactCache:xo}):c.record("reference","not-written",{reason:Z});try{it||c.record("cache-write",ot?
884
- "skipped: tool-call turn (an action request must not be replayed from cache)":Ue===!1?"skipped: response fails its output contract":vo?'skipped: answer cut off by the output cap (finish_reason "length\
885
- "); replaying half an answer would bill it as a 100% avoided call':"skipped: answered with a reduced tool view (tool discovery), so it must not be replayed");let S=de?Qn(r,{servedModel:pe}):u;if(xo){let L=this.
886
- config.exactCacheTtlMs??864e5,q=o.maxCacheAgeMs==null?L:Math.min(L,o.maxCacheAgeMs);await this.deps.exactCache.set(S,typeof Z=="object"?{...st,meta:{...st.meta??{},reference:{...Z,cacheKey:S}}}:st,q);}
887
- let A=pe!==n.model;it&&!A&&o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache?await this.deps.semanticCache.store(r,st):it&&A&&s.semanticCache&&c.record("cache-write","semantic write skipp\
888
- ed: a cheaper model answered, and this cache keys on the model the caller asked for");}catch(S){c.record("cache-write","failed (non-fatal; answer already served)",{error:S instanceof Error?S.message:String(
889
- S)});}i.callsWithoutUsage=e.sinContador;let Lt=this.finish(n,r,st,"miss",i,$e,c,g,b,void 0,void 0,Ue,R.backend,ba,this.informeDeCascada(d,{servedModel:pe,...d.enruta?{escalated:de}:{},...d.elegible&&d.
890
- precioBarato?{estimatedSwapSaving:kl(i,de,d.precioBarato,this.costModelFor(n.model))}:{},...Ve?{sampled:true,sampleCost:Bn(Ve.coste),...Ve.divergio!==null?{divergedOnSample:Ve.divergio}:{}}:{},...i.cascadeInput>
891
- 0||i.cascadeOutput>0?{cascadeInputTokens:i.cascadeInput,cascadeOutputTokens:i.cascadeOutput}:{}}),Te,yo);return typeof Z=="object"&&this.referenciasDeLider.set(Lt,Z),ot&&(Lt.toolCalls=P.toolCalls),P.finishReason!==
892
- void 0&&(Lt.finishReason=P.finishReason),Lt}async descubrirHerramientas(e,n,r,o,s,i,a,c){let u={tools:o,tokensLocalesDelSondeo:0,aplicado:false};if(r.toolDiscovery!==true)return u;if(o.length<2)return c.record(
893
- "tool-discovery","skipped (nothing to discover)",{candidates:o.length}),u;let l=p=>this.tokensFor(po(p),n),d=o.map(qi),m=Ui({promptTokens:this.tokensFor(this.assemblePromptText(s),n),esquemasCompletos:o.
894
- reduce((p,v)=>p+l(v),0),descriptoresLigeros:d.reduce((p,v)=>p+l(v),0),esquemasDeLaSegunda:Ki(o.map(p=>({risk:p.risk,tokens:l(p)})),3),salidaFinal:n.response?.maxOutputTokens??256,salidaDelSondeo:96,precio:a});
895
- if(!m.aplicar)return c.record("tool-discovery","skipped (not worth a second call)",{reason:m.razon,oneCall:m.costeDeUnaLlamada,twoCalls:m.costeDeDosLlamadas}),u;let f,h=this.tokensFor(this.assemblePromptText(
896
- s,d),n);try{f=await this.llamarProveedor({model:n.model,messages:s,tools:d,maxOutputTokens:96,...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{}},e);}catch(p){return c.
897
- record("tool-discovery","failed (falling back to a single call with every schema)",{error:p instanceof Error?p.message:String(p)}),u}i.actualLlm+=1,i.actualInput+=f.usage.inputTokens,i.actualOutput+=f.
898
- usage.outputTokens,i.discoveryInput+=f.usage.inputTokens,i.discoveryOutput+=f.usage.outputTokens;let g=Hi((f.toolCalls??[]).map(p=>p.name),o,3);return g.reconocidos.length===0?(c.record("tool-discover\
899
- y","degraded: probe named no known tool",{finishReason:f.finishReason??null,...g.ignorados.length?{unknownNames:g.ignorados}:{}}),{tools:o,tokensLocalesDelSondeo:h,aplicado:false}):(c.record("tool-discov\
900
- ery","applied (two provider calls)",{chosen:g.reconocidos,sent:g.tools.map(p=>p.id),candidates:o.length,...g.ignorados.length?{unknownNames:g.ignorados}:{}}),{tools:g.tools,tokensLocalesDelSondeo:h,aplicado:true})}informeDeCascada(e,n={}){
901
- if(e.modo!=="off")return {mode:e.modo,servedModel:n.servedModel??e.modeloServido,eligible:e.elegible,reason:e.razon,verifier:e.fuerza,creditedLedger:"none",...e.candidato?{candidateModel:e.candidato}:{},
902
- ...e.economia?{costRatio:Ct(e.economia.r),breakEvenEscalationRate:Ct(e.economia.equilibrio),targetEscalationRate:Ct(e.economia.escaladoMaximo)}:{},...e.bucket?{workload:e.bucket}:{},...e.observada!=null?
903
- {escalationRate:Ct(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,r){if(e.deferrable!==true)return;let o=n.requestedServiceTier,s=en(n.servedServiceTier),
904
- i={...o?{requestedTier:o}:{},...s?{servedTier:s.servido}:{},credited:false,creditedLedger:"none",latency:rs(o),reason:""};if(!o)return {...i,reason:ns};if(!s)return {...i,reason:`asked the provider for the\
905
- "${o}" tier, and it reported none back: the rate this request was billed at cannot be known, so nothing is credited`};if(s.factor==null)return {...i,reason:`asked for "${o}" and the provider reports s\
906
- erving "${s.servido}", a tier this layer has no published rate for: nothing is credited`};if(!s.conDescuento)return {...i,reason:`asked for "${o}" and the provider reports serving "${s.servido}", which\
907
- bills at the standard rate: this request was billed as if it had never been deferred`};let a=n.usage,c=Math.min(Math.max(0,a.cachedInputTokens??0),Math.max(0,a.inputTokens)),u=r.cachedInputPer1k??r.inputPer1k,
908
- l=(Math.max(0,a.inputTokens)-c)/1e3*r.inputPer1k+c/1e3*u+Math.max(0,a.outputTokens)/1e3*r.outputPer1k,d=ts(s,l);return {...i,credited:true,discountRate:Ct(s.factor),...d!=null?{estimatedTierSaving:Bn(d)}:
909
- {},reason:`the provider reports serving the "${s.servido}" tier, which bills at ${(s.factor*100).toFixed(0)}% of the standard rate; the discount stacks with provider prefix caching rather than replaci\
910
- ng it`}}diferidoSinLlamada(e){if(e.savings?.deferrable===true)return {credited:false,creditedLedger:"none",latency:"not applicable: no provider call was made for this request.",reason:"no provider call was \
911
- made, so no processing tier was served and none is credited; the call was avoided outright, which is worth more than any tier discount on it"}}finish(e,n,r,o,s,i,a,c,u,l,d,m,f="none",h=0,g,p,v){let b=e.
912
- response?.schema,x=m===null?null:m??(b?ee(r.data,b).valid:true),y=this.buildReport(e,n,o,s,i,a,c,u,l,d,x,f,h,g,p??this.diferidoSinLlamada(e),v);return {requestId:y.requestId,data:r.data,text:r.text,...r.
913
- rendered!==void 0?{rendered:r.rendered}:{},report:y}}buildReport(e,n,r,o,s,i,a,c,u,l,d,m,f,h,g,p){let v=o.estimateCost(s),b=i.elapsed(),x=h!=null&&h.servedModel!==h.requestedModel;return {requestId:p??
914
- this.generateId(),model:h?.servedModel??e.model,calls:{baselineLlm:o.baselineLlm,actualLlm:o.actualLlm,avoidedLlm:o.avoidedLlm,baselineRetrieval:o.baselineRetrieval,actualRetrieval:o.actualRetrieval,baselineTools:o.
915
- baselineTools,actualTools:o.actualTools,retries:o.retries},tokens:{baselineInput:o.baselineInput,actualInput:o.actualInput,eliminatedInput:o.eliminatedInput,compressedInput:o.compressedInput,baselineOutput:o.
916
- publishedBaselineOutput,actualOutput:o.actualOutput,eliminatedOutput:o.eliminatedOutput,...o.providerCachedInput?{providerCachedInput:o.providerCachedInput}:{}},cache:{result:r,...l!==void 0?{confidence:l}:
917
- {},...u!==void 0?{ageMs:u}:{},...o.reference?{reference:{...o.reference}}:{},...o.referenceRejected?{referenceRejected:o.referenceRejected}:{}},routing:{executionClass:a.executionClass,confidence:a.confidence,
918
- rounds:o.actualRetrieval,reason:a.reason},serialization:{chosen:c.chosen,candidateTokens:c.candidateTokens,instructionOverheadTokens:c.instructionOverheadTokens},...o.compressionReport?{compression:o.
919
- compressionReport}:{},constraints:{backend:m,schemaVersion:n.schemaVersion,...d===null?{}:{structurallyValid:d}},qualityStatus:xl(r,d,x),...h?{modelCascade:h}:{},...g?{deferred:g}:{},quality:{...r!=="\
920
- miss"?{freshnessPassed:!er(n).requiresFreshData}:{}},cost:v,latencyMs:{total:b,preprocessing:Math.max(0,b-f),provider:f},traces:i.all()}}async failOpenDirect(e,n){let r=new bt(this.now);r.record("fail\
921
- -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=Xn(e);}catch{i={schemaVersion:e.
922
- response?.version??e.response?.contractId??"none"};}let a=e.response?.schema,c=[...e.messages];e.structuredData!==void 0&&Dt(c,{role:"system",content:JSON.stringify(e.structuredData)});let u=this.now(),
923
- l=await this.config.provider.generate({model:e.model,messages:c,...e.tools?.length?{tools:e.tools}:{},...a?{schema:a}:{},...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:
924
- {},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),d=this.now()-u;o.baselineLlm=1,o.actualLlm=1,o.actualInput=l.usage.inputTokens,o.actualOutput=l.usage.outputTokens,
925
- o.baselineInput=l.usage.inputTokens,o.baselineOutput=l.usage.outputTokens,l.usage.cachedInputTokens&&o.providerCached(l.usage.cachedInputTokens),l.usage.complete===false&&(o.callsWithoutUsage=1);let m=l.
926
- text,f=true,h=(l.toolCalls?.length??0)>0;if(h&&(f=null),a&&!h){let p=ze(l.text);f=p.ok?ee(p.value,a).valid:false,p.ok&&(m=p.value);}let g=this.buildReport(e,i,"miss",o,s,r,It(),_t(),void 0,void 0,f,"none",d,
927
- void 0,e.savings?.deferrable===true?{credited:false,creditedLedger:"none",latency:"unchanged: the fail-open path asks for no processing tier, so this request was scheduled exactly as an ordinary one.",reason:"\
928
- the optimizer failed and this request went out on the direct fail-open path, which asks for no cheaper tier: that tier can be refused for lack of capacity, and trading availability for a discount on a\
929
- last-resort call is the wrong trade"}:void 0);return {requestId:g.requestId,data:m,text:l.text,...h?{toolCalls:l.toolCalls}:{},...l.finishReason!==void 0?{finishReason:l.finishReason}:{},report:g}}asCoalescedFollower(e,n,r,o,s,i={
930
- ok:false,reason:"absent"}){let a=new He;i.ok?a.avoidCallByReference(i.credit):(a.avoidCall(n,r),a.referenceRejected=i.reason);let c=a.estimateCost(o),u=this.generateId(),l=this.diferidoSinLlamada(s),d=l?
931
- {deferred:l}:{},{deferred:m,streaming:f,...h}=e.report;return {...e,requestId:u,report:{...h,requestId:u,calls:{...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:a.baselineInput,actualInput:a.
932
- actualInput,eliminatedInput:a.eliminatedInput,compressedInput:a.compressedInput,baselineOutput:a.publishedBaselineOutput,actualOutput:a.actualOutput,eliminatedOutput:a.eliminatedOutput,...a.providerCachedInput?
933
- {providerCachedInput:a.providerCachedInput}:{}},cache:{result:"singleflight",...a.reference?{reference:{...a.reference}}:a.referenceRejected?{referenceRejected:a.referenceRejected}:{}},...d,cost:c}}}creditoPorReferencia(e,n){
934
- if(typeof e=="string")return {ok:false,reason:e};let r;try{r=n.calidad();}catch{r=false;}try{return Yi(e,{ahoraMs:this.now(),modeloPedido:n.request.model,modeloServido:n.cascada.modeloServido,huella:n.huella(),
935
- textoServidoSha256:G(n.texto),claveLeida:n.claveLeida,calidadOk:r,precio:this.precioDocumentado(n.request.model),determinista:Ji(n.request),salidaDelModelo:wi(n.request.model),topeDeSalida:n.request.response?.
936
- maxOutputTokens,diferible:n.toggles.deferrable===!0})}catch{return {ok:false,reason:"different-request"}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,r){
937
- let o=e.map(s=>s.content);r!==void 0&&o.push(JSON.stringify(r));for(let s of n??[])o.push(po(s));return o.join(`
958
+ Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],te=this.tokensFor(this.assemblePromptText(Me),n),fe=s.sentInputLocal>0?s.actualInput/s.sentInputLocal:1,At=Math.
959
+ round(fe*te),Je=Math.min(I.usage.outputTokens,n.response?.maxOutputTokens??Number.POSITIVE_INFINITY),oe=At/1e3*It.inputPer1k+Je/1e3*It.outputPer1k,me=this.config.skipRepairAboveBaseline?s.estimateCost(
960
+ It):void 0;if(me!=null&&me.baselineEstimate>0&&me.actual+oe>me.baselineEstimate&&me!=null)u.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the\
961
+ invalid answer is served as-is and reported as invalid",errors:M.errors,baselineUsd:me.baselineEstimate,actualUsd:me.actual,repairEstimateUsd:oe}),this.avisar("reparacion-mas-cara-que-el-baseline",`[\
962
+ bvsala] The answer did not satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${me.baselineEstimate}, already spent ~$${me.
963
+ actual}, repair ~$${oe.toFixed(6)}). The repair was skipped and the invalid answer is returned with \`constraints.structurallyValid: false\` \u2014 check it before using it. This combination is usually a req\
964
+ uest carrying both tools and an output contract; see the adapter warning for the cheaper shapes.`),Oe.reparacion={outcome:"skipped",skipReason:"would_cost_more_than_no_layer"};else {s.retries=1,u.record(
965
+ "validation","repair-attempt",{errors:M.errors}),I=await this.llamarProveedor({model:xe,messages:Me,schema:_,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),yi=
966
+ I.usage,s.actualLlm+=1,s.actualInput+=I.usage.inputTokens,s.actualOutput+=I.usage.outputTokens,s.repairOutput+=I.usage.outputTokens,s.repairInput+=I.usage.inputTokens,s.sentInputLocal+=te,ee=I.text;let ie=nt(
967
+ ee);M=ie.ok?de(ie.value,_):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},ie.ok&&(fn=ie.value,ie.rescatado!=null&&M.valid&&(ee=ie.rescatado)),Oe.reparacion={outcome:M.valid?"repaired":"still_\
968
+ invalid"};}}else E.ok&&(fn=E.value);ct=M.valid,!M.valid&&Oe.reparacion===void 0&&(Oe.reparacion={outcome:"skipped",skipReason:"decode_time_constraint"}),Oe.validacion={resultado:M.valid?"passed":"faile\
969
+ d",errores:M.errors.length,desenvuelto:F},u.record("validation",ct?"valid":"invalid");}let Wc=this.now()-L,Kc=cp(fn),_t={text:ee,data:fn,rendered:Kc,storedAtMs:this.now()},Ae=this.informeDeDiferido(i,I,
970
+ xe,ne),Ge=this.informeDeEscrituras(i,ln,st,Er,d.modeloServido,A.marcar);Ge&&u.record("cache-writes",Ge.mode,{breakpoints:Ge.breakpoints,...Ge.avoidedWritePremium?{avoidedWritePremium:Ge.avoidedWritePremium.
971
+ amount,basis:"estimated"}:{},creditedLedger:"none",reason:Ge.reason}),Ae&&u.record("deferred-tier",Ae.credited?"credited":"not-credited",{...Ae.requestedTier?{requestedTier:Ae.requestedTier}:{},...Ae.
972
+ servedTier?{servedTier:Ae.servedTier}:{},creditedLedger:"none",reason:Ae.reason});let Gc=$.aplicado,xi=I.finishReason==="length",Rr=I.replayable===false,Dt=ct!==false&&!Pt&&!Gc&&!xi&&!Rr,wi=this.generateId(),
973
+ re;try{re=sc({contadorSimulado:Xr(this.config.provider),usoPrimario:zc,usoReparacion:yi,tierServido:Vc,eliminatedInput:s.eliminatedInput,compressedInput:s.compressedInput,elididoLocal:s.elididoLocal,sentLocalSinSondeo:qc,
974
+ baselineInput:l,codebookAplicado:S?.applied===!0,tokensDelSondeo:$.tokensLocalesDelSondeo,sondeoAplicado:$.aplicado,hayEsquema:_!=null,esquemaNativo:Uc,esquemaEnFormatoNativo:pn?.esquemaEnFormatoNativo===
975
+ !0&&C===_,esquemaEstricto:pn?.esquemaEstricto===!0,esquemaPorPrompt:pn?.esquemaPorPrompt===!0,piezasDelAdaptador:pn?.piezasDelAdaptador??0,modeloPedido:n.model,modeloServido:xe,cacheable:Dt,mensajesDeLaCapa:k.
976
+ length-n.messages.length,requestId:wi,at:this.now(),textoServido:ee,huella:()=>ii(n)});}catch{re="fingerprint-failed";}let Si=Dt&&o.allowExactCache&&i.exactCache!==false;typeof re=="object"?u.record("refer\
977
+ ence","written",{inputTokens:re.inputTokens,outputTokens:re.outputTokens,layerInsertions:re.layerInsertions,...re.reasoningTokens!==void 0?{reasoningTokens:re.reasoningTokens}:{},exactCache:Si}):u.record(
978
+ "reference","not-written",{reason:re});try{Dt||u.record("cache-write",Pt?"skipped: tool-call turn (an action request must not be replayed from cache)":ct===!1?"skipped: response fails its output contr\
979
+ act":xi?'skipped: answer cut off by the output cap (finish_reason "length"); replaying half an answer would bill it as a 100% avoided call':Rr?"skipped: the provider answer carries content this layer \
980
+ cannot replay":"skipped: answered with a reduced tool view (tool discovery), so it must not be replayed");let E=Ke?zr(r,{servedModel:xe}):c;if(Si){let F=this.config.exactCacheTtlMs??864e5,H=o.maxCacheAgeMs==
981
+ null?F:Math.min(F,o.maxCacheAgeMs);await this.deps.exactCache.set(E,typeof re=="object"?{..._t,meta:{..._t.meta??{},reference:{...re,cacheKey:E}}}:_t,H);}let M=xe!==n.model;Dt&&!M&&o.allowSemanticCache&&
982
+ i.semanticCache&&this.deps.semanticCache?await this.deps.semanticCache.store(r,_t):Dt&&M&&i.semanticCache&&u.record("cache-write","semantic write skipped: a cheaper model answered, and this cache keys\
983
+ on the model the caller asked for");}catch(E){u.record("cache-write","failed (non-fatal; answer already served)",{error:E instanceof Error?E.message:String(E)});}s.callsWithoutUsage=e.sinContador;let Ot=this.
984
+ finish(n,r,_t,"miss",s,It,u,p,y,void 0,void 0,ct,P.backend,Wc,this.informeDeCascada(d,{servedModel:xe,...d.enruta?{escalated:Ke}:{},...d.elegible&&d.precioBarato?{estimatedSwapSaving:dp(s,Ke,d.precioBarato,
985
+ this.costModelFor(n.model,m))}:{},...at?{sampled:true,sampleCost:rt(at.coste),...at.divergio!==null?{divergedOnSample:at.divergio}:{}}:{},...s.cascadeInput>0||s.cascadeOutput>0?{cascadeInputTokens:s.cascadeInput,
986
+ cascadeOutputTokens:s.cascadeOutput}:{}}),Ae,wi,Ge,{...Oe,final:{...I.finishReason!==void 0?{finishReason:I.finishReason}:{},...n.response?.maxOutputTokens!=null?{topeDelLlamante:n.response.maxOutputTokens}:
987
+ {}}});return typeof re=="object"&&this.referenciasDeLider.set(Ot,re),Rr&&this.noReproducibles.add(Ot),Pt&&(Ot.toolCalls=I.toolCalls),I.finishReason!==void 0&&(Ot.finishReason=I.finishReason),Ot}async descubrirHerramientas(e,n,r,o,i,s,a,u){
988
+ let c={tools:o,tokensLocalesDelSondeo:0,aplicado:false};if(r.toolDiscovery!==true)return c;if(o.length<2)return u.record("tool-discovery","skipped (nothing to discover)",{candidates:o.length}),c;let l=p=>this.
989
+ tokensFor(ai(p),n),d=o.map(nc),f=tc({promptTokens:this.tokensFor(this.assemblePromptText(i),n),esquemasCompletos:o.reduce((p,v)=>p+l(v),0),descriptoresLigeros:d.reduce((p,v)=>p+l(v),0),esquemasDeLaSegunda:oc(
990
+ o.map(p=>({risk:p.risk,tokens:l(p)})),3),salidaFinal:n.response?.maxOutputTokens??256,salidaDelSondeo:96,precio:a});if(!f.aplicar)return u.record("tool-discovery","skipped (not worth a second call)",{
991
+ reason:f.razon,oneCall:f.costeDeUnaLlamada,twoCalls:f.costeDeDosLlamadas}),c;let m,h=this.tokensFor(this.assemblePromptText(i,d),n);try{m=await this.llamarProveedor({model:n.model,messages:i,tools:d,maxOutputTokens:96,
992
+ ...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{}},e);}catch(p){return u.record("tool-discovery","failed (falling back to a single call with every schema)",{error:p instanceof
993
+ Error?p.message:String(p)}),c}s.actualLlm+=1,s.actualInput+=m.usage.inputTokens,s.actualOutput+=m.usage.outputTokens,s.discoveryInput+=m.usage.inputTokens,s.discoveryOutput+=m.usage.outputTokens;let b=rc(
994
+ (m.toolCalls??[]).map(p=>p.name),o,3);return b.reconocidos.length===0?(u.record("tool-discovery","degraded: probe named no known tool",{finishReason:m.finishReason??null,...b.ignorados.length?{unknownNames:b.
995
+ ignorados}:{}}),{tools:o,tokensLocalesDelSondeo:h,aplicado:false}):(u.record("tool-discovery","applied (two provider calls)",{chosen:b.reconocidos,sent:b.tools.map(p=>p.id),candidates:o.length,...b.ignorados.
996
+ length?{unknownNames:b.ignorados}:{}}),{tools:b.tools,tokensLocalesDelSondeo:h,aplicado:true})}informeDeCascada(e,n={}){if(e.modo!=="off")return {mode:e.modo,servedModel:n.servedModel??e.modeloServido,eligible:e.
997
+ elegible,reason:e.razon,verifier:e.fuerza,creditedLedger:"none",...e.candidato?{candidateModel:e.candidato}:{},...e.economia?{costRatio:nn(e.economia.r),breakEvenEscalationRate:nn(e.economia.equilibrio),
998
+ targetEscalationRate:nn(e.economia.escaladoMaximo)}:{},...e.bucket?{workload:e.bucket}:{},...e.observada!=null?{escalationRate:nn(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,r,o=false){
999
+ if(e.deferrable!==true)return;let i=Ln(n),s=i?.origen??null,a=n.servedServiceTier;if(o)return {...Ht(this.config.provider)!==void 0?{requestedTier:mt}:{},...a?{servedTier:a}:{},credited:false,capacityFallback:true,
1000
+ creditedLedger:"none",latency:"the cheaper tier refused the request for lack of capacity, and it was repeated once at the standard tier: the wait is the refused attempt plus a standard-tier call.",reason:'\
1001
+ the cheaper tier had no capacity (HTTP 429 or 503), so, as configured with priceLevers.onCapacityError: "standard", the request was repeated once at the standard tier and price; the refused attempt is\
1002
+ not counted as a call and nothing is credited'};let u=n.requestedServiceTier,c={...u?{requestedTier:u}:{},...a?{servedTier:a}:{},credited:false,creditedLedger:"none",latency:us(u,s),reason:""};if(!u)return {
1003
+ ...c,reason:cs};let l=this.precioDelCliente(r),d=as({modelo:r,uso:n.usage,tierServido:a,origen:s,...i?.tierLeidoDe?{tierLeidoDe:i.tierLeidoDe}:{},...l?{precioDelCliente:l}:{},ahoraMs:this.now()});return d.
1004
+ ok?{...c,credited:true,discountRate:nn(d.factorEfectivo),estimatedTierSaving:d.importe,tierSaving:{amount:d.importe,basis:d.basis,standardCost:rt(d.costeEstandar),appliedCost:rt(d.costeAplicado),pricesCheckedOn:d.
1005
+ consultado,basisReason:d.motivoBasis},reason:`the provider reports serving the "${a}" tier; this call's usage was priced at the standard and at the "${a}" published rate cards, component by component \
1006
+ (${(d.factorEfectivo*100).toFixed(1)}% of standard). The discount stacks with provider prefix caching rather than replacing it`}:{...c,reason:lp(d.motivo,u,a)}}informeDeEscrituras(e,n,r,o,i,s){if(e.standalone!==
1007
+ true)return;let a=n?.cacheExplicita;if(!a){let b=Ht(this.config.provider),p="the provider chose where to write its prompt cache, as it does by default";return {mode:"provider-default",breakpoints:0,reason:Ut(
1008
+ i,"openai")?b===void 0?`this provider is not one of this package's adapters, so nothing attests explicit prompt-cache control on it: ${p}`:b!=="openai"?`explicit prompt-cache control only exists on Op\
1009
+ enAI's own API, and this endpoint is not it: ${p}`:`model "${i}" has no list price of its own here, so the layer cannot tell whether writing its prefix pays: ${p}`:`model "${i}" is not an OpenAI model\
1010
+ that bills prompt-cache writes above the input rate, so there was no write premium to avoid: ${p}`}}let u=a.puntos,c="Trade-off: repeats and continuations of this exact prompt lose the cache reads th\
1011
+ e provider default would have given them.",l=u===1?"explicit mode: the provider wrote its prompt cache only at the end of the stable prefix, so the rest of this request was billed at the input rate wi\
1012
+ th no cache-write charge. "+c:(s?"explicit mode with no breakpoint: the message at the prefix boundary cannot carry one":"explicit mode with no breakpoint: there was no stable prefix worth writing, or\
1013
+ the measured hit rate on it did not pay for the write premium")+", so the provider neither wrote nor read its prompt cache for this request. "+c,d=o?_n("openai",o,i,this.now()):void 0,f=Dn(i),m=d&&d.
1014
+ cacheWritePer1k!==void 0?{inputPer1k:d.inputPer1k,cacheWritePer1k:d.cacheWritePer1k,consultado:d.consultado}:f?{inputPer1k:f.inputPer1k,cacheWritePer1k:f.cacheWritePer1k,consultado:void 0}:void 0;if(!m||
1015
+ r.complete===false)return {mode:"explicit",breakpoints:u,reason:l};let h=ps({uso:r,fila:{inputPer1k:m.inputPer1k,cacheWritePer1k:m.cacheWritePer1k},...m.consultado?{consultado:m.consultado}:{}});return {mode:"\
1016
+ explicit",breakpoints:u,avoidedWritePremium:{amount:h.importe,basis:"estimated",standardCost:rt(h.costeEstandar),appliedCost:rt(h.costeAplicado),pricesCheckedOn:h.consultado,basisReason:h.tokensOrdinarios>
1017
+ 0&&r.inputTokens>=1024?"estimated: the provider default was not run for this request. This is the write premium the default would have charged on the tokens after the last breakpoint; it does not subt\
1018
+ ract the cache reads the default could have given a later repeat":"estimated: below the provider's minimum cacheable length (or with nothing written past the breakpoint) the default would not have cha\
1019
+ rged a write premium either"},reason:l}}escriturasSinLlamada(e){if(e.savings?.standalone===true)return {mode:"provider-default",breakpoints:0,reason:"no provider call was made, so nothing was written to \
1020
+ or read from the provider's prompt cache for this request"}}respaldaFaltaDeCapacidad(e,n,r){return e.deferrable!==true||r!==null||this.config.priceLevers?.onCapacityError!=="standard"||Ht(this.config.provider)===
1021
+ void 0?false:n instanceof Error&&/^provider (429|503)\b/.test(n.message)}diferidoSinLlamada(e){if(e.savings?.deferrable===true)return {credited:false,creditedLedger:"none",latency:"not applicable: no provider \
1022
+ call was made for this request.",reason:"no provider call was made, so no processing tier was served and none is credited; the call was avoided outright, which is worth more than any tier discount on \
1023
+ it"}}finish(e,n,r,o,i,s,a,u,c,l,d,f,m="none",h=0,b,p,v,g,y){let k=e.response?.schema,x,T=f===null?null:f??(k?(()=>{let D=de(r.data,k);return x={resultado:D.valid?"passed":"failed",errores:D.errors.length,
1024
+ desenvuelto:false},D.valid})():true),w=x&&!y?.validacion?{...y,validacion:x}:y,R=this.buildReport(e,n,o,i,s,a,u,c,l,d,T,m,h,b,p??this.diferidoSinLlamada(e),v,g??this.escriturasSinLlamada(e),w);return {requestId:R.
1025
+ requestId,data:r.data,text:r.text,...r.rendered!==void 0?{rendered:r.rendered}:{},report:R}}buildReport(e,n,r,o,i,s,a,u,c,l,d,f,m,h,b,p,v,g){let y=o.estimateCost(i),k=s.elapsed(),x=h!=null&&h.servedModel!==
1026
+ h.requestedModel;return {requestId:p??this.generateId(),model:h?.servedModel??e.model,calls:{baselineLlm:o.baselineLlm,actualLlm:o.actualLlm,avoidedLlm:o.avoidedLlm,baselineRetrieval:o.baselineRetrieval,
1027
+ actualRetrieval:o.actualRetrieval,baselineTools:o.baselineTools,actualTools:o.actualTools,retries:o.retries},tokens:{baselineInput:o.baselineInput,actualInput:o.actualInput,eliminatedInput:o.eliminatedInput,
1028
+ compressedInput:o.compressedInput,baselineOutput:o.publishedBaselineOutput,actualOutput:o.actualOutput,eliminatedOutput:o.eliminatedOutput,...o.providerCachedInput?{providerCachedInput:o.providerCachedInput}:
1029
+ {}},cache:{result:r,...l!==void 0?{confidence:l}:{},...c!==void 0?{ageMs:c}:{},...o.reference?{reference:{...o.reference}}:{},...o.referenceRejected?{referenceRejected:o.referenceRejected}:{}},routing:{
1030
+ executionClass:a.executionClass,confidence:a.confidence,rounds:o.actualRetrieval,reason:a.reason},serialization:{chosen:u.chosen,candidateTokens:u.candidateTokens,instructionOverheadTokens:u.instructionOverheadTokens},
1031
+ ...o.compressionReport?{compression:o.compressionReport}:{},constraints:{backend:f,schemaVersion:n.schemaVersion,...d===null?{}:{structurallyValid:d}},qualityStatus:up(r,d,x),qualityLedger:uc({cacheResult:r,
1032
+ structurallyValid:d,backend:f,hayEsquema:e.response?.schema!=null,ageMs:c,cascada:h,hechos:g}),...h?{modelCascade:h}:{},...b?{deferred:b}:{},...v?{cacheWrites:v}:{},quality:{...r!=="miss"?{freshnessPassed:!vn(
1033
+ n).requiresFreshData}:{},...r==="semantic"&&g?.semantico?{semanticScore:g.semantico.similarity}:{}},cost:y,latencyMs:{total:k,preprocessing:Math.max(0,k-m),provider:m},traces:s.all()}}async failOpenDirect(e,n){
1034
+ let r=new Wt(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 dt,i=this.costModelFor(e.model),
1035
+ s;try{s=Br(e);}catch{s={schemaVersion:e.response?.version??e.response?.contractId??"none"};}let a=e.response?.schema,u=[...e.messages];e.structuredData!==void 0&&an(u,{role:"system",content:JSON.stringify(
1036
+ e.structuredData)});let c=this.now(),l=await this.config.provider.generate({model:e.model,messages:u,...e.tools?.length?{tools:e.tools}:{},...a?{schema:a}:{},...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.
1037
+ response.maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),d=this.now()-c;o.baselineLlm=1,o.actualLlm=1,o.actualInput=l.usage.inputTokens,o.actualOutput=
1038
+ l.usage.outputTokens,o.baselineInput=l.usage.inputTokens,o.baselineOutput=l.usage.outputTokens,l.usage.cachedInputTokens&&o.providerCached(l.usage.cachedInputTokens);let f=Vt(e.model);f>1&&(l.usage.cacheWriteInputTokens??
1039
+ 0)>0&&o.providerCacheWritePremium(l.usage.cacheWriteInputTokens??0,f,i),l.usage.complete===false&&(o.callsWithoutUsage=1);let m=l.text,h=true,b={origen:"fail_open",final:{...l.finishReason!==void 0?{finishReason:l.
1040
+ finishReason}:{},...e.response?.maxOutputTokens!=null?{topeDelLlamante:e.response.maxOutputTokens}:{}}},p=(l.toolCalls?.length??0)>0;if(p&&(h=null),a&&!p){let g=nt(l.text),y=g.ok?de(g.value,a).errors.
1041
+ length:1;h=y===0,b.validacion={resultado:h?"passed":"failed",errores:y,desenvuelto:false},g.ok&&(m=g.value);}let v=this.buildReport(e,s,"miss",o,i,r,rn(),on(),void 0,void 0,h,"none",d,void 0,e.savings?.deferrable===
1042
+ true?{credited:false,creditedLedger:"none",latency:"unchanged: the fail-open path asks for no processing tier, so this request was scheduled exactly as an ordinary one.",reason:"the optimizer failed and th\
1043
+ is request went out on the direct fail-open path, which asks for no cheaper tier: that tier can be refused for lack of capacity, and trading availability for a discount on a last-resort call is the wr\
1044
+ ong trade"}:void 0,void 0,e.savings?.standalone===true?{mode:"provider-default",breakpoints:0,reason:"the optimizer failed and this request went out unchanged on the direct fail-open path, so the provid\
1045
+ er chose where to write its prompt cache, as it does by default"}:void 0,b);return {requestId:v.requestId,data:m,text:l.text,...p?{toolCalls:l.toolCalls}:{},...l.finishReason!==void 0?{finishReason:l.finishReason}:
1046
+ {},report:v}}asCoalescedFollower(e,n,r,o,i,s={ok:false,reason:"absent"}){let a=new dt;s.ok?a.avoidCallByReference(s.credit):(a.avoidCall(n,r),a.referenceRejected=s.reason);let u=a.estimateCost(o),c=this.
1047
+ generateId(),l=this.diferidoSinLlamada(i),d=l?{deferred:l}:{},f=this.escriturasSinLlamada(i),{deferred:m,streaming:h,cacheWrites:b,...p}=e.report;return {...e,requestId:c,report:{...p,requestId:c,calls:{
1048
+ ...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:a.baselineInput,actualInput:a.actualInput,eliminatedInput:a.eliminatedInput,compressedInput:a.compressedInput,baselineOutput:a.publishedBaselineOutput,
1049
+ actualOutput:a.actualOutput,eliminatedOutput:a.eliminatedOutput,...a.providerCachedInput?{providerCachedInput:a.providerCachedInput}:{}},cache:{result:"singleflight",...a.reference?{reference:{...a.reference}}:
1050
+ a.referenceRejected?{referenceRejected:a.referenceRejected}:{}},...d,...f?{cacheWrites:f}:{},qualityLedger:lc(e.report.qualityLedger),cost:u}}}creditoPorReferencia(e,n){if(typeof e=="string")return {ok:false,
1051
+ reason:e};let r;try{r=n.calidad();}catch{r=false;}try{return cc(e,{ahoraMs:this.now(),modeloPedido:n.request.model,modeloServido:n.cascada.modeloServido,huella:n.huella(),textoServidoSha256:Y(n.texto),claveLeida:n.
1052
+ claveLeida,calidadOk:r,precio:this.precioDocumentado(n.request.model),determinista:ic(n.request),salidaDelModelo:Ma(n.request.model),topeDeSalida:n.request.response?.maxOutputTokens,diferible:n.toggles.
1053
+ deferrable===!0})}catch{return {ok:false,reason:"different-request"}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,r){let o=e.map(i=>i.
1054
+ content);r!==void 0&&o.push(JSON.stringify(r));for(let i of n??[])o.push(ai(i));return o.join(`
938
1055
  `)}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;
939
1056
  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(
940
- e)}precioConocido(e){return this.precioDelCliente(e)??Ft(e)}precioDelCliente(e){let n=this.config.costModels;if(!n)return;let r=n[e];if(r)return r;let o=e.indexOf("/");if(o>=0){let s=n[e.slice(o+1)];if(s)
941
- return s}}precioDocumentado(e){return this.precioDelCliente(e)??Un(e)}costModelFor(e){let n=this.precioConocido(e);return n||(this.config.defaultCostModel?this.config.defaultCostModel:(this.avisar(`pr\
942
- ecio-ilustrativo:${e}`,`[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}": { inputPer1\
943
- k, outputPer1k } } }.`),xi))}};function gl(t,e){if((e.toolCalls?.length??0)>0||!t.schema)return "none";let n=ze(typeof e.text=="string"?e.text:"");return n.ok&&ee(n.value,t.schema).valid?"met":"missed"}
944
- function ze(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of bl(t))try{return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function bl(t){let e=[],n=/```[ \t]*[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g;
945
- for(let r of t.matchAll(n)){let o=r[1]?.trim();o&&e.push(o);}for(let r of ["{","["]){let o=t.indexOf(r);if(o===-1)continue;let s=vl(t,o);s&&e.push(s);}return e}function vl(t,e){let n=t[e],r=n==="{"?"}":"\
946
- ]",o=0,s=false,i=false;for(let a=e;a<t.length;a+=1){let c=t[a];if(s){i?i=false:c==="\\"?i=true:c==='"'&&(s=false);continue}if(c==='"'){s=true;continue}if(c===n)o+=1;else if(c===r&&(o-=1,o===0))return t.slice(e,a+1)}}
947
- function yl(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function xl(t,e,n=false){if(e===false)return "rejected";if(n)return "bounded_degradation";switch(t){case "deterministic":case "exact":return "e\
948
- xact";case "semantic":return "task_equivalent";default:return "not_verified"}}function Ct(t){return Math.round(t*1e6)/1e6}function Bn(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function kl(t,e,n,r){
949
- if(e)return Bn(-t.extraCostUsd);let o=s=>t.actualInput/1e3*s.inputPer1k+t.actualOutput/1e3*s.outputPer1k;return Bn(o(r)-o(n))}function wl(t,e){if(!(e>0))return false;if(e>=1)return true;let n=G(`${t}:cascade\
950
- -sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function It(){return {executionClass:"NO_RETRIEVAL",confidence:1,reason:"n/a (short-circuited)",rounds:0}}function _t(){return {chosen:"json-co\
951
- mpact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,reason:"no structured payload"}}function fo(t,e="",n=null){if(t==null||typeof t!="object")return "";let r=t,o=[],s=e||"th\
952
- e value",i=h=>typeof r[h]=="number"?r[h]:null,a=i("maxLength"),c=i("minLength"),u=i("maxItems"),l=i("minItems"),d=i("maximum"),m=i("minimum");if(a!=null){let h=n!=null?Math.min(a,n):a;o.push(`${s}<=${h}\
953
- ch`);}c!=null&&o.push(`${s}>=${c}ch`),u!=null&&o.push(`${s}<=${u} items`),l!=null&&o.push(`${s}>=${l} items`),d!=null&&o.push(`${s}<=${d}`),m!=null&&o.push(`${s}>=${m}`),typeof r.pattern=="string"&&o.push(
954
- `${s} matches /${r.pattern}/`);let f=r.properties;if(f&&typeof f=="object")for(let[h,g]of Object.entries(f)){let p=fo(g,e?`${e}.${h}`:h,n);p&&o.push(p);}if(r.items!==void 0){let h=fo(r.items,`${s} entr\
955
- ies`,n);h&&o.push(h);}return o.join("; ")}function Pt(t){let e=t.response;return e?e.contractId??e.version??JSON.stringify(e.schema??{}).slice(0,200):""}function Sl(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.
956
- test(e.message))}function po(t){return JSON.stringify({type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function Dt(t,e){
957
- for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}function mo(t,e=false){if(e){let n=0;for(;n<t.length&&t[n].role==="system";)n+=1;return n}for(let n=t.length-1;n>=0;n--)
958
- if(t[n].role==="user")return n;return mo(t,true)}function Tl(t,e){let n=co(t,e);return n.cacheReadMultiplier<1?n:null}var la=2e3,da=200,El=200,Rl=10,Cl=1e7,Il=5,_l=48*3600*1e3,ho=/^[A-Za-z0-9._:/-]{1,128}$/,rt=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,Ot=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=
959
- 1e3;function Pl(t,e={}){if(!ho.test(t.requestId)||!ho.test(t.requestedModel)||!ho.test(t.servedModel)||typeof t.at!="number"||!Number.isFinite(t.at)||t.at<1e12)return null;let n=typeof e?.ahora=="numb\
960
- er"?e.ahora:Date.now();if(t.at>n+_l)return null;let r=t.optimized;if(!Ot(r.cost)||!rt(r.inputTokens)||!rt(r.cachedInputTokens)||!rt(r.outputTokens))return null;let o=t.prices;if(!Ot(o.inputPer1k)||!Ot(
961
- o.outputPer1k)||o.cachedInputPer1k!==void 0&&!Ot(o.cachedInputPer1k))return null;let s={basis:"verification",requestId:t.requestId,at:Math.floor(t.at),stratum:t.stratum,outcome:t.outcome,requestedModel:t.
1057
+ e)}precioConocido(e,n=this.now()){return this.precioDelCliente(e)??mn(e,n)}precioDelCliente(e){let n=this.config.costModels;if(!n)return;let r=n[e];if(r)return r;let o=e.indexOf("/");if(o>=0){let i=n[e.
1058
+ slice(o+1)];if(i)return i}}precioDocumentado(e){return this.precioDelCliente(e)??Le(e,this.now())}costModelFor(e,n=this.now()){let r=this.precioConocido(e,n);return r||(this.config.defaultCostModel?this.
1059
+ config.defaultCostModel:(this.avisar(`precio-ilustrativo:${e}`,`[bv-sala] no cost model configured for "${e}"; falling back to the ILLUSTRATIVE default price. Dollar figures will not match your bill. \
1060
+ Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),Oa))}};function ip(t,e){if((e.toolCalls?.length??0)>0||!t.schema)return "none";let n=nt(typeof e.text=="string"?e.text:"");return n.ok&&de(
1061
+ n.value,t.schema).valid?"met":"missed"}function nt(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of sp(t))try{return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function sp(t){
1062
+ let e=[],n=/```[ \t]*[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g;for(let r of t.matchAll(n)){let o=r[1]?.trim();o&&e.push(o);}for(let r of ["{","["]){let o=t.indexOf(r);if(o===-1)continue;let i=ap(t,o);i&&
1063
+ e.push(i);}return e}function ap(t,e){let n=t[e],r=n==="{"?"}":"]",o=0,i=false,s=false;for(let a=e;a<t.length;a+=1){let u=t[a];if(i){s?s=false:u==="\\"?s=true:u==='"'&&(i=false);continue}if(u==='"'){i=true;continue}if(u===
1064
+ n)o+=1;else if(u===r&&(o-=1,o===0))return t.slice(e,a+1)}}function cp(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function up(t,e,n=false){if(e===false)return "rejected";if(n)return "bounded_degra\
1065
+ dation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "not_verified"}}function lp(t,e,n){switch(t){case "no-served-tier":return `asked the \
1066
+ provider for the "${e}" tier, and it reported none back: the rate this request was billed at cannot be known, so nothing is credited`;case "unknown-tier":return `asked for "${e}" and the provider report\
1067
+ s serving "${n}", a tier this layer has no published rate for: nothing is credited`;case "standard-rate-tier":return `asked for "${e}" and the provider reports serving "${n}", which bills at the standar\
1068
+ d rate: this request was billed as if it had never been deferred`;case "no-tier-price":return `the provider reports serving "${n}", but there is no published price for the "${n}" tier of this model from\
1069
+ this provider (or it has expired): nothing is credited`;case "no-standard-price":return `the provider reports serving "${n}", but this model has no list price of its own here, so there is no standard r\
1070
+ ate card to price the difference against: nothing is credited`;case "incomplete-usage":return `the provider reports serving "${n}", but its usage for this call is incomplete, so the difference cannot be\
1071
+ priced: nothing is credited`;case "no-difference":return `the provider reports serving "${n}", and this call's usage costs the same at both published rate cards: nothing is credited`}}function nn(t){return Math.
1072
+ round(t*1e6)/1e6}function rt(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function dp(t,e,n,r){if(e)return rt(-t.extraCostUsd);let o=i=>t.actualInput/1e3*i.inputPer1k+t.actualOutput/1e3*i.outputPer1k;
1073
+ return rt(o(r)-o(n))}function pp(t,e){if(!(e>0))return false;if(e>=1)return true;let n=Y(`${t}:cascade-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function Sc(t,e){if(!e.isAgentic||e.allowSemanticCache)
1074
+ return false;let n=t.original;return vn({...t,original:{...n,savings:{...n.savings??{},semanticCache:"include-agentic"}}}).allowSemanticCache}function rn(){return {executionClass:"NO_RETRIEVAL",confidence:1,
1075
+ reason:"n/a (short-circuited)",rounds:0}}function on(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,reason:"no structured payload"}}function ci(t,e="",n=null){
1076
+ if(t==null||typeof t!="object")return "";let r=t,o=[],i=e||"the value",s=h=>typeof r[h]=="number"?r[h]:null,a=s("maxLength"),u=s("minLength"),c=s("maxItems"),l=s("minItems"),d=s("maximum"),f=s("minimum");
1077
+ if(a!=null){let h=n!=null?Math.min(a,n):a;o.push(`${i}<=${h}ch`);}u!=null&&o.push(`${i}>=${u}ch`),c!=null&&o.push(`${i}<=${c} items`),l!=null&&o.push(`${i}>=${l} items`),d!=null&&o.push(`${i}<=${d}`),f!=
1078
+ null&&o.push(`${i}>=${f}`),typeof r.pattern=="string"&&o.push(`${i} matches /${r.pattern}/`);let m=r.properties;if(m&&typeof m=="object")for(let[h,b]of Object.entries(m)){let p=ci(b,e?`${e}.${h}`:h,n);
1079
+ p&&o.push(p);}if(r.items!==void 0){let h=ci(r.items,`${i} entries`,n);h&&o.push(h);}return o.join("; ")}function sn(t){let e=t.response;return e?e.contractId??e.version??JSON.stringify(e.schema??{}).slice(
1080
+ 0,200):""}function fp(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.test(e.message))}function ai(t){return JSON.stringify(
1081
+ {type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function an(t,e){for(let n=t.length-1;n>=0;n--)if(t[n].role===
1082
+ "user"){t.splice(n,0,e);return}t.push(e);}function ui(t,e=false){if(e){let n=0;for(;n<t.length&&t[n].role==="system";)n+=1;return n}for(let n=t.length-1;n>=0;n--)if(t[n].role==="user")return n;return ui(t,
1083
+ true)}function mp(t,e){let n=oi(t,e);return n.cacheReadMultiplier<1?n:null}var Ec=2e3,Rc=200,hp=200,gp=10,bp=1e7,vp=5,yp=48*3600*1e3,li=/^[A-Za-z0-9._:/-]{1,128}$/,Rt=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,cn=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=
1084
+ 1e3;function kp(t,e={}){if(!li.test(t.requestId)||!li.test(t.requestedModel)||!li.test(t.servedModel)||typeof t.at!="number"||!Number.isFinite(t.at)||t.at<1e12)return null;let n=typeof e?.ahora=="numb\
1085
+ er"?e.ahora:Date.now();if(t.at>n+yp)return null;let r=t.optimized;if(!cn(r.cost)||!Rt(r.inputTokens)||!Rt(r.cachedInputTokens)||!Rt(r.outputTokens))return null;let o=t.prices;if(!cn(o.inputPer1k)||!cn(
1086
+ o.outputPer1k)||o.cachedInputPer1k!==void 0&&!cn(o.cachedInputPer1k))return null;let i={basis:"verification",requestId:t.requestId,at:Math.floor(t.at),stratum:t.stratum,outcome:t.outcome,requestedModel:t.
962
1087
  requestedModel,servedModel:t.servedModel,cacheResult:t.cacheResult,optimizedCost:r.cost,optimizedInputTokens:r.inputTokens,optimizedCachedInputTokens:Math.min(r.cachedInputTokens,r.inputTokens),optimizedOutputTokens:r.
963
- outputTokens,inputPer1k:o.inputPer1k,...o.cachedInputPer1k!==void 0?{cachedInputPer1k:o.cachedInputPer1k}:{},outputPer1k:o.outputPer1k};if(t.outcome==="paired"){let i=t.naive;if(!i||!Ot(i.cost)||!rt(i.
964
- inputTokens)||!rt(i.cachedInputTokens)||!rt(i.outputTokens)||i.cachedInputTokens>i.inputTokens)return null;if(s.naiveCost=i.cost,s.naiveInputTokens=i.inputTokens,s.naiveCachedInputTokens=i.cachedInputTokens,
965
- s.naiveOutputTokens=i.outputTokens,i.finishReason!==void 0){if(!/^[a-z_]{1,32}$/.test(i.finishReason))return null;s.naiveFinishReason=i.finishReason;}s.naiveContract=i.contract;}return s}var Fn=class{o;flushIntervalMs;pendientes=[];conteos=new Map;reintentos=[];inflight=null;timer;fallosSeguidos=0;ultimoFallo=Number.
966
- NEGATIVE_INFINITY;constructor(e){this.o=e,this.flushIntervalMs=e.flushIntervalMs??15e3;}ahora(){return (this.o.now??Date.now)()}encolar(e){let n;try{n=Pl(e,{ahora:this.ahora()});}catch{n=null;}n&&(this.pendientes.
967
- push(n),this.pendientes.length>la&&this.pendientes.splice(0,this.pendientes.length-la),this.pendientes.length>=da&&this.flushSiToca());}flushSiToca(){return this.reintentos.length>0&&this.ahora()-this.
1088
+ outputTokens,inputPer1k:o.inputPer1k,...o.cachedInputPer1k!==void 0?{cachedInputPer1k:o.cachedInputPer1k}:{},outputPer1k:o.outputPer1k};if(t.outcome==="paired"){let s=t.naive;if(!s||!cn(s.cost)||!Rt(s.
1089
+ inputTokens)||!Rt(s.cachedInputTokens)||!Rt(s.outputTokens)||s.cachedInputTokens>s.inputTokens)return null;if(i.naiveCost=s.cost,i.naiveInputTokens=s.inputTokens,i.naiveCachedInputTokens=s.cachedInputTokens,
1090
+ i.naiveOutputTokens=s.outputTokens,s.finishReason!==void 0){if(!/^[a-z_]{1,32}$/.test(s.finishReason))return null;i.naiveFinishReason=s.finishReason;}i.naiveContract=s.contract;}return i}var br=class{o;flushIntervalMs;pendientes=[];conteos=new Map;reintentos=[];inflight=null;timer;fallosSeguidos=0;ultimoFallo=Number.
1091
+ NEGATIVE_INFINITY;constructor(e){this.o=e,this.flushIntervalMs=e.flushIntervalMs??15e3;}ahora(){return (this.o.now??Date.now)()}encolar(e){let n;try{n=kp(e,{ahora:this.ahora()});}catch{n=null;}n&&(this.pendientes.
1092
+ push(n),this.pendientes.length>Ec&&this.pendientes.splice(0,this.pendientes.length-Ec),this.pendientes.length>=Rc&&this.flushSiToca());}flushSiToca(){return this.reintentos.length>0&&this.ahora()-this.
968
1093
  ultimoFallo<this.flushIntervalMs?Promise.resolve():this.flush()}contar(e,n){let r=`${e}|${n}`;this.conteos.set(r,(this.conteos.get(r)??0)+1);}start(){this.timer||(this.timer=setInterval(()=>{this.flush();},
969
1094
  this.flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async flush(){if(this.inflight)return this.inflight;this.inflight=this.hacerFlush();
970
1095
  try{await this.inflight;}finally{this.inflight=null;}}hayAlgo(){return this.reintentos.length>0||this.pendientes.length>0||this.conteos.size>0}siguienteSobre(){let e=this.reintentos.shift();if(e)return e;
971
- if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,da),r=[];for(let[o,s]of this.conteos){if(r.length>=El)break;let[i="",a=""]=o.split("|"),c=Math.min(s,Cl);
972
- r.push({day:i,category:a,requests:c}),s>c?this.conteos.set(o,s-c):this.conteos.delete(o);}return {batchId:(this.o.randomId??dt)(),samples:n,counts:r}}async hacerFlush(){let e=this.o.fetchImpl??globalThis.
973
- fetch;if(e)for(let n=0;n<Il&&this.hayAlgo();n++){let r=this.siguienteSobre();if(!r||!await this.enviar(e,r))return}}async enviar(e,n){try{let r=await e(this.o.url,{method:"POST",headers:{authorization:`\
974
- Bearer ${this.o.serviceAccountKey}`,"content-type":"application/json",[zt]:`sdk/${lt}`},body:JSON.stringify(n)});return r.ok?(this.fallosSeguidos=0,!0):r.status>=500?(this.fallosSeguidos++,this.ultimoFallo=
975
- this.ahora(),this.reencolar(n),this.avisarDeFallo(`the server responded ${r.status}`),!1):r.status===401||r.status===403?(this.o.silenceWarnings||F(`verification-auth-${r.status}`,`[bvsala] verificati\
1096
+ if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,Rc),r=[];for(let[o,i]of this.conteos){if(r.length>=hp)break;let[s="",a=""]=o.split("|"),u=Math.min(i,bp);
1097
+ r.push({day:s,category:a,requests:u}),i>u?this.conteos.set(o,i-u):this.conteos.delete(o);}return {batchId:(this.o.randomId??jt)(),samples:n,counts:r}}async hacerFlush(){let e=this.o.fetchImpl??globalThis.
1098
+ fetch;if(e)for(let n=0;n<vp&&this.hayAlgo();n++){let r=this.siguienteSobre();if(!r||!await this.enviar(e,r))return}}async enviar(e,n){try{let r=await e(this.o.url,{method:"POST",headers:{authorization:`\
1099
+ Bearer ${this.o.serviceAccountKey}`,"content-type":"application/json",[hn]:`sdk/${Se}`},body:JSON.stringify(n)});return r.ok?(this.fallosSeguidos=0,!0):r.status>=500?(this.fallosSeguidos++,this.ultimoFallo=
1100
+ this.ahora(),this.reencolar(n),this.avisarDeFallo(`the server responded ${r.status}`),!1):r.status===401||r.status===403?(this.o.silenceWarnings||V(`verification-auth-${r.status}`,`[bvsala] verificati\
976
1101
  on reporting is being rejected with HTTP ${r.status} at ${this.o.url}. Check \`serviceAccountKey\`. Pairs are not reaching your dashboard; your requests and your usage reporting are not affected.`),!1):
977
1102
  (this.fallosSeguidos++,this.avisarDeFallo(r.status===404||r.status===405?`HTTP ${r.status}: the reporting URL looks wrong, or the server does not have this feature yet`:`the server rejected the batch \
978
1103
  with HTTP ${r.status}`),!1)}catch(r){return this.fallosSeguidos++,this.ultimoFallo=this.ahora(),this.reencolar(n),this.avisarDeFallo(r instanceof Error?r.message:"network error"),false}}reencolar(e){for(this.
979
- reintentos.unshift(e);this.reintentos.length>Rl;)this.reintentos.pop();}avisarDeFallo(e){if(this.o.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.warn(`[bvsala] verificatio\
1104
+ reintentos.unshift(e);this.reintentos.length>gp;)this.reintentos.pop();}avisarDeFallo(e){if(this.o.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.warn(`[bvsala] verificatio\
980
1105
  n reporting has failed ${n} times in a row against ${this.o.url} (${e}). Your requests and usage reporting keep working; the pairs are not arriving.`);}get estado(){return {pendientes:this.pendientes.length,
981
- conteos:this.conteos.size,reintentos:this.reintentos.length}}};var Dl=72*3600,Ol,pa=new Set(Object.values($t).flatMap(t=>t.flatMap(e=>[e,`openai/${e}`]))),fa="[bvsala] `gpt-tokenizer` is not installed, so token counts for OpenAI models are ESTIMATED with a built-\
1106
+ conteos:this.conteos.size,reintentos:this.reintentos.length}}};var xp=72*3600,wp,Cc=new Set(Object.values(gn).flatMap(t=>t.flatMap(e=>[e,`openai/${e}`]))),Ic="[bvsala] `gpt-tokenizer` is not installed, so token counts for OpenAI models are ESTIMATED with a built-\
982
1107
  in heuristic and the reconstructed savings are less accurate. Savings where the layer removed something are reported as `estimated` either way, and estimated savings are never billed. Install it once \
983
- (`npm i gpt-tokenizer`) and the SDK loads it automatically.";function Yh(t){t.licenseGate&&(console.warn("[bvsala] Ignoring the injected `licenseGate`: in the published package a license is only accep\
984
- ted as a `licenseKey` verified against BiVelio's embedded public key. Get yours at https://savings.bivelio.com/dashboard/install"),t={...t,licenseGate:void 0});let n={...t,tokenizer:t.tokenizer??Kn},r=t.
985
- tokenizer==null&&t.exactTokenizer!==false?Ol??=Wn(Kn).catch(()=>false):Promise.resolve(true),o,s;if(t.licenseKey&&!t.licenseGate){let m=pi;if(t.licenseServerUrl){let f=new Qe,h=v=>Tn(v,
986
- m,{revocation:f,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??Dl}),g=h(t.licenseKey);n.licenseGate={isEntitled:v=>g.isEntitled(v),isActive:()=>g.isActive(),status:()=>g.
987
- status(),reason:()=>g.reason()};let p=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;o=new En({url:p,publicKeyPem:m,snapshot:f,getRefreshAfter:()=>g.refreshAfter?.(),...t.now?{nowSeconds:()=>Math.
1108
+ (`npm i gpt-tokenizer`) and the SDK loads it automatically.";function Cb(t){t.licenseGate&&(console.warn("[bvsala] Ignoring the injected `licenseGate`: in the published package a license is only accep\
1109
+ ted as a `licenseKey` verified against BiVelio's embedded public key. Get yours at https://savings.bivelio.com/dashboard/install"),t={...t,licenseGate:void 0});let n={...t,tokenizer:t.tokenizer??Mr},r=t.
1110
+ tokenizer==null&&t.exactTokenizer!==false?wp??=Nr(Mr).catch(()=>false):Promise.resolve(true),o,i;if(t.licenseKey&&!t.licenseGate){let f=Ta;if(t.licenseServerUrl){let m=new wt,h=v=>rr(v,
1111
+ f,{revocation:m,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??xp}),b=h(t.licenseKey);n.licenseGate={isEntitled:v=>b.isEntitled(v),isActive:()=>b.isActive(),status:()=>b.
1112
+ status(),reason:()=>b.reason()};let p=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;o=new or({url:p,publicKeyPem:f,snapshot:m,getRefreshAfter:()=>b.refreshAfter?.(),...t.now?{nowSeconds:()=>Math.
988
1113
  floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.licensePollIntervalSeconds}:{},...t.silenceWarnings!=null?{silenceWarnings:t.
989
- silenceWarnings}:{},...t.licenseRevocation??{}}),o.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(s=new Cn({url:`${t.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,serviceAccountKey:t.
990
- serviceAccountKey,publicKey:m,initialToken:t.licenseKey,revocados:f,onNewToken:v=>{g=h(v);},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?
991
- {pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),s.start());}else n.licenseGate=vi(t.licenseKey,m,t.now);}let i=Ln(
992
- t.verification),a=(m,f)=>{t.silenceWarnings!==true&&F(m,f);};!i.activo&&i.motivo==="invalido"&&a("verificacion-invalida",Xi(t.verification));let c,u;if(i.activo){let m;if(t.serviceAccountKey&&t.metering?.
993
- enabled!==false)if(t.meteringUrl){let f=/^(.*)\/api\/metering\/usage\/?$/.exec(t.meteringUrl);f&&(m=`${f[1]}/api/metering/verification`);}else t.licenseServerUrl&&(m=`${t.licenseServerUrl.replace(/\/+$/,"")}\
994
- /api/metering/verification`);if(!m&&!i.onCheck)a("verificacion-sin-destino",Qi);else {m&&t.serviceAccountKey&&(c=new Fn({url:m,serviceAccountKey:t.serviceAccountKey,...t.meteringFetch?{fetchImpl:t.meteringFetch}:
1114
+ silenceWarnings}:{},...t.licenseRevocation??{}}),o.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(i=new sr({url:`${t.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,serviceAccountKey:t.
1115
+ serviceAccountKey,publicKey:f,initialToken:t.licenseKey,revocados:m,onNewToken:v=>{b=h(v);},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?
1116
+ {pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),i.start());}else n.licenseGate=_a(t.licenseKey,f,t.now);}let s=mr(
1117
+ t.verification),a=(f,m)=>{t.silenceWarnings!==true&&V(f,m);};!s.activo&&s.motivo==="invalido"&&a("verificacion-invalida",pc(t.verification));let u,c;if(s.activo){let f;if(t.serviceAccountKey&&t.metering?.
1118
+ enabled!==false)if(t.meteringUrl){let m=/^(.*)\/api\/metering\/usage\/?$/.exec(t.meteringUrl);m&&(f=`${m[1]}/api/metering/verification`);}else t.licenseServerUrl&&(f=`${t.licenseServerUrl.replace(/\/+$/,"")}\
1119
+ /api/metering/verification`);if(!f&&!s.onCheck)a("verificacion-sin-destino",fc);else {f&&t.serviceAccountKey&&(u=new br({url:f,serviceAccountKey:t.serviceAccountKey,...t.meteringFetch?{fetchImpl:t.meteringFetch}:
995
1120
  t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.silenceWarnings!=null?{silenceWarnings:t.
996
- silenceWarnings}:{}}),c.start());let f=c;u={encolar:h=>f?.encolar(h),...f?{contar:(h,g)=>f.contar(h,g)}:{},enReposo:()=>f?.flushSiToca()},a(`verificacion-activa:${i.tasa}`,Zi(i.tasa));}}let l=new jn(n,
997
- u?{verificacion:u}:{}),d;if(t.serviceAccountKey&&t.metering?.enabled!==false){let m=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/usage`:void 0);if(!m&&t.silenceWarnings!==
1121
+ silenceWarnings}:{}}),u.start());let m=u;c={encolar:h=>m?.encolar(h),...m?{contar:(h,b)=>m.contar(h,b)}:{},enReposo:()=>m?.flushSiToca()},a(`verificacion-activa:${s.tasa}`,dc(s.tasa));}}let l=new gr(n,
1122
+ c?{verificacion:c}:{}),d;if(t.serviceAccountKey&&t.metering?.enabled!==false){let f=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/usage`:void 0);if(!f&&t.silenceWarnings!==
998
1123
  true&&console.warn('[bvsala] `serviceAccountKey` is set but there is no `licenseServerUrl` (or `meteringUrl`): seat metering and automatic license renewal are OFF, so nothing will reach your dashboard a\
999
- nd a renewed license will not be picked up. Add `licenseServerUrl: "https://savings.bivelio.com"` \u2014 or drop `serviceAccountKey` for a zero-network deployment.'),m){d=new Tt({url:m,serviceAccountKey:t.
1124
+ nd a renewed license will not be picked up. Add `licenseServerUrl: "https://savings.bivelio.com"` \u2014 or drop `serviceAccountKey` for a zero-network deployment.'),f){d=new Qt({url:f,serviceAccountKey:t.
1000
1125
  serviceAccountKey,surface:"sdk",...t.metering?.orgId?{orgId:t.metering.orgId}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.metering?.maxBatch!=null?{maxBatch:t.
1001
1126
  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}:
1002
- {},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let f=t.metering?.ci??Hr();if(t.metering?.seatId)d.setSeat(t.metering.seatId,f);else {
1003
- let h=d;Kr(t.serviceAccountKey).then(g=>h.setSeat(g,f)).catch(()=>{});}d.start();}}return {generate:async m=>{let f=await r,h=await l.generate(m);if(!f&&t.silenceWarnings!==true&&pa.has(m.model)&&F("tokeni\
1004
- zador-exacto-ausente",fa),d)try{d.record(h.report);}catch{}return h},generateStream:(m,f)=>{let h=l.generateStream(m,f??{},r);return h.result.then(async g=>{if(d)try{d.record(g.report);}catch{}!await r&&
1005
- t.silenceWarnings!==true&&pa.has(m.model)&&F("tokenizador-exacto-ausente",fa);},()=>{}),h},close:()=>{l.cerrarVerificacion(),c?.stop(),o?.stop(),s?.stop(),d?.stop();}}}/*! Bundled license information:
1127
+ {},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let m=t.metering?.ci??zo();if(t.metering?.seatId)d.setSeat(t.metering.seatId,m);else {
1128
+ let h=d;Vo(t.serviceAccountKey).then(b=>h.setSeat(b,m)).catch(()=>{});}d.start();}}return {generate:async f=>{let m=await r,h=await l.generate(f);if(!m&&t.silenceWarnings!==true&&Cc.has(f.model)&&V("tokeni\
1129
+ zador-exacto-ausente",Ic),d)try{d.record(h.report);}catch{}return h},generateStream:(f,m)=>{let h=l.generateStream(f,m??{},r);return h.result.then(async b=>{if(d)try{d.record(b.report);}catch{}!await r&&
1130
+ t.silenceWarnings!==true&&Cc.has(f.model)&&V("tokenizador-exacto-ausente",Ic);},()=>{}),h},close:()=>{l.cerrarVerificacion(),u?.stop(),o?.stop(),i?.stop(),d?.stop();}}}function di(t){if(!Number.isFinite(t))throw new TypeError(`[bvsala] cannot write a non-finite number (${String(t)}) as a decimal`);if(Math.abs(t)>=1e21)return BigInt(Math.round(t)).toString();let e=t.
1131
+ toFixed(10).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return e==="-0"?"0":e}function Pc(t,e){if(t==null)return "";if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`[bvsala] toCsv: \
1132
+ column "${e}" holds a non-finite number`);return di(t)}if(typeof t=="boolean")return t?"true":"false";if(typeof t!="string")throw new TypeError(`[bvsala] toCsv: column "${e}" holds a ${typeof t}; writ\
1133
+ e strings, numbers, booleans or null (flatten objects such as a series row's \`dimensions\` into their own columns first)`);let n=t;return n===""||/[",\r\n]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}function Sp(t,e){
1134
+ let n;if(e?.columns)n=e.columns;else {if(t.length===0)return "";let o=new Set;for(let i of t)for(let s of Object.keys(i))o.add(s);n=[...o];}let r=[n.map(o=>Pc(o,o)).join(",")];for(let o of t)r.push(n.map(
1135
+ i=>Pc(o[i],i)).join(","));return r.map(o=>`${o}\r
1136
+ `).join("")}var _c={openai:{otel:"openai",nombre:"OpenAI"},anthropic:{otel:"anthropic",nombre:"Anthropic"},google:{otel:"gcp.gen_ai",nombre:"Google"},mistral:{otel:"mistral_ai",nombre:"Mistral AI"},deepseek:{otel:"\
1137
+ deepseek",nombre:"DeepSeek"},groq:{otel:"groq",nombre:"Groq"},xai:{otel:"x_ai",nombre:"xAI"},cohere:{otel:"cohere",nombre:"Cohere"},perplexity:{otel:"perplexity",nombre:"Perplexity"}};function Dc(t){let e=t.
1138
+ indexOf("/");return e>0?t.slice(0,e):void 0}function pi(t){let e=Dc(t)?.toLowerCase();return e!==void 0&&Object.hasOwn(_c,e)?_c[e]:void 0}function Oc(t){return pi(t)?.otel??Dc(t)}function Ac(t){return pi(
1139
+ t)?.nombre}function ot(t){return pi(t)?t.slice(t.indexOf("/")+1):t}var Q={operacion:"gen_ai.operation.name",proveedor:"gen_ai.provider.name",modeloPedido:"gen_ai.request.model",temperatura:"gen_ai.request.temperature",semilla:"gen_ai.request.seed",maxTokens:"gen_ai.r\
1140
+ equest.max_tokens",stream:"gen_ai.request.stream",conversacion:"gen_ai.conversation.id",modeloRespuesta:"gen_ai.response.model",motivosDeFin:"gen_ai.response.finish_reasons",primerTrozo:"gen_ai.respon\
1141
+ se.time_to_first_chunk",entrada:"gen_ai.usage.input_tokens",salida:"gen_ai.usage.output_tokens",lecturaDeCache:"gen_ai.usage.cache_read.input_tokens"},Mc="error.type",j="com.bivelio.",Lc=`${j}stream.r\
1142
+ equest_sent`;function _e(t){return t==="measured"||t==="reference"||t==="estimated"}function Ct(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Nc(t){return Ct(t.cost.baselineEstimate-t.cost.
1143
+ actual)}function N(t,e,n){(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))&&(t[e]=n);}function fi(t,e){let{cost:n,tokens:r,calls:o,cache:i}=t,s={bivelio_request_id:t.requestId,
1144
+ bivelio_basis:n.basis,bivelio_currency:e};_e(n.basis)&&(s.bivelio_baseline_cost=n.baselineEstimate,s.bivelio_actual_cost=n.actual,s[`bivelio_saved_${n.basis}`]=Nc(t),s.bivelio_net_savings_ratio=n.netSavings),
1145
+ s.bivelio_avoided_calls=o.avoidedLlm,s.bivelio_eliminated_input_tokens=r.eliminatedInput,s.bivelio_compressed_input_tokens=r.compressedInput,r.providerCachedInput!==void 0&&(s.bivelio_provider_cached_input_tokens=
1146
+ r.providerCachedInput),s.bivelio_cache_result=i.result,t.qualityStatus!==void 0&&(s.bivelio_quality_status=t.qualityStatus);for(let[a,u]of Object.entries(s))typeof u=="number"&&!Number.isFinite(u)&&delete s[a];
1147
+ return s}function mi(t){let e={};return N(e,Q.modeloRespuesta,ot(t.model)),_e(t.cost.basis)&&(N(e,Q.entrada,t.tokens.actualInput),N(e,Q.salida,t.tokens.actualOutput),t.tokens.providerCachedInput!==void 0&&
1148
+ N(e,Q.lecturaDeCache,t.tokens.providerCachedInput)),e}function vr(t,e){let n=e?.currency??"USD",{cost:r,tokens:o,calls:i,cache:s}=t,a={};N(a,`${j}request_id`,t.requestId),N(a,`${j}sdk.version`,Se),N(a,
1149
+ `${j}model.id`,t.model),N(a,`${j}model.requested_id`,t.modelCascade?.requestedModel),N(a,`${j}cost.basis`,r.basis),N(a,`${j}cost.currency`,n),_e(r.basis)&&(N(a,`${j}cost.baseline`,r.baselineEstimate),
1150
+ N(a,`${j}cost.actual`,r.actual),N(a,`${j}cost.saved.${r.basis}`,Nc(t)),N(a,`${j}cost.net_savings_ratio`,r.netSavings),N(a,`${j}cost.eliminated_input_floor`,r.eliminatedInputFloorCost)),N(a,`${j}calls.\
1151
+ baseline`,i.baselineLlm),N(a,`${j}calls.actual`,i.actualLlm),N(a,`${j}calls.avoided`,i.avoidedLlm),N(a,`${j}calls.retries`,i.retries),N(a,`${j}tokens.baseline_input`,o.baselineInput),N(a,`${j}tokens.a\
1152
+ ctual_input`,o.actualInput),N(a,`${j}tokens.eliminated_input`,o.eliminatedInput),N(a,`${j}tokens.compressed_input`,o.compressedInput),N(a,`${j}tokens.provider_cached_input`,o.providerCachedInput),N(a,
1153
+ `${j}tokens.baseline_output`,o.baselineOutput),N(a,`${j}tokens.actual_output`,o.actualOutput),N(a,`${j}tokens.eliminated_output`,o.eliminatedOutput),N(a,`${j}cache.result`,s.result),N(a,`${j}cache.ref\
1154
+ erence_request_id`,s.reference?.requestId),N(a,`${j}cache.reference_rejected`,s.referenceRejected),N(a,`${j}quality.status`,t.qualityStatus),N(a,`${j}latency.preprocessing_ms`,t.latencyMs?.preprocessing),
1155
+ N(a,`${j}latency.provider_ms`,t.latencyMs?.provider);let c=e?.langfuse?.metadata||e?.datadog?.metadata?fi(t,n):void 0;if(c&&e?.langfuse?.metadata)for(let[l,d]of Object.entries(c))a[`langfuse.observati\
1156
+ on.metadata.${l}`]=typeof d=="number"?di(d):d;if(e?.langfuse?.cost&&n==="USD"&&_e(r.basis)&&Number.isFinite(r.actual)&&(a["langfuse.observation.cost_details"]=JSON.stringify({total:r.actual})),c&&e?.datadog?.
1157
+ metadata){let l={};for(let[d,f]of Object.entries(c))l[d.replace(/^bivelio_/,"")]=f;a["_dd.ml_obs.metadata"]=JSON.stringify({bivelio:l});}return a}var Tp=2,Ep=2,Rp="@bivelio/savings-layer";function Cp(t,e,n){try{if(t.isRecording?.()===!1)return;let r=vr(e,n);n?.genAi&&Object.assign(r,mi(e)),t.setAttributes(r);}catch{}}function hi(t){return typeof t==
1158
+ "function"}function Ip(t){let e=t;if(e&&hi(e.startActiveSpan))return e;if(e&&hi(e.getTracer)){let n=e.getTracer(Rp,Se);if(n&&hi(n.startActiveSpan))return n}throw new TypeError("[bvsala] instrumentSavi\
1159
+ ngsLayer: `tracer` must be an OpenTelemetry Tracer, a TracerProvider or the `trace` object of the OpenTelemetry API")}function Pp(t){let e=t?.name;return typeof e=="string"&&/^[A-Za-z_$][\w$.-]{0,127}$/.
1160
+ test(e)?e:"_OTHER"}function _p(t,e,n){let r={[Q.operacion]:"chat"},o=n??Oc(t.model);typeof o=="string"&&o!==""&&(r[Q.proveedor]=o),r[Q.modeloPedido]=ot(t.model);let i=(a,u)=>{typeof u=="number"&&Number.
1161
+ isFinite(u)&&(r[a]=u);};i(Q.temperatura,t.temperature),i(Q.semilla,t.seed),i(Q.maxTokens,t.response?.maxOutputTokens),e&&(r[Q.stream]=true);let s=t.context?.sessionId;return typeof s=="string"&&s!==""&&(r[Q.
1162
+ conversacion]=s),r}function jc(t,e,n){try{if(t.isRecording?.()!==!1){let r=e.report,o={...mi(r),...vr(r,n)};typeof e.finishReason=="string"&&e.finishReason!==""&&(o[Q.motivosDeFin]=[e.finishReason]);let i=r.
1163
+ streaming;i?.delivery==="live"&&typeof i.firstEventMs=="number"&&Number.isFinite(i.firstEventMs)&&(o[Q.primerTrozo]=i.firstEventMs/1e3),t.setAttributes(o);}}catch{}finally{try{t.end();}catch{}}}function gi(t,e){
1164
+ try{if(t.isRecording?.()!==!1){let n={[Mc]:Pp(e)};e instanceof pe&&(n[Lc]=e.requestSent),t.setAttributes(n),t.setStatus?.({code:Ep});}}catch{}finally{try{t.end();}catch{}}}function Dp(t,e){let n=Ip(e?.tracer);
1165
+ if(e.currency!==void 0&&!/^[A-Z]{3}$/.test(e.currency))throw new TypeError(`[bvsala] instrumentSavingsLayer: currency must be an ISO 4217 code such as "USD" (got "${e.currency}")`);let r={...e.currency!==
1166
+ void 0?{currency:e.currency}:{},...e.langfuse?{langfuse:e.langfuse}:{},...e.datadog?{datadog:e.datadog}:{}},o=e.providerName;function i(s,a,u,c){let l,d,f=false,m;try{m=_p(s,a,o);}catch{m=void 0;}let h=`ch\
1167
+ at ${Op(s)}`;try{n.startActiveSpan(h,{kind:Tp,...m?{attributes:m}:{}},b=>{if(l)return l.valor;if(d)throw d.error;if(f){try{b.end();}catch{}return}let p;try{p=u();}catch(v){throw d={error:v},gi(b,v),v}try{
1168
+ l={valor:c(b,p)};}catch{l={valor:p};try{b.end();}catch{}}return l.valor});}catch{}if(d)throw d.error;return l?l.valor:(f=true,u())}return {generate(s){return i(s,false,()=>t.generate(s),(a,u)=>u.then(c=>(jc(a,
1169
+ c,r),c),c=>{throw gi(a,c),c}))},generateStream(s,a){return i(s,true,()=>t.generateStream(s,a),(u,c)=>(c.result.then(l=>jc(u,l,r),l=>gi(u,l)),c))},close(){t.close();}}}function Op(t){try{return typeof t.model==
1170
+ "string"?ot(t.model):""}catch{return ""}}function Ap(t,e){let n=e?.currency??"USD",r={model:ot(t.model),metadata:fi(t,n)};if(_e(t.cost.basis)){let{actualInput:o,actualOutput:i,providerCachedInput:s}=t.tokens,a={input:Math.max(0,o-(s??0)),output:i};
1171
+ s!==void 0&&(a.cache_read_input_tokens=s),r.usageDetails=a,e?.includeCost&&n==="USD"&&Number.isFinite(t.cost.actual)&&(r.costDetails={total:t.cost.actual});}return r}var $c=["measured","reference","estimated","unmeasured"],bi=36e5,Fc=24*bi;function yr(t,e){if(t===void 0)return "day";if(t==="hour"||t==="day")return t;throw new TypeError(`[bvsala] ${e}: granularity m\
1172
+ ust be "hour" or "day"`)}function kr(t,e){if(t===void 0)return "USD";if(typeof t=="string"&&/^[A-Z]{3}$/.test(t))return t;throw new TypeError(`[bvsala] ${e}: currency must be an ISO 4217 code such as "\
1173
+ USD"`)}function Mp(t,e){let n=t.at,r=Number.NaN;if(n instanceof Date?r=n.getTime():typeof n=="number"?r=n:typeof n=="string"&&n.trim()!==""&&(r=Date.parse(n)),!Number.isFinite(r))throw new TypeError(`\
1174
+ [bvsala] ${e}: invalid "at" for request ${String(t.report?.requestId)}: expected an ISO 8601 string, epoch milliseconds or a valid Date`);return r}function Lp(t,e){let n=e==="hour"?bi:Fc;return Math.floor(
1175
+ t/n)*n}function Np(t,e){return t+(e==="hour"?bi:Fc)}function We(t){return new Date(t).toISOString().replace(/\.\d{3}Z$/,"Z")}function ce(t,e,n,r){if(typeof t=="number"&&Number.isFinite(t))return t;throw new TypeError(
1176
+ `[bvsala] ${r}: report ${n} has no finite number in ${e}`)}function xr(t,e,n,r){let o=new Map;for(let s of t){if(!s||typeof s!="object"||!s.report||typeof s.report!="object")throw new TypeError(`[bvsa\
1177
+ la] ${n}: every record must be { at, report }`);let a=s.report,u=a.cost?.basis;if(u==="shadow")continue;if(!$c.includes(u))throw new TypeError(`[bvsala] ${n}: report ${String(a.requestId)} has an unkn\
1178
+ own cost basis`);let c=u,l=Lp(Mp(s,n),e),{clave:d,extra:f}=r(s,l),m=JSON.stringify([l,a.model,c,d]),h=o.get(m);h||(h={inicio:l,fin:Np(l,e),modelo:a.model,basis:c,clave:d,extra:f,peticiones:0,llamadas:0,
1179
+ evitadas:0,baseline:0,actual:0,ahorro:0,suelo:void 0,tokens:{baselineInput:0,actualInput:0,eliminatedInput:0,compressedInput:0,providerCachedInput:void 0,baselineOutput:0,actualOutput:0,eliminatedOutput:0}},
1180
+ o.set(m,h));let b=String(a.requestId);h.peticiones+=1,h.llamadas+=ce(a.calls?.actualLlm,"calls.actualLlm",b,n),h.evitadas+=ce(a.calls?.avoidedLlm,"calls.avoidedLlm",b,n);let p=a.tokens;if(h.tokens.baselineInput+=
1181
+ ce(p?.baselineInput,"tokens.baselineInput",b,n),h.tokens.actualInput+=ce(p?.actualInput,"tokens.actualInput",b,n),h.tokens.eliminatedInput+=ce(p?.eliminatedInput,"tokens.eliminatedInput",b,n),h.tokens.
1182
+ compressedInput+=ce(p?.compressedInput,"tokens.compressedInput",b,n),h.tokens.baselineOutput+=ce(p?.baselineOutput,"tokens.baselineOutput",b,n),h.tokens.actualOutput+=ce(p?.actualOutput,"tokens.actual\
1183
+ Output",b,n),h.tokens.eliminatedOutput+=ce(p?.eliminatedOutput,"tokens.eliminatedOutput",b,n),p.providerCachedInput!==void 0&&(h.tokens.providerCachedInput=(h.tokens.providerCachedInput??0)+ce(p.providerCachedInput,
1184
+ "tokens.providerCachedInput",b,n)),_e(c)){let v=ce(a.cost.baselineEstimate,"cost.baselineEstimate",b,n),g=ce(a.cost.actual,"cost.actual",b,n);h.baseline+=v,h.actual+=g,h.ahorro+=v-g,a.cost.eliminatedInputFloorCost!==
1185
+ void 0&&(h.suelo=(h.suelo??0)+ce(a.cost.eliminatedInputFloorCost,"cost.eliminatedInputFloorCost",b,n));}}let i=s=>$c.indexOf(s);return [...o.values()].sort((s,a)=>s.inicio-a.inicio||(s.modelo<a.modelo?-1:
1186
+ s.modelo>a.modelo?1:0)||i(s.basis)-i(a.basis)||(s.clave<a.clave?-1:s.clave>a.clave?1:0))}function wr(t){let e=_e(t.basis),n=Ct(t.ahorro);return {baseline:e?Ct(t.baseline):null,actual:e?Ct(t.actual):null,
1187
+ measured:t.basis==="measured"?n:null,reference:t.basis==="reference"?n:null,estimated:t.basis==="estimated"?n:null,suelo:e&&t.suelo!==void 0?Ct(t.suelo):null}}function Sr(t){return JSON.stringify(Object.
1188
+ keys(t).sort().map(e=>[e,t[e]]))}function Tr(t,e,n){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new TypeError(`[bvsala] ${n}: ${e} must return an object of strings`);let r={};for(let[
1189
+ o,i]of Object.entries(t)){if(typeof i!="string")throw new TypeError(`[bvsala] ${n}: ${e} value for "${o}" must be a string`);r[o]=i;}return r}var jp=new Set(["periodStart","periodEnd","date","model","basis","currency","requests","providerCalls","avoidedCalls","baselineCost","actualCost","measuredSavings","referenceSavings","estimatedSavings",
1190
+ "eliminatedInputFloorCost","baselineInputTokens","actualInputTokens","eliminatedInputTokens","compressedInputTokens","providerCachedInputTokens","baselineOutputTokens","actualOutputTokens","eliminated\
1191
+ OutputTokens","dimensions"]),un="toSavingsSeries";function $p(t,e){let n=yr(e?.granularity,un),r=kr(e?.currency,un),o=e?.dimensions;return xr(t,n,un,s=>{let a=o?Tr(o(s),"dimensions",un):{};for(let u of Object.
1192
+ keys(a))if(jp.has(u))throw new TypeError(`[bvsala] ${un}: dimension "${u}" repeats a column of the series`);return {clave:Sr(a),extra:a}}).map(s=>{let a=wr(s),u=We(s.inicio);return {periodStart:u,periodEnd:We(
1193
+ s.fin),date:u.slice(0,10),model:s.modelo,basis:s.basis,currency:r,requests:s.peticiones,providerCalls:s.llamadas,avoidedCalls:s.evitadas,baselineCost:a.baseline,actualCost:a.actual,measuredSavings:a.measured,
1194
+ referenceSavings:a.reference,estimatedSavings:a.estimated,eliminatedInputFloorCost:a.suelo,baselineInputTokens:s.tokens.baselineInput,actualInputTokens:s.tokens.actualInput,eliminatedInputTokens:s.tokens.
1195
+ eliminatedInput,compressedInputTokens:s.tokens.compressedInput,providerCachedInputTokens:s.tokens.providerCachedInput??null,baselineOutputTokens:s.tokens.baselineOutput,actualOutputTokens:s.tokens.actualOutput,
1196
+ eliminatedOutputTokens:s.tokens.eliminatedOutput,dimensions:Object.freeze({...s.extra})}})}var ue="toFocusRows",Fp="BV-SALA savings ledger",Bc="bivelio/";function it(t){return typeof t=="string"&&t.trim()!==""}function vi(t,e,n,r){let o=typeof t=="function"?t(n):t??e;if(it(o))return o;throw new TypeError(
1197
+ `[bvsala] ${ue}: cannot determine the FOCUS ${r} for model "${n}". FOCUS allows no placeholder there: pass it in the options.`)}function Bp(t,e,n){if(!n){let s=new Date(t);return {start:Date.UTC(s.getUTCFullYear(),
1198
+ s.getUTCMonth(),1),end:Date.UTC(s.getUTCFullYear(),s.getUTCMonth()+1,1)}}let r=n(new Date(t)),o=r?.start instanceof Date?r.start.getTime():Number.NaN,i=r?.end instanceof Date?r.end.getTime():Number.NaN;
1199
+ if(!Number.isFinite(o)||!Number.isFinite(i)||o>=i)throw new TypeError(`[bvsala] ${ue}: billingPeriod must return valid Dates with start before end`);if(t<o||e>i)throw new TypeError(`[bvsala] ${ue}: bi\
1200
+ llingPeriod must contain the charge period it is given`);return {start:o,end:i}}function zp(t,e){if(!e||typeof e!="object")throw new TypeError(`[bvsala] ${ue}: options with a billingAccountId are requi\
1201
+ red`);let n=yr(e.granularity,ue),r=kr(e.currency,ue),{billingAccountId:o,billingAccountName:i,subAccount:s,tags:a}=e;if(typeof o!="function"&&!it(o))throw new TypeError(`[bvsala] ${ue}: billingAccount\
1202
+ Id must be a non-empty string or a function`);let u=e.serviceName??Fp;if(!it(u))throw new TypeError(`[bvsala] ${ue}: serviceName must be a non-empty string`);return xr(t,n,ue,l=>{let d=typeof o=="func\
1203
+ tion"?o(l):o;if(!it(d))throw new TypeError(`[bvsala] ${ue}: billingAccountId returned no id for request ${String(l.report.requestId)}`);let f=typeof i=="function"?i(l):i,m=s?s(l):void 0;if(m!==void 0&&
1204
+ (!it(m?.id)||!it(m?.name)))throw new TypeError(`[bvsala] ${ue}: subAccount must return { id, name } as non-empty strings, or undefined`);let h=Tr(a?a(l):void 0,"tags",ue);for(let p of Object.keys(h))if(p.
1205
+ startsWith(Bc))throw new TypeError(`[bvsala] ${ue}: tag "${p}" uses the reserved "${Bc}" prefix`);let b={id:d,nombre:it(f)?f:null,subId:m?m.id:null,subNombre:m?m.name:null,tags:h};return {clave:JSON.stringify(
1206
+ [b.id,b.nombre,b.subId,b.subNombre,Sr(h)]),extra:b}}).map(l=>{let d=l.modelo,f=vi(e.serviceProviderName,Ac(d),d,"ServiceProviderName"),m=vi(e.invoiceIssuerName,f,d,"InvoiceIssuerName"),h=vi(e.hostProviderName,
1207
+ f,d,"HostProviderName"),b=Bp(l.inicio,l.fin,e.billingPeriod),p=wr(l),v=l.extra,g={"bivelio/basis":l.basis,"bivelio/model":d};for(let y of Object.keys(v.tags).sort())g[y]=v.tags[y];return {BilledCost:0,
1208
+ EffectiveCost:0,ListCost:0,ContractedCost:0,BillingCurrency:r,BillingAccountId:v.id,BillingAccountName:v.nombre,BillingPeriodStart:We(b.start),BillingPeriodEnd:We(b.end),ChargePeriodStart:We(l.inicio),
1209
+ ChargePeriodEnd:We(l.fin),ChargeCategory:"Adjustment",ChargeClass:null,ChargeDescription:`BV-SALA savings ledger for ${d} (basis: ${l.basis}). Not a charge: cost columns are 0 by design.`,ChargeFrequency:"\
1210
+ Usage-Based",InvoiceIssuerName:m,ServiceProviderName:f,HostProviderName:h,ServiceName:u,ServiceCategory:"AI and Machine Learning",ServiceSubcategory:"Generative AI",PricingQuantity:null,PricingUnit:null,
1211
+ SubAccountId:v.subId,SubAccountName:v.subNombre,Tags:JSON.stringify(g),x_BiVelioBasis:l.basis,x_BiVelioModelId:d,x_BiVelioRequestCount:l.peticiones,x_BiVelioProviderCallCount:l.llamadas,x_BiVelioAvoidedCallCount:l.
1212
+ evitadas,x_BiVelioBaselineCost:p.baseline,x_BiVelioActualCost:p.actual,x_BiVelioMeasuredSavings:p.measured,x_BiVelioReferenceSavings:p.reference,x_BiVelioEstimatedSavings:p.estimated,x_BiVelioEliminatedInputFloorCost:p.
1213
+ suelo,x_BiVelioBaselineInputTokens:l.tokens.baselineInput,x_BiVelioActualInputTokens:l.tokens.actualInput,x_BiVelioEliminatedInputTokens:l.tokens.eliminatedInput,x_BiVelioCompressedInputTokens:l.tokens.
1214
+ compressedInput,x_BiVelioProviderCachedInputTokens:l.tokens.providerCachedInput??null,x_BiVelioBaselineOutputTokens:l.tokens.baselineOutput,x_BiVelioActualOutputTokens:l.tokens.actualOutput,x_BiVelioEliminatedOutputTokens:l.
1215
+ tokens.eliminatedOutput}})}/*! Bundled license information:
1006
1216
 
1007
1217
  @noble/curves/utils.js:
1008
1218
  @noble/curves/abstract/modular.js:
@@ -1010,4 +1220,4 @@ t.silenceWarnings!==true&&pa.has(m.model)&&F("tokenizador-exacto-ausente",fa);},
1010
1220
  @noble/curves/abstract/edwards.js:
1011
1221
  @noble/curves/ed25519.js:
1012
1222
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
1013
- */export{ps as AnthropicProvider,lt as BV_SALA_VERSION,jt as CATALOGO,dc as COMPACT_ROWS_INSTRUCTION,xi as DEFAULT_COST_MODEL,Dl as DEFAULT_MAX_STALENESS_SECONDS,pi as EMBEDDED_PUBLIC_KEY,Jn as ExactTokenizer,Ht as ExecutionRouter,Yt as FormatSelector,qn as HeuristicEstimator,Ut as InMemoryExactCache,No as InMemorySemanticCache,rr as InMemoryToolSetFreezer,Ce as LicenseError,Gl as MODELOS_POR_CODIFICACION,$t as MODELS_BY_ENCODING,pr as MockProvider,cs as OpenAICompatibleProvider,xa as PRECIOS_AL_DIA,Bl as QUALITY_STATUSES,Ro as REFERENCE_MAX_AGE_MS,Io as REFERENCE_MESSAGE_ALLOWANCE,Co as REFERENCE_OUTPUT_SHARE,nr as ResolverRegistry,En as RevocationPoller,Qe as RevocationSnapshot,He as SavingsLedger,Zt as SchemaRegistry,qt as Singleflight,le as StreamAbortedError,Hn as TokenizerRegistry,Kt as ToolSelector,bt as TraceCollector,Mo as UMBRAL_LOCAL,Tt as UsageEmitter,ec as adaptiveK,qa as arithmeticResolver,Qn as buildExactKey,Do as buildInflightKey,Xn as canonicalize,Ho as compactRowsSerializer,Yo as compresionFiel,fu as computeNextDelay,Ba as cosine,pc as createCompactRowsSerializer,jo as createDefaultResolvers,zl as createHandoff,Sp as createMockProvider,Yh as createSavingsLayer,Jo as csvSerializer,$o as decodeCompactRows,Qa as dedupe,Kn as defaultTokenizerRegistry,Kr as deriveSeatId,qr as deriveStatus,Hr as detectCi,Ao as embebedorLocal,jd as emptyState,cc as encodeCompactRows,Ja as evalArithmetic,er as evaluatePolicy,Fo as executeRetrievalPlan,vi as gateFromKey,qe as heuristicEstimator,cu as isKeyset,Re as isStrictCompatible,zo as jsonCompactSerializer,Va as keyTokensMatch,Vr as licenseKeyShape,Tn as liveGateFromKey,Bd as mergeDelta,Zn as modelFamilyOf,tr as multisetEqual,mt as negationCount,gp as noopCompressor,Ze as normalizeLicenseKey,Vt as normalizeText,pt as numericTokens,Ft as precioDeLista,Fd as projectContext,cp as providerNativeBackend,as as quitarPrefijoDeProveedor,dt as randomId,Wn as registerExactTokenizer,Yl as registrarTokenizadorExacto,nc as renderState,Go as resolveConstraintBackend,ki as resolveDependencies,Df as resolveLicense,G as sha256,lr as shouldCompress,ae as stableStringify,Gt as uniformColumns,ee as validateAgainstSchema,ja as vectorLocal,Ur as verifyCompactSignature,Xe as verifyLicenseToken,bi as verifyRevocationList,hp as withProtectedSpans,ft as words};
1223
+ */export{Cs as AnthropicProvider,Se as BV_SALA_VERSION,Nt as CATALOGO,qu as COMPACT_ROWS_INSTRUCTION,Oa as DEFAULT_COST_MODEL,xp as DEFAULT_MAX_STALENESS_SECONDS,Ta as EMBEDDED_PUBLIC_KEY,Lr as ExactTokenizer,xn as ExecutionRouter,Rn as FormatSelector,Or as HeuristicEstimator,yn as InMemoryExactCache,Fi as InMemorySemanticCache,qr as InMemoryToolSetFreezer,$e as LicenseError,sf as MODELOS_POR_CODIFICACION,gn as MODELS_BY_ENCODING,Qr as MockProvider,ks as OpenAICompatibleProvider,Pr as PRECIOS_AL_DIA,Kp as QUALITY_STATUSES,Pi as REFERENCE_MAX_AGE_MS,Di as REFERENCE_MESSAGE_ALLOWANCE,_i as REFERENCE_OUTPUT_SHARE,Ur as ResolverRegistry,or as RevocationPoller,wt as RevocationSnapshot,dt as SavingsLedger,Cn as SchemaRegistry,kn as Singleflight,pe as StreamAbortedError,Ar as TokenizerRegistry,wn as ToolSelector,Wt as TraceCollector,ji as UMBRAL_LOCAL,Qt as UsageEmitter,Au as adaptiveK,Su as arithmeticResolver,zr as buildExactKey,Mi as buildInflightKey,Br as canonicalize,Gi as compactRowsSerializer,Qi as compresionFiel,ed as computeNextDelay,bu as cosine,Hu as createCompactRowsSerializer,Bi as createDefaultResolvers,Jp as createHandoff,Mm as createMockProvider,Cb as createSavingsLayer,Yi as csvSerializer,qi as decodeCompactRows,Ou as dedupe,Mr as defaultTokenizerRegistry,Vo as deriveSeatId,Bo as deriveStatus,zo as detectCi,Ni as embebedorLocal,Gf as emptyState,zu as encodeCompactRows,Ru as evalArithmetic,vn as evaluatePolicy,Vi as executeRetrievalPlan,_a as gateFromKey,lt as heuristicEstimator,Dp as instrumentSavingsLayer,Jl as isKeyset,je as isStrictCompatible,Ui as jsonCompactSerializer,xu as keyTokensMatch,$o as licenseKeyShape,rr as liveGateFromKey,Jf as mergeDelta,Fr as modelFamilyOf,Vr as multisetEqual,Bt as negationCount,Cm as noopCompressor,kt as normalizeLicenseKey,bn as normalizeText,$t as numericTokens,mn as precioDeLista,Yf as projectContext,ym as providerNativeBackend,bs as quitarPrefijoDeProveedor,jt as randomId,Cp as recordSavingsOnSpan,Nr as registerExactTokenizer,af as registrarTokenizadorExacto,Lu as renderState,Xi as resolveConstraintBackend,Aa as resolveDependencies,rg as resolveLicense,vr as savingsSpanAttributes,Y as sha256,Zr as shouldCompress,ve as stableStringify,Sp as toCsv,zp as toFocusRows,Ap as toLangfuseGeneration,$p as toSavingsSeries,En as uniformColumns,de as validateAgainstSchema,gu as vectorLocal,Fo as verifyCompactSignature,xt as verifyLicenseToken,Pa as verifyRevocationList,Rm as withProtectedSpans,Ft as words};