@bivelio/savings-layer 0.4.21 → 0.4.24

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 oi="2026-09-06",yt={"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 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,
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,288 +6,344 @@ 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},"claude-opus-4-5":{
10
- 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,cachedInputPer1k:5e-4},
11
- "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,outputPer1k:.075,cachedInputPer1k:.0015},
12
- "claude-sonnet-4-5":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-4-6":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-5":{inputPer1k:.002,outputPer1k:.01,
13
- cachedInputPer1k:2e-4},"claude-fable-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-fable-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5-1":{inputPer1k:.01,
14
- outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-sonnet-4":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-haik\
15
- u-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,outputPer1k:.004,cachedInputPer1k:8e-5},
16
- "claude-3-opus":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"claude-3-haiku":{inputPer1k:25e-5,outputPer1k:.00125,cachedInputPer1k:3e-5},"gemini-3.7-flash":{inputPer1k:75e-5,outputPer1k:.00375,
17
- cachedInputPer1k:75e-6},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5},"gemini-3.1-pro-\
18
- preview":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}};
19
- function pn(t,e,n){if(!n)return;let o=t[n];if(o)return o;let r=n.lastIndexOf("/"),s=r>=0?n.slice(r+1):n,i=t[s];if(i)return i;for(let a of e){if(!s.startsWith(a))continue;let c=s.charAt(a.length);if(c!==
20
- ""&&c!=="-"&&c!=="."&&c!=="_")continue;let l=s.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return t[a]}}function fn(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var ri=fn(yt);function xt(t){
21
- return pn(yt,ri,t)}Object.fromEntries(Object.keys(yt).map(t=>[t,t]));var mn="0.4.21",$o="x-bvsala-version";var si=0;function hn(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let o=++si,r=Date.now?Date.now():0;for(let s=0;s<
22
- 16;s++)e[s]=(s<6?o>>>s*8:r>>>(s-6)*8)&255;}e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=[];for(let o=0;o<16;o++)n.push(e[o].toString(16).padStart(2,"0"));return `${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}\
23
- -${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var nl=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function rl(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 gn=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)??[],o=0;for(let r of n){let s=r[0];if(/\s/.test(s)){let i=(r.
24
- match(/\n/g)??[]).length;o+=i+Math.floor(Math.max(0,r.length-1)/2);}else /[A-Za-z]/.test(s)?o+=Math.max(1,Math.ceil(r.length/4)):/\d/.test(s)?o+=Math.max(1,Math.ceil(r.length/2)):o+=1;}return Math.max(o,
25
- Math.ceil(e.length/4))}},Ne=new gn;var bn=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=Ne){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){
26
- 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 o=this.modelToTokenizer.get(e.model);if(o){let r=this.estimators.
27
- get(o);if(r)return r}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},Fo=new bn;var yn=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}},zo={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini",
28
- "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 ii(t,e={}){let n=e.codificaciones??
29
- ["o200k_base","cl100k_base"],o=false;for(let r of n){let s;try{s=await import(`gpt-tokenizer/encoding/${r}`);}catch{continue}if(typeof s.encode=="function"){t.register(new yn(r,s)),o=true;for(let i of zo[r]??
30
- [])t.mapModel(i,r),t.mapModel(`openai/${i}`,r);}}return o}var pl=zo,fl=ii;var je=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;discoveryInput=0;discoveryOutput=0;extraCostUsd=0;cascadeInput=0;cascadeOutput=0;cascadeAttempt(e,n){
31
- 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,o){
32
- let r=Math.max(0,e);this.cacheWriteInputTokens+=r,this.cacheWritePremiumUsd+=r/1e3*o.inputPer1k*Math.max(0,n-1);}compressionReport=void 0;eliminate(e){this.eliminatedInput+=Math.max(0,e);}compress(e,n){
33
- this.compressedInput+=Math.max(0,e-n);}providerCached(e){this.providerCachedInput+=Math.max(0,e);}avoidCall(e,n){this.avoidedLlm+=1,this.actualLlm=0,this.baselineInput=e,this.baselineOutput=n;}get publishedBaselineOutput(){
34
- return this.avoidedLlm===0?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):this.baselineOutput}estimateCost(e){let n=this.avoidedLlm===0,o="estimated";if(n)if(this.actualInput>0&&
35
- this.sentInputLocal>0){let d=this.actualInput/this.sentInputLocal,f=Math.max(0,this.actualInput-this.repairInput-this.discoveryInput);this.baselineInput=f+Math.round(d*this.removedInputLocal),o=this.removedInputLocal===
36
- 0?"measured":"estimated";}else this.actualInput>0?(this.baselineInput=this.actualInput,o="measured"):(this.baselineInput=0,o="unmeasured");let r=n?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):
37
- this.baselineOutput,s=e.cachedInputPer1k??e.inputPer1k,i=Math.min(this.providerCachedInput,this.actualInput),a=d=>Math.max(0,d-i)/1e3*e.inputPer1k+i/1e3*s,c=a(this.baselineInput)+r/1e3*e.outputPer1k,l=a(
38
- this.actualInput)+this.actualOutput/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd,u=c===0?0:1-l/c;return {baselineEstimate:Vo(c),actual:Vo(l),netSavings:ai(u),basis:o}}};function Vo(t){
39
- return Math.round(t*1e10)/1e10}function ai(t){return Math.round(t*1e6)/1e6}var ci=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
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},
11
+ "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,
19
+ 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){
29
+ 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),
37
+ 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
+ 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.
40
+ 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,
40
45
  4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
41
46
  1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,
42
- 1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),li=new TextEncoder;function se(t,e){return t>>>e|t<<32-e}function Uo(t){let e=li.encode(t),n=e.length*
43
- 8,o=(e.length+8>>6)+1,r=new Uint8Array(o*64);r.set(e),r[e.length]=128;let s=new DataView(r.buffer);s.setUint32(r.length-8,Math.floor(n/4294967296)),s.setUint32(r.length-4,n>>>0);let i=new Uint32Array(
44
- [1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let l=0;l<r.length;l+=64){for(let b=0;b<16;b++)a[b]=s.getUint32(l+b*4);for(let b=16;b<
45
- 64;b++){let x=a[b-15],T=a[b-2],E=se(x,7)^se(x,18)^x>>>3,R=se(T,17)^se(T,19)^T>>>10;a[b]=a[b-16]+E+a[b-7]+R|0;}let u=i[0],d=i[1],f=i[2],m=i[3],h=i[4],g=i[5],p=i[6],y=i[7];for(let b=0;b<64;b++){let x=se(
46
- h,6)^se(h,11)^se(h,25),T=h&g^~h&p,E=y+x+T+ci[b]+a[b]|0,R=se(u,2)^se(u,13)^se(u,22),C=u&d^u&f^d&f,D=R+C|0;y=p,p=g,g=h,h=m+E|0,m=f,f=d,d=u,u=E+D|0;}i[0]=i[0]+u|0,i[1]=i[1]+d|0,i[2]=i[2]+f|0,i[3]=i[3]+m|0,
47
- i[4]=i[4]+h|0,i[5]=i[5]+g|0,i[6]=i[6]+p|0,i[7]=i[7]+y|0;}let c="";for(let l=0;l<8;l++)c+=(i[l]>>>0).toString(16).padStart(8,"0");return c}var ui=/\s+/g,di=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],pi=/[¿?¡!;.,:'"·•]/g,fi=/([a-z])\p{M}+/gu,mi=/(^|\s)\p{M}+/gu,
48
- xn=/\p{L}/u;function Y(t){return t>="0"&&t<="9"}function vt(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,o]of di)e=e.replace(n,o);return e=e.normalize("NFD").replace(fi,"$1").replace(mi,"$1").
49
- normalize("NFC"),e=e.replace(pi,(n,o,r)=>{let s=r[o-1]??"",i=r[o+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return Y(s)&&Y(i)?n:"";case "!":return Y(s)?n:"";case ".":case ",":return Y(s)&&Y(i)||
50
- Y(i)&&!Y(s)&&!xn.test(s)?n:"";case ":":return Y(s)&&Y(i)?n:"";case "'":case '"':return xn.test(s)&&xn.test(i)||Y(s)||Y(i)?n:"";default:return Y(s)||Y(i)?n:""}}),e.replace(ui," ").trim()}function ie(t){return Uo(
51
- t)}function Se(t){return JSON.stringify(vn(t))}function vn(t){if(Array.isArray(t))return t.map(vn);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=vn(t[n]);return e}return t}
52
- function kn(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function wn(t){let e=t.context??{},n=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(
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(
53
58
  `
54
- `),o=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${vt(s.content)}`).join(`
55
- `),r=(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:kn(t.model),messages:t.messages,normalizedText:o,
56
- systemPromptHash:ie(n),toolsetHash:ie(Se(r)),structuredDataHash:t.structuredData!==void 0?ie(Se(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.contractId??"none",contractId:t.
57
- response?.contractId??null,temperature:t.temperature??null,seed:t.seed??null,tenantId:e.tenantId??"anonymous",authorizationScope:e.authorizationScope??"default",principal:e.sessionId??null,locale:e.locale??
58
- "und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var qo="n2";function Sn(t,e={}){let n=e.servedModel??t.model,o=Se({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily:kn(n),
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?.
62
+ 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),
59
64
  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,
60
- freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${qo}:${ie(o)}`}function Ho(t,e={}){let n=Se({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,
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,
61
66
  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===
62
- true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:inflight:${qo}:${ie(n)}`}var hi=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\
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\
63
68
  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|\
64
69
  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\
65
70
  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\
66
71
  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\
67
- nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),gi=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nu\
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\
68
73
  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\
69
74
  |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\
70
75
  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\
71
76
  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\
72
- 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 Tn(t){let e=[],n=t.normalizedText,
73
- o=(t.original.tools??[]).some(m=>m.risk==="write"||m.risk==="destructive"),r=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||hi.test(n),s=gi.test(n),i=(t.temperature??0)>.3&&t.seed==null;o&&e.
74
- push("write/destructive tools present"),r&&e.push("freshness-sensitive request"),s&&e.push("personalized/account-scoped request"),i&&e.push("stochastic sampling (temp>0.3, no seed)");let a=r&&(t.freshnessBucket==
75
- null||t.freshnessBucket==="any"),c=t.freshnessBucket==="live",l=s&&t.principal==null,u=!i&&!a&&!c&&!l&&!o;o&&e.push("write/destructive tools \u2192 exact cache off (side effects must execute)"),c&&e.push(
76
- "freshnessBucket=live \u2192 exact cache off (answer must be current)"),a&&e.push("freshness-sensitive without a freshness bucket \u2192 exact cache off"),l&&e.push("personalized request with no princ\
77
- ipal (context.sessionId) \u2192 exact cache off");let d=!o&&!r&&!s&&!i&&t.freshnessBucket!=="day",f=!o&&!r&&!s&&!i&&t.freshnessBucket!=="day";return {allowExactCache:u,allowSemanticCache:d,allowElision:f,
78
- allowSingleflight:!o&&!l,allowCompression:true,requiresFreshData:r,hasSideEffects:o,isPersonalized:s,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var kt=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.
79
- now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),Ko(n.value)):null}async set(e,n,o){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let r=this.store.keys().
80
- next().value;r!==void 0&&this.store.delete(r);}this.store.set(e,{value:Ko(n),expiresAtMs:o!=null?this.now()+o:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};function Ko(t){
81
- try{return structuredClone(t)}catch{return t}}var wt=class{inflight=new Map;waiters=new Map;async run(e,n){let o=this.inflight.get(e);if(o)return this.waiters.set(e,(this.waiters.get(e)??1)+1),{value:await o,coalesced:true};let r=(async()=>n())();this.
82
- inflight.set(e,r),this.waiters.set(e,1);try{return {value:await r,coalesced:!1}}finally{this.inflight.delete(e),this.waiters.delete(e);}}get activeKeys(){return this.inflight.size}};function bi(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 yi(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(
83
- Boolean)}function xi(t){let e=new Array(256).fill(0),n=yi(t);if(n.length===0)return e;let o=new Map;for(let s=0;s<n.length;s++){let i=n[s];if(o.set(i,(o.get(i)??0)+1),s+1<n.length){let a=`${i}\0${n[s+
84
- 1]}`;o.set(a,(o.get(a)??0)+1);}}for(let[s,i]of o){let a=bi(s),c=a%256,l=a>>>31===1?-1:1;e[c]+=l*(1+Math.log(i));}let r=0;for(let s of e)r+=s*s;if(r=Math.sqrt(r),r===0)return e;for(let s=0;s<e.length;s++)
85
- e[s]/=r;return e}function Jo(t){return xi(t)}var Wo=.72;function vi(t,e){if(t.length!==e.length)return 0;let n=t.length,o=0,r=0,s=0;for(let i=0;i<n;i++){let a=t[i],c=e[i];o+=a*c,r+=a*a,s+=c*c;}return r===0||s===0?0:o/(Math.sqrt(r)*Math.sqrt(s))}var ki=new Set(
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.
87
+ 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(
86
92
  ["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\
87
- \xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),wi=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what",
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",
88
94
  "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",
89
95
  "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\
90
96
  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",
91
97
  "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",
92
- "aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function tt(t){return (t.
93
- match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function En(t,e){if(t.length!==e.length)return false;let n=new Map;for(let o of t)n.set(o,(n.get(o)??0)+1);for(let o of e){let r=n.get(o);if(!r)
94
- return false;n.set(o,r-1);}return true}function nt(t){return t.split(/\s+/).filter(Boolean)}function ot(t){return t.filter(e=>ki.has(e.replace(/'/g,""))||e.endsWith("n't")).length}var Si=/^(system|user|assistant|tool):/;
95
- function Go(t){return t.split(`
96
- `).map(e=>{let n=Si.exec(e);return n?{rol:n[1],texto:e.slice(n[0].length)}:{rol:"",texto:e}})}function Ti(t,e){let n=Go(t),o=Go(e);if(n.length!==o.length)return false;for(let r=0;r<n.length;r++)if(n[r].rol!==
97
- o[r].rol||!Ei(n[r].texto,o[r].texto))return false;return true}function Ei(t,e){if(!En(tt(t),tt(e)))return false;let n=nt(t),o=nt(e);if(ot(n)!==ot(o))return false;let r=l=>l.length>1&&!wi.has(l)&&!/^\d/.test(l),s=new Set(
98
- n.filter(r)),i=new Set(o.filter(r));if(s.size===0&&i.size===0)return true;let a=0;for(let l of s)i.has(l)&&a++;let c=s.size+i.size-a;return c===0?true:a/c>=.75}var Yo=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;constructor(e={}){
99
- let n=e.embed==null;this.embed=e.embed??Jo,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??(n?Wo:.9),this.acceptThreshold=e.acceptThreshold??.85,this.ttlMs=e.ttlMs,this.maxRecords=
100
- 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),o=null;for(let r of this.records){if(r.tenantId!==e.tenantId||
101
- r.authorizationScope!==e.authorizationScope||r.principal!==e.principal||r.knowledgeEpoch!==e.knowledgeEpoch||r.contractId!==e.contractId||r.model!==e.model||r.systemPromptHash!==e.systemPromptHash||r.
102
- structuredDataHash!==e.structuredDataHash||r.locale!==e.locale||r.schemaVersion!==e.schemaVersion||r.safetyPolicyVersion!==e.safetyPolicyVersion||this.ttlMs!=null&&this.now()-r.storedAtMs>this.ttlMs)continue;
103
- let s=vi(n,r.embedding);if(s<this.similarityThreshold||!Ti(e.normalizedText,r.query))continue;let i=this.verify?await this.verify(e.normalizedText,r.query):s,a=Math.min(s,i);a<this.acceptThreshold||(!o||
104
- a>o.confidence)&&(o={record:r,similarity:s,verifierScore:i,confidence:a,ageMs:this.now()-r.storedAtMs});}return o}async store(e,n){let o=await this.embed(e.normalizedText);this.records.length>=this.maxRecords&&
105
- this.records.shift(),this.records.push({embedding:o,query:e.normalizedText,answer:n,tenantId:e.tenantId,authorizationScope:e.authorizationScope,principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.
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.
106
112
  contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.structuredDataHash,locale:e.locale,schemaVersion:e.schemaVersion,safetyPolicyVersion:e.safetyPolicyVersion,storedAtMs:this.
107
- now()});}invalidateEpoch(e){let n=0;for(let o=this.records.length-1;o>=0;o--)this.records[o].knowledgeEpoch===e&&(this.records.splice(o,1),n++);return n}get size(){return this.records.length}};var Rn=class{resolvers=[];register(e){return this.resolvers.push(e),this}try(e){for(let n of this.resolvers)try{let o=n.try(e);if(o)return o}catch{}return null}get size(){return this.resolvers.length}},
108
- Ri={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]??Ci(t.normalizedText))?.trim();if(!n)return null;
109
- let o=Oi(n);return o===null||!Number.isFinite(o)?null:{text:Ii(o),data:{value:o},resolver:"arithmetic"}}};function Ci(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function Ii(t){
110
- return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function Oi(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],o=[],r={"+":1,"-":1,
111
- "*":2,"/":2,"%":2},s=a=>{let c=n.pop(),l=n.pop();if(l===void 0||c===void 0)return false;switch(a){case "+":return n.push(l+c),true;case "-":return n.push(l-c),true;case "*":return n.push(l*c),true;case "/":return c===
112
- 0?false:(n.push(l/c),true);case "%":return c===0?false:(n.push(l%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==="(")o.push(a),i=true;else if(a===")"){for(;o.length&&
113
- o[o.length-1]!=="(";)if(!s(o.pop()))return null;if(o.pop()!=="(")return null;i=false;}else {if(i)return null;for(;o.length&&o[o.length-1]!=="("&&r[o[o.length-1]]>=r[a];)if(!s(o.pop()))return null;o.push(a),
114
- i=true;}for(;o.length;){let a=o.pop();if(a==="("||!s(a))return null}return n.length===1?n[0]:null}function Zo(){return new Rn().register(Ri)}var _i=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,Xo=/\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,
115
- Ai=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,St=class{classifier;maxRounds;constructor(e={}){this.
116
- classifier=e.classifier,this.maxRounds=e.maxRounds??2;}classify(e){let n=e.original.retrieval?.mode,o=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.
117
- test(o))return me("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return me("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(Ai.test(o)&&!Xo.test(o))return me("NO_RETRIEVAL",
118
- .8,"self-contained transformation",0);let s=this.classifier?.classify(o);return s&&s.confidence>=.75?me(s.executionClass,s.confidence,"local classifier",Di(s.executionClass,this.maxRounds)):n==="singl\
119
- e"?me("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?me("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):_i.test(o)?me("MULTI_HOP_RETRIEVAL",.7,"comparison/compoun\
120
- d question",Math.min(this.maxRounds,2)):Xo.test(o)?me("SINGLE_RETRIEVAL",.65,"single factual lookup",1):me("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function Di(t,e){return t===
121
- "SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function me(t,e,n,o){return {executionClass:t,confidence:e,reason:n,rounds:o}}var Cn=class{constructor(e=512){this.cap=e;}cap;map=new Map;read(e){return this.map.get(e)}record(e,n,o){this.map.size>=this.cap&&!this.map.has(e)&&this.map.clear(),this.map.set(e,{ids:n,turns:o});}};function Pi(t){
122
- return !t.some(e=>Array.isArray(e.intents)&&e.intents.length>0)&&!t.some(e=>typeof e.risk=="string")}var Tt=class{maxTools;scoreIntentMatch;learningTurns;freezer;constructor(e={}){this.maxTools=e.maxTools??
123
- 8,this.scoreIntentMatch=e.scoreIntentMatch??Li,this.learningTurns=e.learningTurns??16,this.freezer=e.freezer??new Cn;}passthrough(e){if(!e||e.length===0)return {tools:[],droppedIds:[],reason:"no tools p\
124
- rovided",setIsStable:true};let n=e.slice(0,this.maxTools),o=e.slice(this.maxTools).map(r=>r.id);return {tools:n,droppedIds:o,reason:`router off: caller tools passed through unfiltered (${n.length}/${e.length}\
125
- , capped at maxTools=${this.maxTools}; risk gating is the caller's responsibility while routing is off)`,setIsStable:true}}select(e,n,o,r){if(!n||n.length===0)return {tools:[],droppedIds:[],reason:"no to\
126
- ols provided",setIsStable:true};if(Pi(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}\
127
- , capped at maxTools=${this.maxTools}). Declare ToolDescriptor.intents/risk to enable pruning`}}let s=o==="TOOL_ACTION",i=n.filter(p=>s||p.risk==="read"),a=p=>s&&p.risk!=="read",c=i.filter(p=>!a(p)),l=i.
128
- filter(p=>a(p)),u=l.map(p=>({tool:p,score:this.scoreIntentMatch(e,p)})).sort((p,y)=>y.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,y)=>y.
129
- score-p.score).map(p=>p.tool),m=[...u.slice(0,this.maxTools),...d.slice(0,Math.max(0,this.maxTools-l.length))].map(p=>({tool:p})).map(p=>p.tool).sort((p,y)=>p.id<y.id?-1:p.id>y.id?1:0);if(r!==void 0){
130
- let p=this.freezer.read(r),y=(p?.turns??0)+1;if(p&&y>this.learningTurns){let x=new Set(p.ids),T=n.filter(R=>x.has(R.id));this.freezer.record(r,p.ids,y);let E=new Set(T.map(R=>R.id));return {tools:T,droppedIds:n.
131
- filter(R=>!E.has(R.id)).map(R=>R.id),reason:`frozen tool set after ${this.learningTurns} turns (${T.length}/${n.length}): it no longer depends on this request's text, so the prefix cache survives`,setIsStable:true}}
132
- let b=[...new Set([...p?.ids??[],...m.map(x=>x.id)])].sort().slice(0,this.maxTools);this.freezer.record(r,b,y);}let h=new Set(m.map(p=>p.id)),g=n.filter(p=>!h.has(p.id)).map(p=>p.id);return {tools:m,droppedIds:g,
133
- reason:`selected ${m.length}/${n.length} by intent match (writes ${s?"allowed":"blocked"})`,setIsStable:g.length===0}}};function Li(t,e){let n=vt(t),o=0;for(let r of Array.isArray(e.intents)?e.intents:
134
- []){let s=vt(r);s&&(n.includes(s)?o+=2:s.split(/\s+/).some(i=>i.length>3&&n.includes(i))&&(o+=1));}return o}function Mi(t){let e=new Set,n=[];for(let o of t){let r=o.hash??Ni(o.text);e.has(r)||(e.add(r),n.push(o));}return n}function Bi(t,e={maxDocuments:5}){let n=e.minDocuments??1,o=[...t].sort((i,a)=>(a.score??
135
- 0)-(i.score??0));if(o.length<=n)return o;let r=o[0]?.score??0;if(r<=0)return o.slice(0,e.maxDocuments);let s=[];for(let i of o){let a=(i.score??0)/r;if(s.length<n||a>=.4&&s.length<e.maxDocuments)s.push(
136
- i);else break}return s}async function Qo(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};
137
- let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,o=[];for(let i=0;i<n;i++){let a=await e.retriever.retrieve(t.query,t.maxDocuments*2);o.push(...a);}let r=o.length;o=Mi(o),e.reranker&&
138
- (o=await e.reranker.rerank(t.query,o));let s=Bi(o,{maxDocuments:t.maxDocuments});return {docs:s,rounds:n,retrievedCount:r,keptCount:s.length}}function Ni(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function eu(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function tu(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{
139
- ...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[o,r]of Object.entries(e.set??{}))o==="userPreferences"&&zi(r)?Object.assign(n.userPreferences,
140
- r):n.confirmedFacts[o]=r;for(let[o,r]of Object.entries(e.append??{})){let s=$i(n,o);s?s.push(...r.map(String)):n.confirmedFacts[o]=r;}for(let o of e.remove??[])delete n.confirmedFacts[o],delete n.userPreferences[o],
141
- Fi(n,o);return n}function nu(t){let e=t.rawTurns??3,n=[],o=ji(t.state);o&&n.push({role:"system",content:`Conversation state:
142
- ${o}`});let r=t.history.slice(-e);return n.push(...r,t.current),n}function ji(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`fa\
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\
130
+ 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
+ , 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\
143
149
  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(
144
150
  "; ")}`),t.openItems.length&&e.push(`open: ${t.openItems.join("; ")}`),e.join(`
145
- `)}function $i(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 Fi(t,e){
146
- for(let n of ["goals","decisions","openItems","evidenceRefs"]){let o=t[n].indexOf(e);o>=0&&t[n].splice(o,1);}}function zi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var er={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function tr(t,e={}){let n=e.delimiter??",",o=e.indent??" ",s=t.split(`
147
- `).filter(c=>c.trim().length>0).map(c=>({indent:Vi(c,o),content:c.slice(nr(c,o))}));if(s.length===0)return {};let i=s[0];if(i.indent===0){let c=i.content.match(/^\[(\d+)\]\{(.*)\}:\s*$/);if(c){let u=$e(
148
- c[2],n),d=Number(c[1]),f=[];for(let m=0,h=1;m<d&&h<s.length;m++,h++){let g=s[h];if(g.indent!==1)break;let p=$e(g.content,n),y={};u.forEach((b,x)=>{y[b]=rt(p[x]??"null");}),f.push(y);}return f}let l=i.content.
149
- match(/^\[(\d+)\]:\s*(.*)$/);if(l){let u=l[2];return Number(l[1])===0||u.trim()===""?[]:$e(u,n).map(rt)}}let[a]=or(s,0,0,n);return a}function nr(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}
150
- function Vi(t,e){return nr(t,e)/e.length}function or(t,e,n,o){let r={},s=e;for(;s<t.length;){let i=t[s];if(i.indent<n)break;if(i.indent>n){s++;continue}let a=Ui(i.content,o);if(!a){s++;continue}let{key:c,
151
- kind:l}=a;if(l.type==="scalar")r[c]=l.value,s++;else if(l.type==="inlineArray")r[c]=l.values,s++;else if(l.type==="emptyArray")r[c]=[],s++;else if(l.type==="table"){let u=[];s++;for(let d=0;d<l.count&&
152
- s<t.length;d++,s++){let f=t[s];if(f.indent!==n+1)break;let m=$e(f.content,o),h={};l.columns.forEach((g,p)=>{h[g]=rt(m[p]??"null");}),u.push(h);}r[c]=u;}else {let[u,d]=or(t,s+1,n+1,o);r[c]=u,s=d;}}return [r,
153
- s]}function Ui(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:Et(n[1]),kind:{type:"table",count:Number(n[2]),columns:$e(n[3],e)}};let o=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(o){
154
- let s=Number(o[2]),i=o[3];return s===0||i.trim()===""?{key:Et(o[1]),kind:{type:"emptyArray"}}:{key:Et(o[1]),kind:{type:"inlineArray",values:$e(i,e).map(rt)}}}let r=t.match(/^([^:]+):\s*(.*)$/);if(r){let s=Et(
155
- r[1]),i=r[2];return i===""?{key:s,kind:{type:"object"}}:{key:s,kind:{type:"scalar",value:rt(i)}}}return null}function $e(t,e){let n=[],o="",r=false;for(let s=0;s<t.length;s++){let i=t[s];r?i==='"'?t[s+1]===
156
- '"'?(o+='"',s++):r=false:o+=i:i==='"'?r=true:i===e?(n.push(o),o=""):o+=i;}return n.push(o),n.map(s=>s.trim())}function rt(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,
157
- '"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function Et(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,
158
- '"'):e}function qi(t,e={}){let n=e.delimiter??",",o=e.indent??" ",r=[];return _n(null,t,0,r,n,o),r.join(`
159
- `)}function _n(t,e,n,o,r,s){let i=s.repeat(n),a=t===null?"":`${Ki(t)}`;if(Array.isArray(e)){Hi(a,e,n,o,r,s);return}if(On(e)){t!==null&&o.push(`${i}${a}:`);let c=t===null?n:n+1;for(let[l,u]of Object.entries(
160
- e))_n(l,u,c,o,r,s);return}o.push(`${i}${a}: ${Rt(e,r)}`);}function Hi(t,e,n,o,r,s){let i=s.repeat(n),a=t===""?"":t;if(e.length===0){o.push(`${i}${a}[0]:`);return}if(e.every(In)){let d=e.map(f=>Rt(f,r)).
161
- join(r);o.push(`${i}${a}[${e.length}]: ${d}`);return}let c=Ct(e);if(c){o.push(`${i}${a}[${e.length}]{${c.join(r)}}:`);let d=s.repeat(n+1);for(let f of e){let m=c.map(h=>Rt(f[h],r)).join(r);o.push(`${d}${m}`);}
162
- return}o.push(`${i}${a}[${e.length}]:`);let l=n+1,u=s.repeat(l);for(let d of e)if(In(d))o.push(`${u}- ${Rt(d,r)}`);else {let f=[];_n(null,d,0,f,r,s);let[m,...h]=f;o.push(`${u}- ${m??""}`);for(let g of h)
163
- o.push(`${u}${s}${g}`);}}function Ct(t){if(t.length===0)return null;let e=t[0];if(!On(e))return null;let n=Object.keys(e);if(n.length===0)return null;let o=n.slice().sort().join("\0");for(let r of t){if(!On(
164
- r))return null;let s=Object.keys(r);if(s.slice().sort().join("\0")!==o)return null;for(let i of s)if(!In(r[i]))return null}return n}function Ki(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:rr(t)}function Rt(t,e){
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
171
  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(`
166
- `)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?rr(n):n}function rr(t){return `"${t.replace(/"/g,'""')}"`}function In(t){return t===null||typeof t=="string"||typeof t==
167
- "number"||typeof t=="boolean"}function On(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ji="Data is the compact encoder: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; ea\
168
- 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 Wi(t={}){return {format:"compact-rows",supports(){return true},
169
- encode(e){return qi(e,t)},instruction(){return Ji},decode(e){return tr(e,t)}}}var sr=Wi();var ar={format:"csv",supports(t){return Array.isArray(t)&&Ct(t)!==null},encode(t){let e=t,n=Ct(e),o=n.map(ir).join(","),r=e.map(s=>n.map(i=>ir(s[i])).join(","));return [o,...r].join(`
170
- `)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function ir(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,
171
- '""')}"`:e}var It=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[er,sr,ar],this.minSavingsTokens=e.minimumSavingsTokens??
172
- 64,this.minSavingsRatio=e.minimumSavingsRatio??.08,this.qualityPenalty=e.qualityPenalty??(()=>0);}choose(e,n){let o={model:n.model,tokenizer:n.tokenizer},r=[];for(let l of this.serializers){if(!l.supports(
173
- e))continue;let u=l.encode(e);if(l.format!=="json-compact"&&!Gi(l,u,e))continue;let d=l.instruction(e),f=this.tokenizer.count(u,o),m=d?this.tokenizer.count(d,o):0,h=this.qualityPenalty(n.model??"",l.format);
174
- r.push({format:l.format,encoded:u,instruction:d,payloadTokens:f,instructionTokens:m,penalty:h,total:f+m+h});}let s=r.find(l=>l.format==="json-compact"),i={};for(let l of r)i[l.format]=l.total;if(!s){let l=r[0];
175
- return l?cr(l,i,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:i,instructionOverheadTokens:0,reason:"no serializer supported payload; defa\
176
- ulted to JSON"}}let a=s,c="json baseline (no challenger cleared thresholds)";for(let l of r){if(l.format==="json-compact")continue;let u=s.total-l.total,d=s.total===0?0:u/s.total;u>=this.minSavingsTokens&&
177
- d>=this.minSavingsRatio&&l.total<a.total&&(a=l,c=`${l.format} saved ${u} tokens (${(d*100).toFixed(1)}%) vs json`);}return cr(a,i,c)}};function Gi(t,e,n){if(!t.decode)return false;try{return An(t.decode(e),
178
- n)}catch{return false}}function An(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),o=Array.isArray(e);if(n||o){if(!n||!o||t.length!==e.
179
- length)return false;for(let i=0;i<t.length;i++)if(!An(t[i],e[i]))return false;return true}let r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return false;for(let i of r)if(!Object.prototype.hasOwnProperty.
180
- call(e,i)||!An(t[i],e[i]))return false;return true}function cr(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function ae(t,e,n="$"){let o=[];return Dn(t,e,n,o),{valid:o.length===0,errors:o}}function Yi(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
181
- string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function Dn(t,e,n,o){switch(e.enum&&!e.enum.some(s=>ta(s,t))&&o.push({path:n,message:"value not in enum"}),
182
- e.type??Yi(t)){case "object":Zi(t,e,n,o);break;case "array":Xi(t,e,n,o);break;case "string":Qi(t,e,n,o);break;case "number":case "integer":ea(t,e,n,o);break;case "boolean":typeof t!="boolean"&&o.push({path:n,
183
- message:"expected boolean"});break;case "null":t!==null&&o.push({path:n,message:"expected null"});break;}}function Zi(t,e,n,o){if(typeof t!="object"||t===null||Array.isArray(t)){o.push({path:n,
184
- message:"expected object"});return}let r=t;for(let s of e.required??[])s in r||o.push({path:`${n}.${s}`,message:"missing required property"});if(e.additionalProperties===false&&e.properties){let s=new Set(
185
- Object.keys(e.properties));for(let i of Object.keys(r))s.has(i)||o.push({path:`${n}.${i}`,message:"additional property not allowed"});}if(e.properties)for(let[s,i]of Object.entries(e.properties))s in r&&
186
- Dn(r[s],i,`${n}.${s}`,o);}function Xi(t,e,n,o){if(!Array.isArray(t)){o.push({path:n,message:"expected array"});return}e.maxItems!=null&&t.length>e.maxItems&&o.push({path:n,message:`array exceeds maxIte\
187
- ms ${e.maxItems}`}),e.minItems!=null&&t.length<e.minItems&&o.push({path:n,message:`array below minItems ${e.minItems}`}),e.items&&t.forEach((r,s)=>Dn(r,e.items,`${n}[${s}]`,o));}function Qi(t,e,n,o){if(typeof t!=
188
- "string"){o.push({path:n,message:"expected string"});return}if(e.maxLength!=null&&t.length>e.maxLength&&o.push({path:n,message:`string exceeds maxLength ${e.maxLength}`}),e.minLength!=null&&t.length<e.
189
- minLength&&o.push({path:n,message:`string below minLength ${e.minLength}`}),e.pattern){let r=null;try{r=new RegExp(e.pattern);}catch{o.push({path:n,message:`schema pattern is not a valid regular expres\
190
- sion: ${e.pattern}`});}r&&!r.test(t)&&o.push({path:n,message:"string does not match pattern"});}}function ea(t,e,n,o){if(typeof t!="number"||Number.isNaN(t)){o.push({path:n,message:"expected number"});return}
191
- e.type==="integer"&&!Number.isInteger(t)&&o.push({path:n,message:"expected integer"}),e.maximum!=null&&t>e.maximum&&o.push({path:n,message:`number exceeds maximum ${e.maximum}`}),e.minimum!=null&&t<e.
192
- minimum&&o.push({path:n,message:`number below minimum ${e.minimum}`});}function ta(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var Ot=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 o=[];return Pn(
193
- e,n,o),o}};function Pn(t,e,n){if(t.type==="object"){t.additionalProperties!==false&&n.push(`${e}: object should set additionalProperties:false`);for(let[o,r]of Object.entries(t.properties??{}))Pn(r,`${e}\
194
- .${o}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&Pn(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: s\
195
- tring should set maxLength or use an enum`);}function lr(t,e,n){for(let o of n)if(o.supports(t,e))return {backend:o.id,reason:`first supporting backend: ${o.id}`};return {backend:"none",reason:"no constrained-decoding backend available; will valid\
196
- ate + repair"}}function Eu(t=()=>true){return {id:"provider-native",supports:t}}function Ln(t){let e=t.minimumContextTokens??2e3,n=t.minimumNetTokens??200;if(t.contextTokens<e)return {compress:false,reason:`context ${t.contextTokens} < ${e} min`};let o=t.projectedEliminable-t.compressorCostTokens;
197
- return o<n?{compress:false,reason:`net saving ${o} < ${n} min`}:{compress:true,reason:`net saving ${o} tokens`}}function Du(t){return {async compress(e){let n=e.protectedSpans??[],o=e.text,r=[];n.forEach((c,l)=>{
198
- let u=`\0PROTECT_${l}\0`;r.push({token:u,span:c}),o=o.split(c.text).join(u);});let s=await t.compress({text:o,...e.targetRatio!=null?{targetRatio:e.targetRatio}:{}}),i=s.compressed,a=true;for(let{token:c,
199
- span:l}of r){if(!i.includes(c)){a=false;break}i=i.split(c).join(l.text);}return a?{...s,compressed:i,protectedSpans:n.length,fidelityPassed:true}:{compressed:e.text,originalTokens:s.originalTokens,compressedTokens:s.
200
- originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var Pu={async compress(t){return {compressed:t.text,originalTokens:0,
201
- compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function ur(t,e){let n=i=>i.toLowerCase().replace(/[.,;:!¡?¿()[\]{}"«»…]/g,
202
- " ").replace(/\s+/g," ").trim(),r=n((i=>{let a=new Set,c=[];for(let l of i.split(`
203
- `)){let u=l.trim();u&&a.has(u)||(u&&a.add(u),c.push(l));}return c.join(`
204
- `)})(t)),s=n(e);return !(!En(tt(r),tt(s))||ot(nt(r))!==ot(nt(s)))}var dr=new WeakSet;function pr(t){dr.add(t);}var Mn=class{id="mock";options;constructor(e={}){this.options=e,pr(this);}async generate(e){let n=e.messages.map(a=>a.content).join(`
205
- `),o=Ne.count(n);if(e.tools&&e.tools.length>0){let a=JSON.stringify(e.tools.map(c=>({name:c.id,description:c.description,parameters:c.parameters??{}})));o+=Ne.count(a);}let r,s=false;if(e.schema){let a=this.
206
- options.data??_t(e.schema);r=JSON.stringify(a),s=true;}else r=this.options.answer??`mock-response(${e.model})`;let i=Math.min(e.maxOutputTokens??Number.MAX_SAFE_INTEGER,Ne.count(r));return {text:r,usage:{
207
- inputTokens:o,outputTokens:i,...this.options.cachedInputTokens!=null?{cachedInputTokens:this.options.cachedInputTokens}:{}},structuredNatively:s}}};function _t(t){if(t.enum&&t.enum.length>0)return t.enum[0];
208
- switch(t.type){case "object":{let e={};for(let n of t.required??[]){let o=t.properties?.[n];e[n]=o?_t(o):null;}for(let[n,o]of Object.entries(t.properties??{}))n in e||(e[n]=_t(o));return e}case "array":return t.
209
- items?[_t(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 Fu(t){return new Mn(t)}var na={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},At="flex";function mr(t){if(t==null||t==="")return null;let e=na[t];return e==null?{servido:t,factor:null,conDescuento:false}:
210
- {servido:t,factor:e,conDescuento:e<1}}function hr(t,e){return !t||t.factor==null||!t.conDescuento||!Number.isFinite(e)||e<=0?null:e*(1-t.factor)}var oa="slower and variable: OpenAI publishes no latency\
211
- 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 short the request re\
212
- turns 429 and is not charged. Do not put a deferrable request on a user-facing path.",ra="unchanged: this provider has no cheaper synchronous processing tier, so nothing was asked for and the request \
213
- was scheduled exactly as it would have been.",gr="this provider has no cheaper synchronous processing tier, so the request was sent unchanged and nothing is credited; on this provider the deferred dis\
214
- count lives only in the asynchronous batch API, which is not a request/response call";function br(t){return t==null||t===""?ra:t===At?oa:`unknown: this layer has no published latency statement for the\
215
- "${t}" tier.`}var yr=new Set;function G(t,e){yr.has(t)||(yr.add(t),console.warn(e));}function Ae(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 r=Object.keys(n),s=Array.isArray(e.required)?e.required.
216
- map(String):[];if(r.some(i=>!s.includes(i)))return false;for(let i of Object.values(n))if(!Ae(i))return false}if(e.items!==void 0&&!Ae(e.items))return false;for(let r of ["anyOf","oneOf","allOf"]){let s=e[r];if(Array.
217
- isArray(s)&&s.some(i=>!Ae(i)))return false}let o=e.$defs??e.definitions;return !(o&&typeof o=="object"&&Object.values(o).some(r=>!Ae(r)))}function sa(t){return !/response_format/i.test(t)||/invalid schema/i.
218
- test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.test(t)}function ia(t){return `Respond with a single JSON object and nothing else: no prose, no\
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!=
194
+ "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
+ 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}
197
+ 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(
225
+ 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
+ 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\
219
236
  explanation, no markdown code fences. The object must validate against this JSON Schema:
220
- `+JSON.stringify(t)}var xr=class{id;opts;fetchImpl;sinResponseFormat=new Set;constructor(e){this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch;}async generate(e){let n=this.
221
- opts.stripProviderPrefix?e.model.replace(/^[^/]+\//,""):e.model,o=e.schema!=null&&!this.sinResponseFormat.has(n),r=await this.enviar(n,e,o);if(!r.ok&&r.status===400&&o){let s=await vr(r);if(!sa(s))throw new Error(
222
- `provider ${r.status}: ${s}`);this.sinResponseFormat.add(n),G(`sin-response-format:${n}`,`[bvsala] El modelo "${n}" rechaza \`response_format\` con un 400: no tiene structured outputs. Se repite la peti\
223
- ci\xF3n pidiendo el JSON por prompt (una sola vez: el modelo queda anotado y las siguientes van directas). El esquema sigue viajando y el layer sigue validando, pero la garant\xEDa la da el layer, no el pro\
224
- veedor, y el informe lo dice: \`constraints.backend: "none"\`. Para recuperar la garant\xEDa nativa, usa un modelo con structured outputs (gpt-4o o posterior).`),o=false,r=await this.enviar(n,e,false);}if(!r.
225
- ok){let s=await vr(r);throw new Error(`provider ${r.status}: ${s}`)}return this.leer(r,e,o)}async enviar(e,n,o){let r=n.messages.map(i=>i.role==="tool"?{role:"tool",content:i.content,tool_call_id:i.toolCallId??
226
- i.metadata?.tool_call_id,...i.name?{name:i.name}:{}}:i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0?{role:"assistant",content:i.content||null,tool_calls:i.toolCalls.map((a,c)=>({id:a.id??`cal\
227
- l_${c}`,type:"function",function:{name:a.name,arguments:a.arguments}}))}:{role:i.role,content:i.content});n.schema&&!o&&r.push({role:"system",content:ia(n.schema)});let s={model:e,messages:r};if(n.maxOutputTokens!=
228
- null&&(s.max_tokens=n.maxOutputTokens),n.temperature!=null&&(s.temperature=n.temperature),n.seed!=null&&(s.seed=n.seed),n.promptCacheKey!=null&&(s.prompt_cache_key=n.promptCacheKey),n.deferrable===true&&
229
- (s.service_tier=At),n.schema&&o){let i=Ae(n.schema);i||G("strict-incompatible","[bvsala] El contrato de respuesta no cumple el modo `strict` de OpenAI (en strict, `required` debe listar TODAS las clav\
230
- es de `properties`, y todo objeto necesita `additionalProperties: false`). Se env\xEDa el esquema con `strict: false`: el modelo sigue guiado y el layer sigue validando, pero la garant\xEDa la da el layer, \
231
- no el proveedor. Para recuperarla, haz obligatorias todas las claves del contrato."),s.response_format={type:"json_schema",json_schema:{name:"bvsala_contract",schema:n.schema,strict:i}};}return n.tools&&
232
- n.tools.length>0&&(s.tools=n.tools.map(i=>({type:"function",function:{name:i.id,...i.description?{description:i.description}:{},parameters:i.parameters??{type:"object",properties:{}}}}))),await this.fetchImpl(
233
- `${this.opts.baseUrl.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.headers},
234
- body:JSON.stringify(s)})}async leer(e,n,o){let r=await e.json(),s=r.choices?.[0]?.message,i=s?.content??"",a=(s?.tool_calls??[]).map(g=>({...g.id?{id:g.id}:{},name:g.function?.name??"",arguments:g.function?.
235
- arguments??""})).filter(g=>g.name!==""),c=r.usage??{},l=c.prompt_tokens??0,u=c.completion_tokens??0,d=typeof c.prompt_tokens!="number",f=typeof c.completion_tokens!="number";if(this.opts.requireUsage&&
236
- (d||f))throw new Error(`provider returned incomplete usage (prompt=${c.prompt_tokens??"absent"}, completion=${c.completion_tokens??"absent"}); cannot measure cost. For gateways/streaming, ensure usage\
237
- reporting is enabled.`);let m=r.choices?.[0]?.finish_reason,h=typeof r.service_tier=="string"&&r.service_tier!==""?r.service_tier:void 0;return {text:i,...a.length>0?{toolCalls:a}:{},...m?{finishReason:m}:
238
- {},...h?{servedServiceTier:h}:{},...n.deferrable===true?{requestedServiceTier:At}:{},usage:{inputTokens:l,outputTokens:u,...c.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:c.prompt_tokens_details.
239
- cached_tokens}:{}},structuredNatively:n.schema!=null&&o,raw:r}}};async function vr(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function kr(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:
240
- `+JSON.stringify(t)}var Dt=4,Fe="bvsala_contract",wr=class{id;opts;fetchImpl;constructor(e={}){this.opts=e,this.id=`anthropic:${e.baseUrl??"https://api.anthropic.com/v1"}`,this.fetchImpl=e.fetchImpl??fetch;}async generate(e){
241
- let n=this.construirCuerpo(e),o=(this.opts.baseUrl??"https://api.anthropic.com/v1").replace(/\/$/,""),r=await this.fetchImpl(`${o}/messages`,{method:"POST",headers:{"content-type":"application/json","\
242
- anthropic-version":this.opts.apiVersion??"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},body:JSON.stringify(n.body)});if(!r.ok)throw new Error(`provider ${r.status}\
243
- : ${await la(r)}`);return this.leer(r,e,n.contratoNativo)}construirCuerpo(e){let{system:n,messages:o,prefijoEnMensajes:r,prefijoEnSystem:s}=aa(e);if(o.length===0)throw new Error("anthropic: the reques\
244
- t 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 i=(e.tools??[]).map(d=>({name:d.id,...d.description?
245
- {description:d.description}:{},input_schema:d.parameters??{type:"object",properties:{}}})),a=false,c=false;if(e.schema){let d=i.length>0,f=i.some(h=>h.name===Fe),m=Ae(e.schema);f?(n.push({type:"text",text:kr(
246
- e.schema)}),G("anthropic-contrato-nombre-ocupado",`[bvsala] One of your tools is already named \`${Fe}\`, so the output contract cannot travel as a tool without colliding with it (duplicate tool names \
247
- 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.`)):(!m&&!d&&G("anthropic-strict-incompatible",
248
- "[bvsala] El contrato de respuesta no cumple el modo `strict` (en strict, `required` debe listar TODAS las claves de `properties`, y todo objeto necesita `additionalProperties: false`). Se env\xEDa el es\
249
- quema sin `strict`: el modelo sigue guiado y el layer sigue validando, pero la garant\xEDa la da el layer, no el proveedor."),a=m&&!d,i.push({name:Fe,description:d?"Return the final answer in the requ\
250
- ired 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.schema,...a?{strict:true}:{}}),
251
- d&&(c=this.opts.forceAnswerThroughTool!==false,G("anthropic-contrato-con-herramientas","[bvsala] This request carries BOTH your tools and an output contract. On Anthropic's Messages API a specific shape \
252
- 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"+(c?' and the request is sent with `tool_choice: {typ\
253
- e: "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 layer\'s, not the provider\'s (\
254
- `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`). The guarantee is the layer's\
255
- , 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-pays the whole tool-use overhea\
256
- d.")+" Dropping either the tools or the contract from this request is what makes the guarantee free.")));}let l={model:e.model,max_tokens:e.maxOutputTokens??this.opts.defaultMaxOutputTokens??4096,messages:o};
257
- n.length>0&&(l.system=n),e.temperature!=null&&(l.temperature=e.temperature),i.length>0&&(l.tools=i),a?l.tool_choice={type:"tool",name:Fe}:c&&(l.tool_choice={type:"any"}),e.deferrable===true&&G("anthropi\
258
- c-sin-tier-diferible","[bvsala] Esta petici\xF3n se declar\xF3 diferible, pero la API de Mensajes de Anthropic NO tiene un tier s\xEDncrono m\xE1s barato: su `service_tier` elige entre capacidad prioritaria (m\xE1s \
259
- cara) y est\xE1ndar, no un flex. La petici\xF3n sale sin cambios y el informe no acredita ning\xFAn descuento. El 50% por diferir existe en la Message Batches API, que es as\xEDncrona y no cabe en una llamada de \
260
- petici\xF3n/respuesta.");let u=this.marcarCache(e,n,o,r,s);return this.opts.automaticCache===true&&e.stablePrefixMessages!=null&&u<Math.min(this.opts.maxCacheBreakpoints??Dt,Dt)&&(l.cache_control={type:"\
261
- ephemeral"}),{body:l,contratoNativo:a}}marcarCache(e,n,o,r,s){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return 0;let i=Math.min(this.opts.maxCacheBreakpoints??Dt,Dt);if(i<=0)return 0;let a=i,
262
- c=s>0?n[s-1]:void 0;if(c&&(c.cache_control={type:"ephemeral"},i-=1),i>0&&r>0){let l=o[Math.min(r,o.length)-1],u=l?.content[l.content.length-1];u&&(u.cache_control={type:"ephemeral"},i-=1);}return a-i}async leer(e,n,o){
263
- let r=await e.json(),s=r.content??[],i=s.filter(b=>b.type==="text").map(b=>b.text??"").join(""),a=s.filter(b=>b.type==="tool_use"&&b.name!==Fe).map(b=>({...b.id?{id:b.id}:{},name:b.name??"",arguments:JSON.
264
- stringify(b.input??{})})).filter(b=>b.name!==""),c=s.find(b=>b.type==="tool_use"&&b.name===Fe),l=c?JSON.stringify(c.input??{}):i,u=r.usage??{},d=u.cache_read_input_tokens,f=u.cache_creation_input_tokens,
265
- m=(u.input_tokens??0)+(f??0)+(d??0),h=u.output_tokens??0,g=typeof u.input_tokens!="number",p=typeof u.output_tokens!="number";if(this.opts.requireUsage&&(g||p))throw new Error(`provider returned incom\
266
- plete usage (input=${u.input_tokens??"absent"}, output=${u.output_tokens??"absent"}); cannot measure cost.`);let y=typeof u.service_tier=="string"&&u.service_tier!==""?u.service_tier:void 0;return {text:l,
267
- ...a.length>0?{toolCalls:a}:{},...r.stop_reason?{finishReason:ca(r.stop_reason)}:{},...y?{servedServiceTier:y}:{},usage:{inputTokens:m,outputTokens:h,...d!=null?{cachedInputTokens:d}:{},...f!=null?{cacheWriteInputTokens:f}:
268
- {}},structuredNatively:n.schema!=null&&o,raw:r}}};function aa(t){let e=[],n=[],o=t.stablePrefixMessages??0,r=0,s=0,i=true;return t.messages.forEach((a,c)=>{if(a.role==="system"&&i){e.push({type:"text",text:a.
269
- content}),c<o&&(s=e.length);return}i=false,n.push({role:a.role==="assistant"?"assistant":"user",content:[{type:"text",text:a.content}]}),c<o&&(r=n.length);}),n.length>0&&n[0].role==="assistant"&&(n.unshift(
270
- {role:"user",content:[{type:"text",text:"(continue)"}]}),r>0&&(r+=1)),{system:e,messages:n,prefijoEnMensajes:r,prefijoEnSystem:s}}function ca(t){switch(t){case "end_turn":return "stop";case "max_tokens":
271
- return "length";case "tool_use":return "tool_calls";case "refusal":return "content_filter";default:return t}}async function la(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}var st=class{events=[];start;now;constructor(e=()=>Date.now()){this.now=e,this.start=e();}record(e,n,o){this.events.push({stage:e,outcome:n,...o?{detail:o}:{},atMs:this.now()-this.start});}elapsed(){return this.
272
- now()-this.start}all(){return this.events}};var De=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function Bn(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Pt(t,e=""){if(typeof t!="number"){let n=e&&
273
- `"${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 oe(t,e,n=""){
274
- let o=Bn(t),r=t?.length,s=e!==void 0;if(!o||s&&r!==e){let i=n&&`"${n}" `,a=s?` of length ${e}`:"",c=o?`length=${r}`:`type=${typeof t}`,l=i+"expected Uint8Array"+a+", got "+c;throw o?new RangeError(l):
275
- new TypeError(l)}return t}function Nn(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 Tr(t,e){oe(t,void 0,"digestInt\
276
- o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function it(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function Lt(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Er=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ua=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Mt(t){if(oe(t),Er)return t.toHex();
277
- let e="";for(let n=0;n<t.length;n++)e+=ua[t[n]];return e}var he={_0:48,_9:57,A:65,F:70,a:97,f:102};function Sr(t){if(t>=he._0&&t<=he._9)return t-he._0;if(t>=he.A&&t<=he.F)return t-(he.A-10);if(t>=he.a&&
278
- t<=he.f)return t-(he.a-10)}function at(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Er)try{return Uint8Array.fromHex(t)}catch(r){throw r instanceof SyntaxError?
279
- new RangeError(r.message):r}let e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let o=new Uint8Array(n);for(let r=0,s=0;r<n;r++,s+=2){let i=Sr(t.charCodeAt(
280
- s)),a=Sr(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)}o[r]=i*16+a;}return o}function jn(...t){let e=0;for(let o=0;o<t.length;o++){let r=t[o];oe(r),e+=r.length;}let n=new Uint8Array(e);for(let o=0,r=0;o<t.length;o++){let s=t[o];n.set(s,r),r+=s.length;}return n}function Rr(t,e={}){let n=(r,s)=>t(s).update(r).digest(),o=t(void 0);return n.outputLen=o.outputLen,n.blockLen=o.blockLen,n.canXOF=o.canXOF,n.create=r=>t(r),Object.assign(n,e),Object.freeze(n)}function Cr(t=32){
281
- Pt(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(
282
- `"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var Ir=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var Bt=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(e,n,o,r){this.blockLen=e,this.outputLen=n,this.padOffset=o,this.isLE=r,this.buffer=
283
- new Uint8Array(e),this.view=Lt(this.buffer);}update(e){Nn(this),oe(e);let{view:n,buffer:o,blockLen:r}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(r-this.pos,s-i);if(a===r){let c=Lt(e);for(;r<=s-i;i+=
284
- r)this.process(c,i);continue}o.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===r&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){Nn(this),
285
- Tr(e,this),this.finished=true;let{buffer:n,view:o,blockLen:r,isLE:s}=this,{pos:i}=this;n[i++]=128,it(this.buffer.subarray(i)),this.padOffset>r-i&&(this.process(o,0),i=0);for(let d=i;d<r;d++)n[d]=0;o.setBigUint64(
286
- r-8,BigInt(this.length*8),s),this.process(o,0);let a=Lt(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_s\
287
- ha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s);}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let o=e.slice(0,n);return this.destroy(),o}_cloneInto(e){e||=new this.
288
- constructor,e.set(...this.get());let{blockLen:n,buffer:o,length:r,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=r,e.pos=a,r%n&&e.buffer.set(o),e}clone(){return this._cloneInto()}};var K=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Nt=BigInt(4294967295),Or=BigInt(32);function da(t,e=false){return e?{h:Number(t&Nt),l:Number(t>>Or&Nt)}:{h:Number(t>>Or&Nt)|0,l:Number(t&Nt)|0}}function _r(t,e=false){let n=t.length,o=new Uint32Array(n),
289
- r=new Uint32Array(n);for(let s=0;s<n;s++){let{h:i,l:a}=da(t[s],e);[o[s],r[s]]=[i,a];}return [o,r]}var $n=(t,e,n)=>t>>>n,Fn=(t,e,n)=>t<<32-n|e>>>n,Pe=(t,e,n)=>t>>>n|e<<32-n,Le=(t,e,n)=>t<<32-n|e>>>n,ct=(t,e,n)=>t<<64-n|e>>>n-32,lt=(t,e,n)=>t>>>n-32|e<<64-n;function ce(t,e,n,o){let r=(e>>>0)+(o>>>0);return {h:t+n+(r/2**32|0)|0,l:r|0}}var Ar=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Dr=(t,e,n,o)=>e+n+o+(t/2**32|0)|0,Pr=(t,e,n,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Lr=(t,e,n,o,r)=>e+
290
- n+o+r+(t/2**32|0)|0,Mr=(t,e,n,o,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0)+(r>>>0),Br=(t,e,n,o,r,s)=>e+n+o+r+s+(t/2**32|0)|0;var Nr=_r(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
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){
278
+ 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.
294
+ 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\
300
+ 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\
302
+ 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\
304
+ 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
+ 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
+ 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
+ ). 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
+ 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\
311
+ 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",
291
347
  "0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
292
348
  8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
293
349
  0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
@@ -295,294 +351,369 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
295
351
  x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
296
352
  efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
297
353
  eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
298
- 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),fa=Nr[0],ma=Nr[1],Te=new Uint32Array(80),Ee=new Uint32Array(80),zn=class extends Bt{constructor(e){
299
- super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:o,Bl:r,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:m,Gl:h,Hh:g,Hl:p}=this;return [e,n,o,r,s,i,a,c,l,u,d,f,m,h,g,p]}set(e,n,o,r,s,i,a,c,l,u,d,f,m,h,g,p){this.Ah=
300
- e|0,this.Al=n|0,this.Bh=o|0,this.Bl=r|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=m|0,this.Gl=h|0,this.Hh=g|0,this.Hl=p|0;}process(e,n){for(let x=0;x<
301
- 16;x++,n+=4)Te[x]=e.getUint32(n),Ee[x]=e.getUint32(n+=4);for(let x=16;x<80;x++){let T=Te[x-15]|0,E=Ee[x-15]|0,R=Pe(T,E,1)^Pe(T,E,8)^$n(T,E,7),C=Le(T,E,1)^Le(T,E,8)^Fn(T,E,7),D=Te[x-2]|0,I=Ee[x-2]|0,S=Pe(
302
- D,I,19)^ct(D,I,61)^$n(D,I,6),B=Le(D,I,19)^lt(D,I,61)^Fn(D,I,6),k=Pr(C,B,Ee[x-7],Ee[x-16]),w=Lr(k,R,S,Te[x-7],Te[x-16]);Te[x]=w|0,Ee[x]=k|0;}let{Ah:o,Al:r,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:m,Fl:h,
303
- Gh:g,Gl:p,Hh:y,Hl:b}=this;for(let x=0;x<80;x++){let T=Pe(d,f,14)^Pe(d,f,18)^ct(d,f,41),E=Le(d,f,14)^Le(d,f,18)^lt(d,f,41),R=d&m^~d&g,C=f&h^~f&p,D=Mr(b,E,C,ma[x],Ee[x]),I=Br(D,y,T,R,fa[x],Te[x]),S=D|0,
304
- B=Pe(o,r,28)^ct(o,r,34)^ct(o,r,39),k=Le(o,r,28)^lt(o,r,34)^lt(o,r,39),w=o&s^o&a^s&a,_=r&i^r&c^i&c;y=g|0,b=p|0,g=m|0,p=h|0,m=d|0,h=f|0,{h:d,l:f}=ce(l|0,u|0,I|0,S|0),l=a|0,u=c|0,a=s|0,c=i|0,s=o|0,i=r|0;
305
- let P=Ar(S,k,_);o=Dr(P,I,B,w),r=P|0;}(({h:o,l:r}=ce(this.Ah|0,this.Al|0,o|0,r|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:l,l:u}=ce(this.Dh|0,this.Dl|0,l|0,
306
- u|0),{h:d,l:f}=ce(this.Eh|0,this.El|0,d|0,f|0),{h:m,l:h}=ce(this.Fh|0,this.Fl|0,m|0,h|0),{h:g,l:p}=ce(this.Gh|0,this.Gl|0,g|0,p|0),{h:y,l:b}=ce(this.Hh|0,this.Hl|0,y|0,b|0),this.set(o,r,s,i,a,c,l,u,d,
307
- f,m,h,g,p,y,b);}roundClean(){it(Te,Ee);}destroy(){this.destroyed=true,it(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},Vn=class extends zn{Ah=K[0]|0;Al=K[1]|0;Bh=K[2]|0;Bl=K[3]|0;Ch=K[4]|0;Cl=K[5]|
308
- 0;Dh=K[6]|0;Dl=K[7]|0;Eh=K[8]|0;El=K[9]|0;Fh=K[10]|0;Fl=K[11]|0;Gh=K[12]|0;Gl=K[13]|0;Hh=K[14]|0;Hl=K[15]|0;constructor(){super(64);}};var jt=Rr(()=>new Vn,Ir(3));var z=(t,e,n)=>oe(t,e,n),qn=Pt,Hn=Mt,le=(...t)=>jn(...t),jr=t=>at(t),zt=Bn,$r=t=>Cr(t),Ft=BigInt(0),Un=BigInt(1);function ze(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"e\
309
- xpected boolean, got type="+typeof t)}return t}function ha(t){if(typeof t=="bigint"){if(!$t(t))throw new RangeError("positive bigint expected, got "+t)}else qn(t);return t}function ge(t,e=""){if(typeof t!=
310
- "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 Fr(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Ft:BigInt("0x"+t)}function Kn(t){return Fr(Mt(t))}function be(t){return Fr(Mt(ut(oe(t)).reverse()))}
311
- function Jn(t,e){if(Pt(e),e===0)throw new RangeError("zero length");t=ha(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return at(n.padStart(e*2,"0"))}function zr(t,e){
312
- return Jn(t,e).reverse()}function Vr(t,e){if(t=z(t),e=z(e),t.length!==e.length)return false;let n=0;for(let o=0;o<t.length;o++)n|=t[o]^e[o];return n===0}function ut(t){return Uint8Array.from(z(t))}var $t=t=>typeof t=="bigint"&&Ft<=t;function ga(t,e,n){return $t(t)&&$t(e)&&$t(n)&&e<=t&&t<n}function Wn(t,e,n,o){if(!ga(e,n,o))throw new RangeError(
313
- "expected valid "+t+": "+n+" <= n < "+o+", got "+e)}function Gn(t){if(t<Ft)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>Ft;t>>=Un,e+=1);return e}var Ur=t=>(Un<<BigInt(t))-Un;function Me(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function o(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(
314
- `param "${s}" is invalid: expected own property`);let c=t[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${l}`)}let r=(s,i)=>Object.
315
- entries(s).forEach(([a,c])=>o(a,c,i));r(e,false),r(n,true);}var Yn=()=>{throw new Error("not implemented")};var J=BigInt(0),q=BigInt(1),Be=BigInt(2),Jr=BigInt(3),Wr=BigInt(4),Gr=BigInt(5),ba=BigInt(7),Yr=BigInt(8),ya=BigInt(9),Zr=BigInt(16);function j(t,e){if(e<=J)throw new Error("mod: expected positive mod\
316
- ulus, got "+e);let n=t%e;return n>=J?n:e+n}function re(t,e,n){if(e<J)throw new Error("pow2: expected non-negative exponent, got "+e);let o=t;for(;e-- >J;)o*=o,o%=n;return o}function qr(t,e){if(t===J)throw new Error("invert: expected non-zero n\
317
- umber");if(e<=J)throw new Error("invert: expected positive modulus, got "+e);let n=j(t,e),o=e,r=J,i=q;for(;n!==J;){let l=o/n,u=o-n*l,d=r-i*l;o=n,n=u,r=i,i=d;}if(o!==q)throw new Error(
318
- "invert: does not exist");return j(r,e)}function Zn(t,e,n){let o=t;if(!o.eql(o.sqr(e),n))throw new Error("Cannot find square root")}function Xr(t,e){let n=t,o=(n.ORDER+q)/Wr,r=n.pow(e,o);return Zn(n,r,
319
- e),r}function xa(t,e){let n=t,o=(n.ORDER-Gr)/Yr,r=n.mul(e,Be),s=n.pow(r,o),i=n.mul(e,s),a=n.mul(n.mul(i,Be),s),c=n.mul(i,n.sub(a,n.ONE));return Zn(n,c,e),c}function va(t){let e=Ht(t),n=Qr(t),o=n(e,e.neg(
320
- e.ONE)),r=n(e,o),s=n(e,e.neg(o)),i=(t+ba)/Zr;return((a,c)=>{let l=a,u=l.pow(c,i),d=l.mul(u,o),f=l.mul(u,r),m=l.mul(u,s),h=l.eql(l.sqr(d),c),g=l.eql(l.sqr(f),c);u=l.cmov(u,d,h),d=l.cmov(m,f,g);let p=l.
321
- eql(l.sqr(d),c),y=l.cmov(u,d,p);return Zn(l,y,c),y})}function Qr(t){if(t<Jr)throw new Error("sqrt is not defined for small field");let e=t-q,n=0;for(;e%Be===J;)e/=Be,n++;let o=Be,r=Ht(t);for(;Hr(r,o)===
322
- 1;)if(o++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Xr;let s=r.pow(o,e),i=(e+q)/Be;return function(c,l){let u=c;if(u.is0(l))return l;if(Hr(u,l)!==1)throw new Error(
323
- "Cannot find square root");let d=n,f=u.mul(u.ONE,s),m=u.pow(l,e),h=u.pow(l,i);for(;!u.eql(m,u.ONE);){if(u.is0(m))return u.ZERO;let g=1,p=u.sqr(m);for(;!u.eql(p,u.ONE);)if(g++,p=u.sqr(p),g===d)throw new Error(
324
- "Cannot find square root");let y=q<<BigInt(d-g-1),b=u.pow(f,y);d=g,f=u.sqr(b),m=u.mul(m,f),h=u.mul(h,b);}return h}}function ka(t){return t%Wr===Jr?Xr:t%Yr===Gr?xa:t%Zr===ya?va(t):Qr(t)}var ye=(t,e)=>(j(
325
- t,e)&q)===q,wa=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function es(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=wa.
326
- reduce((o,r)=>(o[r]="function",o),e);if(Me(t,n),ge(t.BYTES,"BYTES"),ge(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=q)throw new Error("inval\
327
- id field: expected ORDER > 1, got "+t.ORDER);return t}function Sa(t,e,n){let o=t;if(n<J)throw new Error("invalid exponent, negatives unsupported");if(n===J)return o.ONE;if(n===q)return e;let r=o.ONE,s=e;
328
- for(;n>J;)n&q&&(r=o.mul(r,s)),s=o.sqr(s),n>>=q;return r}function qt(t,e,n=false){let o=t,r=new Array(e.length).fill(n?o.ZERO:void 0),s=e.reduce((a,c,l)=>o.is0(c)?a:(r[l]=a,o.mul(a,c)),o.ONE),i=o.inv(s);return e.
329
- reduceRight((a,c,l)=>o.is0(c)?a:(r[l]=o.mul(a,r[l]),o.mul(a,c)),i),r}function Hr(t,e){let n=t,o=(n.ORDER-q)/Be,r=n.pow(e,o),s=n.eql(r,n.ONE),i=n.eql(r,n.ZERO),a=n.eql(r,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Ta(t,e){if(e!==void 0&&qn(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);
330
- let n=Gn(t);if(e!==void 0&&e<n)throw new Error(`invalid n length: expected bit length (${n}) >= n.length (${e})`);let o=e!==void 0?e:n,r=Math.ceil(o/8);return {nBitLength:o,nByteLength:r}}var Kr=new WeakMap,
331
- Ut=class{ORDER;BITS;BYTES;isLE;ZERO=J;ONE=q;_lengths;_mod;constructor(e,n={}){if(e<=q)throw new Error("invalid field: expected ORDER > 1, got "+e);let o;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
332
- BITS=="number"&&(o=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.
333
- freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:r,nByteLength:s}=Ta(e,o);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2\
334
- 048 bytes");this.ORDER=e,this.BITS=r,this.BYTES=s,Object.freeze(this);}create(e){return j(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got\
335
- "+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&q)===q}neg(e){return j(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return j(
336
- e*e,this.ORDER)}add(e,n){return j(e+n,this.ORDER)}sub(e,n){return j(e-n,this.ORDER)}mul(e,n){return j(e*n,this.ORDER)}pow(e,n){return Sa(this,e,n)}div(e,n){return j(e*qr(n,this.ORDER),this.ORDER)}sqrN(e){
337
- return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return qr(e,this.ORDER)}sqrt(e){let n=Kr.get(this);return n||Kr.set(this,n=ka(this.ORDER)),n(this,e)}toBytes(e){return this.
338
- isLE?zr(e,this.BYTES):Jn(e,this.BYTES)}fromBytes(e,n=false){z(e);let{_lengths:o,BYTES:r,isLE:s,ORDER:i,_mod:a}=this;if(o){if(e.length<1||!o.includes(e.length)||e.length>r)throw new Error("Field.fromBytes\
339
- : expected "+o+" bytes, got "+e.length);let l=new Uint8Array(r);l.set(e,s?0:l.length-e.length),e=l;}if(e.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=s?be(e):
340
- Kn(e);if(a&&(c=j(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return qt(this,e)}cmov(e,n,o){return ze(o,"condition"),o?n:e}};Object.
341
- freeze(Ut.prototype);function Ht(t,e={}){return new Ut(t,e)}var Kt=BigInt(0),to=BigInt(1);function ts(t,e){let n=e.negate();return t?n:e}function Wt(t,e){let n=qt(t.Fp,e.map(o=>o.Z));return e.map((o,r)=>t.fromAffine(o.toAffine(n[r])))}function ss(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
342
- throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Xn(t,e){ss(t,e);let n=Math.ceil(e/t)+1,o=2**(t-1),r=2**t,s=Ur(t),i=BigInt(t);return {windows:n,windowSize:o,mask:s,maxNumber:r,
343
- shiftBy:i}}function ns(t,e,n){let{windowSize:o,mask:r,maxNumber:s,shiftBy:i}=n,a=Number(t&r),c=t>>i;a>o&&(a-=s,c+=to);let l=e*o,u=l+Math.abs(a)-1,d=a===0,f=a<0,m=e%2!==0;return {nextN:c,offset:u,isZero:d,
344
- isNeg:f,isNegF:m,offsetF:l}}var Qn=new WeakMap,is=new WeakMap;function eo(t){return is.get(t)||1}function os(t){if(t!==Kt)throw new Error("invalid wNAF")}var Jt=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
345
- e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,o=this.ZERO){let r=e;for(;n>Kt;)n&to&&(o=o.add(r)),r=r.double(),n>>=to;return o}precomputeWindow(e,n){let{windows:o,windowSize:r}=Xn(n,this.bits),s=[],
346
- i=e,a=i;for(let c=0;c<o;c++){a=i,s.push(a);for(let l=1;l<r;l++)a=a.add(i),s.push(a);i=a.double();}return s}wNAF(e,n,o){if(!this.Fn.isValid(o))throw new Error("invalid scalar");let r=this.ZERO,s=this.BASE,
347
- i=Xn(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:f,offsetF:m}=ns(o,a,i);o=c,u?s=s.add(ts(f,n[m])):r=r.add(ts(d,n[l]));}return os(o),{p:r,f:s}}wNAFUnsafe(e,n,o,r=this.
348
- ZERO){let s=Xn(e,this.bits);for(let i=0;i<s.windows&&o!==Kt;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=ns(o,i,s);if(o=a,!l){let d=n[c];r=r.add(u?d.negate():d);}}return os(o),r}getPrecomputes(e,n,o){let r=Qn.
349
- get(n);return r||(r=this.precomputeWindow(n,e),e!==1&&(typeof o=="function"&&(r=o(r)),Qn.set(n,r))),r}cached(e,n,o){let r=eo(e);return this.wNAF(r,this.getPrecomputes(r,e,o),n)}unsafe(e,n,o,r){let s=eo(
350
- e);return s===1?this._unsafeLadder(e,n,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,o),n,r)}createCache(e,n){ss(n,this.bits),is.set(e,n),Qn.delete(e);}hasCache(e){return eo(e)!==1}};function rs(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return es(e),e}else return Ht(t,{isLE:n})}function as(t,e,n={},o){if(o===void 0&&(o=t==="edwar\
351
- ds"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of ["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Kt))throw new Error(`CURVE.${c} must be positive bigint`)}
352
- let r=rs(e.p,n.Fp,o),s=rs(e.n,n.Fn,o),a=["Gx","Gy","a","d"];for(let c of a)if(!r.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.
353
- freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:s}}function cs(t,e){return function(o){let r=t(o);return {secretKey:r,publicKey:e(r)}}}var Re=BigInt(0),H=BigInt(1),no=BigInt(2),Ea=BigInt(8);function Ra(t,e,n,o){let r=t.sqr(n),s=t.sqr(o),i=t.add(t.mul(e.a,r),s),a=t.add(t.ONE,t.mul(e.d,t.mul(r,s)));return t.eql(i,a)}function ls(t,e={}){
354
- let n=e,o=as("edwards",t,n,n.FpFnLE),{Fp:r,Fn:s}=o,i=o.CURVE,{h:a}=i;Me(n,{},{uvRatio:"function"});let c=no<<BigInt(s.BYTES*8)-H,l=g=>r.create(g),u=n.uvRatio===void 0?(g,p)=>{try{return {isValid:!0,value:r.
355
- sqrt(r.div(g,p))}}catch{return {isValid:false,value:Re}}}:n.uvRatio;if(!Ra(r,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(g,p,y=false){let b=y?H:Re;return Wn("coordinate "+g,p,
356
- b,c),p}function f(g){if(!(g instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,H,l(i.Gx*i.Gy));static ZERO=new m(Re,H,H,Re);static Fp=r;static Fn=s;X;Y;Z;T;constructor(p,y,b,x){
357
- this.X=d("x",p),this.Y=d("y",y),this.Z=d("z",b,true),this.T=d("t",x),Object.freeze(this);}static CURVE(){return i}static fromAffine(p){if(p instanceof m)throw new Error("extended point not allowed");let{
358
- x:y,y:b}=p||{};return d("x",y),d("y",b),new m(y,b,H,l(y*b))}static fromBytes(p,y=false){let b=r.BYTES,{a:x,d:T}=i;p=ut(z(p,b,"point")),ze(y,"zip215");let E=ut(p),R=p[b-1];E[b-1]=R&-129;let C=be(E),D=y?c:
359
- r.ORDER;Wn("point.y",C,Re,D);let I=l(C*C),S=l(I-H),B=l(T*I-x),{isValid:k,value:w}=u(S,B);if(!k)throw new Error("bad point: invalid y coordinate");let _=(w&H)===H,P=(R&128)!==0;if(!y&&w===Re&&P)throw new Error(
360
- "bad point: x=0 and x_0=1");return P!==_&&(w=l(-w)),m.fromAffine({x:w,y:C})}static fromHex(p,y=false){return m.fromBytes(jr(p),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,y=true){
361
- return h.createCache(this,p),y||this.multiply(no),this}assertValidity(){let p=this,{a:y,d:b}=i;if(p.is0())throw new Error("bad point: ZERO");let{X:x,Y:T,Z:E,T:R}=p,C=l(x*x),D=l(T*T),I=l(E*E),S=l(I*I),
362
- B=l(C*y),k=l(I*l(B+D)),w=l(S+l(b*l(C*D)));if(k!==w)throw new Error("bad point: equation left != right (1)");let _=l(x*T),P=l(E*R);if(_!==P)throw new Error("bad point: equation left != right (2)")}equals(p){
363
- f(p);let{X:y,Y:b,Z:x}=this,{X:T,Y:E,Z:R}=p,C=l(y*R),D=l(T*x),I=l(b*R),S=l(E*x);return C===D&&I===S}is0(){return this.equals(m.ZERO)}negate(){return new m(l(-this.X),this.Y,this.Z,l(-this.T))}double(){
364
- let{a:p}=i,{X:y,Y:b,Z:x}=this,T=l(y*y),E=l(b*b),R=l(no*l(x*x)),C=l(p*T),D=y+b,I=l(l(D*D)-T-E),S=C+E,B=S-R,k=C-E,w=l(I*B),_=l(S*k),P=l(I*k),N=l(B*S);return new m(w,_,N,P)}add(p){f(p);let{a:y,d:b}=i,{X:x,
365
- Y:T,Z:E,T:R}=this,{X:C,Y:D,Z:I,T:S}=p,B=l(x*C),k=l(T*D),w=l(R*b*S),_=l(E*I),P=l((x+T)*(C+D)-B-k),N=_-w,V=_+w,O=l(k-y*B),X=l(P*N),$=l(V*O),Q=l(P*O),W=l(N*V);return new m(X,$,W,Q)}subtract(p){return f(p),
366
- this.add(p.negate())}multiply(p){if(!s.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:b}=h.cached(this,p,x=>Wt(m,x));return Wt(m,[y,b])[0]}multiplyUnsafe(p){
367
- if(!s.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===Re?m.ZERO:this.is0()||p===H?this:h.unsafe(this,p,y=>Wt(m,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){
368
- return h.unsafe(this,i.n).is0()}toAffine(p){let y=this,b=p,{X:x,Y:T,Z:E}=y,R=y.is0();b==null&&(b=R?Ea:r.inv(E));let C=l(x*b),D=l(T*b),I=r.mul(E,b);if(R)return {x:Re,y:H};if(I!==H)throw new Error("invZ \
369
- was invalid");return {x:C,y:D}}clearCofactor(){return a===H?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y}=this.toAffine(),b=r.toBytes(y);return b[b.length-1]|=p&H?128:0,b}toHex(){return Hn(this.toBytes())}toString(){
370
- return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let h=new Jt(m,s.BITS);return s.BITS>=8&&m.BASE.precompute(8),Object.freeze(m.prototype),Object.freeze(m),m}var Gt=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){
371
- this.ep=e;}static fromBytes(e){Yn();}static fromHex(e){Yn();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){
372
- return this.ep.toAffine(e)}toHex(){return Hn(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){
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.
388
+ 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){
373
429
  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.
374
- ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function us(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is r\
375
- equired');let o=e,r=n;Me(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=r,{BASE:i,Fp:a,Fn:c}=t,l=o.
376
- outputLen,u=2*a.BYTES;if(l!==void 0&&(ge(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=r.randomBytes===void 0?$r:r.randomBytes,f=r.adjustScalarBytes===void 0?
377
- k=>k:r.adjustScalarBytes,m=r.domain===void 0?(k,w,_)=>{if(ze(_,"phflag"),w.length||_)throw new Error("Contexts/pre-hash are not supported");return k}:r.domain;function h(k){return c.create(be(k))}function g(k){
378
- let w=C.secretKey;z(k,C.secretKey,"secretKey");let _=z(o(k),2*w,"hashedSecretKey"),P=f(_.slice(0,w)),N=_.slice(w,2*w),V=h(P);return {head:P,prefix:N,scalar:V}}function p(k){let{head:w,prefix:_,scalar:P}=g(
379
- k),N=i.multiply(P),V=N.toBytes();return {head:w,prefix:_,scalar:P,point:N,pointBytes:V}}function y(k){return p(k).pointBytes}function b(k=Uint8Array.of(),...w){let _=le(...w);return h(o(m(_,z(k,void 0,
380
- "context"),!!s)))}function x(k,w,_={}){k=z(k,void 0,"message"),s&&(k=s(k));let{prefix:P,scalar:N,pointBytes:V}=p(w),O=b(_.context,P,k),X=i.multiply(O).toBytes(),$=b(_.context,X,V,k),Q=c.create(O+$*N);
381
- if(!c.isValid(Q))throw new Error("sign failed: invalid s");let W=le(X,c.toBytes(Q));return z(W,C.signature,"result")}let T={zip215:r.zip215};function E(k,w,_,P=T){let{context:N}=P,V=P.zip215===void 0?
382
- !!T.zip215:P.zip215,O=C.signature;k=z(k,O,"signature"),w=z(w,void 0,"message"),_=z(_,C.publicKey,"publicKey"),V!==void 0&&ze(V,"zip215"),s&&(w=s(w));let X=O/2,$=k.subarray(0,X),Q=be(k.subarray(X,O)),W,
383
- ue,ve;try{W=t.fromBytes(_,V),ue=t.fromBytes($,V),ve=i.multiplyUnsafe(Q);}catch{return false}if(!V&&W.isSmallOrder())return false;let ke=b(N,$,_,w);return ue.add(W.multiplyUnsafe(ke)).subtract(ve).clearCofactor().
384
- is0()}let R=a.BYTES,C={secretKey:R,publicKey:R,signature:2*R,seed:R};function D(k){return k=k===void 0?d(C.seed):k,z(k,C.seed,"seed")}function I(k){return zt(k)&&k.length===C.secretKey}function S(k,w){
385
- try{return !!t.fromBytes(k,w===void 0?T.zip215:w)}catch{return false}}let B={getExtendedPublicKey:p,randomSecretKey:D,isValidSecretKey:I,isValidPublicKey:S,toMontgomery(k){let{y:w}=t.fromBytes(k),_=C.publicKey,
386
- P=_===32;if(!P&&_!==57)throw new Error("only defined for 25519 and 448");let N=P?a.div(H+w,H-w):a.div(w-H,w+H);return a.toBytes(N)},toMontgomerySecret(k){let w=C.secretKey;z(k,w);let _=o(k.subarray(0,
387
- w));return f(_).subarray(0,w)}};return Object.freeze(C),Object.freeze(B),Object.freeze({keygen:cs(D,y),getPublicKey:y,sign:x,verify:E,utils:B,Point:t,lengths:C})}var Oa=BigInt(0),xe=BigInt(1),ps=BigInt(2);var _a=BigInt(5),Aa=BigInt(8),Ve=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ao={p:Ve,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Aa,
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,
388
444
  a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
389
- c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Da(t){let e=BigInt(10),n=BigInt(20),o=BigInt(40),r=BigInt(80),s=Ve,a=t*t%
390
- s*t%s,c=re(a,ps,s)*a%s,l=re(c,xe,s)*t%s,u=re(l,_a,s)*l%s,d=re(u,e,s)*u%s,f=re(d,n,s)*d%s,m=re(f,o,s)*f%s,h=re(m,r,s)*m%s,g=re(h,r,s)*m%s,p=re(g,e,s)*u%s;return {pow_p_5_8:re(p,ps,s)*t%s,b2:a}}function Pa(t){
391
- return t[0]&=248,t[31]&=127,t[31]|=64,t}var ro=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function co(t,e){let n=Ve,o=j(e*e*e,n),r=j(o*o*e,n),s=Da(t*r).pow_p_5_8,
392
- i=j(t*o*s,n),a=j(e*i*i,n),c=i,l=j(i*ro,n),u=a===t,d=a===j(-t,n),f=a===j(-t*ro,n);return u&&(i=c),(d||f)&&(i=l),ye(i,n)&&(i=j(-i,n)),{isValid:u||d,value:i}}var Ie=ls(ao,{uvRatio:co}),Ce=Ie.Fp,hs=Ie.Fn;function La(t){return us(Ie,jt,Object.assign({adjustScalarBytes:Pa,zip215:true},t))}var gs=La({});var so=ro;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Ba=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
393
- "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var fs=t=>co(xe,t),$a=BigInt("0x7\
394
- fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),io=t=>Ce.create(be(t)&$a);var Oe=class t extends Gt{static BASE=new t(
395
- Ie.BASE);static ZERO=new t(Ie.ZERO);static Fp=Ce;static Fn=hs;constructor(e){super(e);}static fromAffine(e){return new t(Ie.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoP\
396
- oint expected")}init(e){return new t(e)}static fromBytes(e){oe(e,32);let{a:n,d:o}=ao,r=Ve,s=T=>Ce.create(T),i=io(e);if(!Vr(Ce.toBytes(i),e)||ye(i,r))throw new Error("invalid ristretto255 encoding 1");
397
- let a=s(i*i),c=s(xe+n*a),l=s(xe-n*a),u=s(c*c),d=s(l*l),f=s(n*o*u-d),{isValid:m,value:h}=fs(s(f*d)),g=s(h*l),p=s(h*g*f),y=s((i+i)*g);ye(y,r)&&(y=s(-y));let b=s(c*p),x=s(y*b);if(!m||ye(x,r)||b===Oa)throw new Error(
398
- "invalid ristretto255 encoding 2");return new t(new Ie(y,b,xe,x))}static fromHex(e){return t.fromBytes(at(e))}toBytes(){let{X:e,Y:n,Z:o,T:r}=this.ep,s=Ve,i=p=>Ce.create(p),a=i(i(o+n)*i(o-n)),c=i(e*n),
399
- l=i(c*c),{value:u}=fs(i(a*l)),d=i(u*a),f=i(u*c),m=i(d*f*r),h;if(ye(r*m,s)){let p=i(n*so),y=i(e*so);e=p,n=y,h=i(d*Ba);}else h=f;ye(e*m,s)&&(n=i(-n));let g=i((o-n)*h);return ye(g,s)&&(g=i(-g)),Ce.toBytes(
400
- g)}equals(e){this.assertSame(e);let{X:n,Y:o}=this.ep,{X:r,Y:s}=e.ep,i=l=>Ce.create(l),a=i(n*s)===i(o*r),c=i(o*s)===i(n*r);return a||c}is0(){return this.equals(t.ZERO)}};Object.freeze(Oe.BASE);Object.freeze(
401
- Oe.ZERO);Object.freeze(Oe.prototype);Object.freeze(Oe);var bs=`-----BEGIN PUBLIC KEY-----
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-----
402
458
  MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
403
- -----END PUBLIC KEY-----`;function ys(t){let e=atob(t),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n}function lo(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.
404
- length%4?"=".repeat(4-e.length%4):"";return ys(e+n)}function za(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=ys(e);return n.subarray(n.length-32)}var Va=new TextEncoder,xs=new TextDecoder;
405
- function Ua(t){return typeof t=="object"&&t!==null&&"keys"in t}function Ue(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 qa=/^[A-Za-z0-9_-]+$/;
406
- function vs(t){let e=t.split(".");return e.length===3&&e.every(n=>qa.test(n))}function uo(t){return t===""?"empty":vs(t)?"token":"malformed"}function po(t,e){if(!vs(t))return {ok:false,reason:"malformed t\
407
- oken"};let n=t.split("."),o=n[0],r=n[1],s=n[2],i;try{i=JSON.parse(xs.decode(lo(o)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(Ua(e)){let u=typeof i.kid=="string"?i.kid:e.defaultKid,
408
- d=e.keys[u];if(!d)return {ok:false,reason:`unknown key id "${u}"`};a=d;}else {if(!e)return {ok:false,reason:"no verification key"};a=e;}let c;try{if(c=za(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
409
- return {ok:false,reason:"invalid public key"}}let l=false;try{l=gs.verify(lo(s),Va.encode(`${o}.${r}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:i,payloadBytes:lo(r)}:
410
- {ok:false,reason:"bad signature"}}function qe(t,e){let n=po(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(xs.decode(
411
- n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function fo(t,e,n){if(n?.has(t.jti))return "revoked";let o=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"\
412
- active":e<=o?"grace":"expired"}function zd(t,e,n={}){let o=Ue(t);if(uo(o)==="empty")return {status:"none",reason:"empty"};let s=qe(o,e);if(!s.signatureValid||!s.payload)return {status:"invalid",...s.reason?
413
- {reason:s.reason}:{}};let i=s.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),c=fo(i,a,n.revoked);return c==="revoked"?{status:c,payload:i,reason:"license revoked"}:{status:c,payload:i}}var ks="BVSALA-REVOC",Ha=300,Ka=new TextDecoder;function ws(t,e,n={}){let o=l=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:l}),r=po(t,e);if(!r.ok||!r.payloadBytes)return o(r.reason??"bad signature");
414
- if(r.header?.typ!==ks)return o(`unexpected token type "${String(r.header?.typ??"")}" (want ${ks})`);let s;try{s=JSON.parse(Ka.decode(r.payloadBytes));}catch{return o("payload is not valid JSON")}if(typeof s.
415
- seq!="number"||typeof s.asOf!="number"||!Array.isArray(s.revoked))return o("malformed revocation payload");let i=n.minSeq??0;if(s.seq<i)return o(`stale/rolled-back list (seq ${s.seq} < ${i})`);let a=n.
416
- nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??Ha;return s.asOf>a+c?o(`asOf too far in the future (${s.asOf} > ${a+c})`):{ok:true,seq:s.seq,asOf:s.asOf,revoked:new Set(s.revoked)}}var He=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
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(){
417
473
  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.
418
- 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 o=this.set.size>n,r=e.seq>this._seq;return e.seq>this._seq&&(this._seq=e.seq),e.asOf>this._asOf&&
419
- (this._asOf=e.asOf),o||r}};function Yt(t,e,n){let o=()=>Math.floor((n.now?n.now():Date.now())/1e3),r=n.startedAt??o(),s=Ue(t),i=uo(s),a=i==="token"?qe(s,e):{signatureValid:false,reason:i},c=a.signatureValid?a.payload:void 0,l=new Set(
420
- c?.features??[]),u=()=>{if(i==="empty")return "none";if(!c)return "invalid";let f=fo(c,o(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(f==="active"||f==="grace")){let m=c.expires_at+c.grace_days*
421
- 86400,h=Math.min(r,m),g=Math.max(n.revocation.lastContactAt,h);if(o()-g>n.maxStalenessSeconds)return "stale"}return f},d=()=>{let f=u();return f==="active"||f==="grace"};return {isEntitled:f=>d()&&l.has(
422
- f),isActive:()=>d(),status:u,reason:()=>c?void 0:a.reason,refreshAfter:()=>{if(c)return Math.min(c.expires_at,o()+86400)}}}function Ss(t,e,n){return Yt(t,e,{revocation:new He,...n?{now:n}:{}})}var Ke={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Ts=3,Ja=12;function Wa(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
423
- 0){let r=Math.pow(2,Math.min(t.consecutiveFailures,4));n=Math.min(t.maxIntervalSeconds,t.floorSeconds*r);}else {let r=t.refreshAfter!=null?t.refreshAfter-t.nowSeconds:t.pollIntervalSeconds,s=r<0?t.pollIntervalSeconds:
424
- r;n=Math.min(t.pollIntervalSeconds,Math.max(t.floorSeconds,s));}let o=1+(e()*2-1)*t.jitterRatio;return Math.max(t.floorSeconds,n*o)}var Ga=10,Zt=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;warnedNoFetch=false;lastEtag=null;consecutive304=0;now(){
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(){
425
481
  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();
426
482
  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.
427
- onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let o=this.opts.requestTimeoutMs??Ke.requestTimeoutMs,r=setTimeout(()=>n.abort(),o);r.unref?.();let s={accept:"applicati\
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\
428
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.
429
- now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=Ga&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!i.
430
- 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 l=ws(c.list,this.opts.
431
- publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??Ke.maxSkewSeconds});if(!l.ok){let d=l.reason??"rejected";this.opts.onEvent?.({type:"rejected",
432
- reason:d}),this.avisar(`rechazada:${d}`,`[bv-sala] la lista de revocaciones NO verifica (${d}). Se mantiene la \xFAltima buena conocida, as\xED que las revocaciones YA conocidas se siguen aplicando, pero la\
433
- s nuevas no llegan. Revise ${this.opts.url}.`);return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let u=this.opts.snapshot.apply(l);this.opts.onEvent?.(u?{type:"applied",seq:l.seq,
434
- size:this.opts.snapshot.snapshot().size}:{type:"unchanged",seq:l.seq});}catch(i){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:i}),this.avisarFalloDeRed(i);}finally{clearTimeout(r),
435
- this.controller=null;}}callado(){return !!(this.opts.silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||G(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;
436
- let n=this.consecutiveFailures;if(n<Ts||(n-Ts)%Ja!==0)return;let o=e instanceof Error?e.message:String(e);console.warn(`[bv-sala] no se ha podido contactar con el servidor de revocaciones ${n} veces s\
437
- eguidas (${o}). La licencia SIGUE funcionando y las revocaciones ya conocidas se siguen aplicando, pero las NUEVAS no est\xE1n llegando. Compruebe la salida hacia ${this.opts.url}.`);}start(){this.started||
438
- this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)return;let e=Wa({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.
439
- consecutiveFailures,floorSeconds:this.opts.floorSeconds??Ke.floorSeconds,pollIntervalSeconds:this.opts.pollIntervalSeconds??Ke.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??Ke.maxIntervalSeconds,
440
- jitterRatio:this.opts.jitterRatio??Ke.jitterRatio,...this.opts.random?{random:this.opts.random}:{}});this.timer=setTimeout(()=>{this.pollOnce().finally(()=>this.schedule());},e*1e3),this.timer.unref?.();}stop(){
441
- this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.controller?.abort();}};var pt=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=
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",
488
+ 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\
493
+ 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.
496
+ 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=
442
498
  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.
443
499
  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.
444
500
  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??
445
- Math.ceil(this.maxBuffer/this.maxBatch)+4,o=0;for(let r=0;r<n&&this.buffer.length>0;r++){let s=this.buffer.length;if(await this.flush(),o=this.buffer.length>=s?o+1:0,o>=2)break}}async flush(){if(this.
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.
446
502
  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.
447
- fetch;if(!e)return;let n=this.buffer.splice(0,this.maxBatch);try{let o=n.map(s=>this.toWire(s)),r=await e(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bear\
448
- er ${this.options.serviceAccountKey}`,[$o]:`${this.options.surface??"sdk"}/${mn}`},body:JSON.stringify(o)});r.ok?this.fallosSeguidos=0:r.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
449
- `el servidor respondi\xF3 ${r.status}`)):r.status===401||r.status===403?(G(`metering-auth-${r.status}`,`[bv-sala] el env\xEDo de uso est\xE1 siendo rechazado con HTTP ${r.status} en ${this.options.url}\
450
- . Revisa 'serviceAccountKey' (\xBFrotada? \xBFrevocada? \xBFde otra organizaci\xF3n?). Mientras no funcione NO se reporta uso: el panel dir\xE1 que no ve tr\xE1fico y los asientos facturables saldr\xE1n a cero.`),
451
- this.options.onAuthError?.(r.status)):(this.fallosSeguidos++,this.avisarDeFallo(r.status===404||r.status===405?`HTTP ${r.status}: la URL de env\xEDo parece equivocada`:`el servidor rechaz\xF3 el lote con\
452
- HTTP ${r.status}`));}catch(o){this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(o instanceof Error?o.message:"error de red");}}avisarDeFallo(e){if(this.options.silenceWarnings)return;let n=this.
453
- fallosSeguidos;n<3||(n-3)%12!==0||console.warn(`[bv-sala] el env\xEDo de uso lleva ${n} intentos seguidos fallando contra ${this.options.url} (${e}). Las peticiones SIGUEN funcionando, pero el uso no \
454
- est\xE1 llegando: el panel dir\xE1 que no ve tr\xE1fico y los asientos facturables saldr\xE1n a cero. Comprueba 'meteringUrl' \u2014 por defecto es \`\${licenseServerUrl}/api/metering/usage\`.`);}requeue(e){
455
- this.buffer=[...e,...this.buffer],this.buffer.length>this.maxBuffer&&(this.buffer.length=this.maxBuffer);}toWire(e){let n=e.report;return {orgId:this.options.orgId??"self",...this.seatId?{seatId:this.seatId}:
456
- {},...this.ci?{ci:true}:{},requestId:n.requestId,model:n.model,at:e.at,avoidedLlm:n.calls.avoidedLlm,actualLlm:n.calls.actualLlm,baselineInputTokens:n.tokens.baselineInput,actualInputTokens:n.tokens.actualInput,
457
- eliminatedInputTokens:n.tokens.eliminatedInput,compressedInputTokens:n.tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutputTokens:n.tokens.actualOutput,providerCachedInputTokens:n.
458
- tokens.providerCachedInput??0,cacheResult:n.cache.result,...n.cost.eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>
459
- 0?{eliminatedInputFloorCost:n.cost.eliminatedInputFloorCost}:{},baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{},...n.
460
- attribution?.sessionId?{sessionId:n.attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function Xt(){return globalThis.process}function Ya(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\
461
- ]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function Za(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??
462
- t.NETLIFY)}async function Xa(){if(Xt()?.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 Qa(t,e=Xa){
463
- if(t.KUBERNETES_SERVICE_HOST||Za(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||Ya(n)))return n}async function ec(){let t=Xt();if(!t||!t.env)return;let e=t.env,n=await Qa(e),o=[t.platform,
464
- t.arch,t.execPath,n,e.USER??e.USERNAME??e.LOGNAME,e.HOME??e.USERPROFILE].filter(r=>typeof r=="string"&&r.length>0);return o.length?o.join("|"):void 0}var tc=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
465
- ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function mo(){let t=Xt()?.env;if(!t)
466
- return false;for(let e of tc){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function nc(t,e){let n=globalThis.crypto,o=new TextEncoder;if(n?.subtle)try{let i=await n.subtle.importKey("raw",
467
- o.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",i,o.encode(e));return [...new Uint8Array(a)].map(c=>c.toString(16).padStart(2,"0")).join("")}catch{}let r=2166136261,s=`${t}\
468
- |${e}`;for(let i=0;i<s.length;i++)r^=s.charCodeAt(i),r=Math.imul(r,16777619);return (r>>>0).toString(16).padStart(8,"0")}async function ho(t){let n=Xt()?.env?.BVSALA_SEAT_ID;if(n&&oc.test(n))return n;let o=await ec();
469
- if(!o)return;let r=await nc(t,o);if(r)return `m-${r.slice(0,32)}`}var oc=/^[A-Za-z0-9._:/-]{1,128}$/;var Es={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function Rs(t){return {exactCache:t.exactCache??new kt,semanticCache:t.semanticCache,singleflight:t.singleflight??new wt,resolvers:t.resolvers??Zo(),router:t.router??new St,toolSelector:t.toolSelector??
470
- new Tt,formatSelector:t.formatSelector??new It({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new Ot,constraintBackends:t.constraintBackends??[]}}var rc=36e5,sc=7*86400,ic=3e4,Qt=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;avisadoDeCredencial=false;currentExpiresAt;currentOrg;constructor(e){this.opts=
471
- e,this.pollIntervalMs=e.pollIntervalMs??rc,this.refreshLeadSeconds=e.refreshLeadSeconds??sc;let n=qe(Ue(e.initialToken),e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.expires_at:
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\
506
+ 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
+ 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
+ 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||
509
+ console.warn(`[bv-sala] usage reporting has failed ${n} times in a row against ${this.options.url} (${e}). Requests keep working, but usage is not arriving: the dashboard will say it sees no traffic a\
510
+ nd billable seats will show zero. Check 'meteringUrl' \u2014 by default it is \`\${licenseServerUrl}/api/metering/usage\`.`);}requeue(e){this.buffer=[...e,...this.buffer],this.buffer.length>this.maxBuffer&&
511
+ (this.buffer.length=this.maxBuffer);}toWire(e){let n=e.report;return {orgId:this.options.orgId??"self",...this.seatId?{seatId:this.seatId}:{},...this.ci?{ci:true}:{},requestId:n.requestId,model:n.model,at:e.
512
+ at,avoidedLlm:n.calls.avoidedLlm,actualLlm:n.calls.actualLlm,baselineInputTokens:n.tokens.baselineInput,actualInputTokens:n.tokens.actualInput,eliminatedInputTokens:n.tokens.eliminatedInput,compressedInputTokens:n.
513
+ tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutputTokens:n.tokens.actualOutput,providerCachedInputTokens:n.tokens.providerCachedInput??0,cacheResult:n.cache.result,...n.cost.
514
+ eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.cost.eliminatedInputFloorCost}:
515
+ {},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
+ 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:
472
529
  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=
473
530
  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.
474
531
  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??
475
- ic);n.unref?.();try{let r=await(this.opts.fetchImpl??globalThis.fetch.bind(globalThis))(this.opts.url,{signal:e.signal,headers:{authorization:`Bearer ${this.opts.serviceAccountKey}`,accept:"applicatio\
476
- n/json"}});if(!r.ok)return (r.status===401||r.status===403||r.status===404)&&!this.avisadoDeCredencial&&(this.avisadoDeCredencial=!0,console.warn(`[bv-sala] la recogida autom\xE1tica de la licencia renova\
477
- da falla con HTTP ${r.status} en ${this.opts.url}. Revisa 'serviceAccountKey' (\xBFrotada? \xBFde otra organizaci\xF3n?) y 'licenseServerUrl': mientras no funcione, el token NO se renovar\xE1 solo y el SDK dejar\xE1\
478
- de operar al terminar el periodo de gracia.`)),!1;let s=await r.json();if(typeof s.token!="string")return !1;let i=Ue(s.token),a=qe(i,this.opts.publicKey);return !a.signatureValid||!a.payload||a.payload.
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\
533
+ 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
+ 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.
479
536
  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.
480
- 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 go={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},Cs={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},ac=[["claude-fable-5-1",512],["claude-mytho\
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.\
538
+ 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\
481
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",
482
- 2048]];function bo(t){for(let[e,n]of ac)if(t===e||t.startsWith(`${e}-`))return {...Cs,minimumCacheTokens:n};return Cs}var yo={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1};var Is={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function en(t,e,n,o){let r=o.minimumCacheTokens;if(r==null||t<r)return t;let s=Math.min(e,t),i=t-s,a=Math.min(1,Math.max(0,
483
- n)),c=a*s*o.cacheReadMultiplier+(1-a)*s*o.cacheWriteMultiplier;return i+c}function xo(t){let e=en(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=en(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??
484
- 0),o=e-n,r=t.tier.minimumCacheTokens,i=r!=null&&t.originalTokens>=r&&t.compressedTokens<r,a;if(o<=0){let c=e<t.originalTokens;a=i?`compressing drops the prompt out of the cacheable tier (${t.compressedTokens}\
485
- < ${r}) 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*
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*
486
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\
487
- es not touch the cache tier";return {comprimir:o>0,costeComprimido:n,costeSinComprimir:e,ganancia:o,razon:a}}function Os(t){let e=r=>xo({...t,prefixHitRate:r}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,
488
- o=1;for(let r=0;r<40;r++){let s=(n+o)/2;e(s)>0?n=s:o=s;}return (n+o)/2}function cc(t){let e=Os({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(en(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.
489
- totalTokens?null:1)}var tn=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-
490
- 1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let o=cc(n),r=this.estados.get(e),s=lc(r);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:o,observada:s}:o==null?
491
- {marcar:true,razon:"marking cannot lose money at this tier (no write premium)",umbral:o,observada:s}:r?.apagada?{marcar:false,razon:`prefix-cache marking OFF: measured hit rate ${Je(s)} did not reach the ${Je(
492
- o)} break-even, so marking was costing money`,umbral:o,observada:s}:r==null||r.marcadas<this.exploracion?{marcar:true,razon:`exploring the prefix cache (${r?.marcadas??0}/${this.exploracion}); hit rate \
493
- is only observable on requests that were marked`,umbral:o,observada:s}:s!=null&&s>o?{marcar:true,razon:`measured hit rate ${Je(s)} beats the ${Je(o)} break-even`,umbral:o,observada:s}:(r.apagada=true,{marcar:false,
494
- razon:`prefix-cache marking OFF: measured hit rate ${Je(s)} did not reach the ${Je(o)} break-even, so marking was costing money`,umbral:o,observada:s})}registrar(e,n){let o=this.estados.get(e)??{marcadas:0,
495
- tokensLeidos:0,tokensEscritos:0,apagada:false};o.marcadas+=1,o.tokensLeidos+=Math.max(0,n.cachedInputTokens??0),o.tokensEscritos+=Math.max(0,n.cacheWriteInputTokens??0),this.estados.set(e,o);}};function lc(t){
496
- if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function Je(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var _s=.5;function uc(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function dc(t){return 1-t}function pc(t,e=_s){return e-t}function As(t,e,n=_s){
497
- if(!t||!e)return null;let o=uc(t,e);if(o==null||!Number.isFinite(o))return null;let r=dc(o),s=pc(o,n),i=s>0,a=c=>`${(c*100).toFixed(1)}%`;return {r:o,equilibrio:r,escaladoMaximo:s,viable:i,razon:i?`the\
498
- cheap model costs ${a(o)} of the strong one, so routing pays off while escalations stay under ${a(s)} (it stops saving money at ${a(r)})`:`the cheap model costs ${a(o)} of the strong one: even with z\
499
- ero escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var vo={"gpt-4":"gpt-4o","gpt-4-turbo":"gpt-4o-mini","gpt-4o":"gpt-4o-mini","gpt-4.1":"gpt-4.1-mini","c\
500
- laude-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 fc(t){return Object.keys(t).sort((e,n)=>n.length-
501
- e.length||e.localeCompare(n))}function Ds(t,e=vo){if(!t)return null;let n=t.lastIndexOf("/"),o=n>=0?t.slice(0,n+1):"",r=n>=0?t.slice(n+1):t,s=e[t]??e[r]??mc(r,e);return !s||s===r?null:o+s}function mc(t,e){
502
- for(let n of fc(e))if(t.startsWith(n)&&t.charAt(n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var nn=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(
503
- e)}decidir(e,n){let o=this.estados.get(e),r=hc(o),s=o?.enrutadas??0,i=a=>a==null?"n/a":`${(a*100).toFixed(1)}%`;return o?.apagada?{enrutar:false,razon:`model cascade OFF for this workload: measured escal\
504
- ation rate ${i(r)} is at or above the ${i(n.equilibrio)} break-even, so routing was costing money`,observada:r,muestras:s}:s<this.exploracion?{enrutar:true,razon:`measuring this workload (${s}/${this.exploracion}\
505
- ); the escalation rate is only observable on requests that were actually routed`,observada:r,muestras:s}:r!=null&&r<n.equilibrio?{enrutar:true,razon:`measured escalation rate ${i(r)} stays under the ${i(
506
- n.equilibrio)} break-even (this is a MONEY check, not a quality one)`,observada:r,muestras:s}:(o&&(o.apagada=true),{enrutar:false,razon:`model cascade OFF for this workload: measured escalation rate ${i(r)}\
507
- is at or above the ${i(n.equilibrio)} break-even, so routing was costing money`,observada:r,muestras:s})}registrar(e,n){let o=this.estados.get(e)??{enrutadas:0,escaladas:0,apagada:false};o.enrutadas+=1,
508
- n&&(o.escaladas+=1),this.estados.set(e,o);}};function hc(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var gc=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function bc(t){return t?ko(t)?"value-constrained":"structural":"none"}function ko(t,e=0){if(e>12)return false;let n=t;
509
- for(let o of gc)if(n[o]!==void 0)return true;if(t.properties){for(let o of Object.values(t.properties))if(ko(o,e+1))return true}return !!(t.items&&ko(t.items,e+1))}function Ps(t){let e=bc(t.schema),n=(t.tools??
510
- []).filter(o=>o.risk==="write"||o.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\
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??
574
+ []).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\
511
575
  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\
512
576
  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 \
513
- content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function wo(t){let e=[];if(e.push("non-empty"),t.texto.trim()==="")return {acepta:false,
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,
514
578
  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 \
515
579
  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\
516
580
  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,
517
- motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let o=ae(n,t.schema);return o.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
518
- acepta:false,motivo:`the cheap model's answer does not satisfy the output contract (${o.errors.slice(0,3).map(s=>`${s.path}: ${s.message}`).join("; ")})`,comprobaciones:e}}function Ls(t,e){let n,o;try{n=
519
- JSON.parse(t),o=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let r=on(n),s=on(o);return r.length===0&&s.length===0?{divergen:false,motivo:"no comparab\
520
- le facts (free prose only)"}:xc(r,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 \
521
- of a false valid \u2014 it is a reason to look, never a verdict"}}var yc=40;function on(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\
522
- an")n.push(`b:${t}`);else if(typeof t=="string"){let o=t.trim();o.length>0&&o.length<=yc&&n.push(`s:${o.toLowerCase()}`);}else if(Array.isArray(t))for(let o of t)on(o,e+1,n);else if(t&&typeof t=="objec\
523
- t")for(let o of Object.keys(t).sort())on(t[o],e+1,n);return n.sort()}function xc(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 Ms="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\
524
- , because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function vc(t){if(t<=0)return "";let e=Ms;for(;e.length<t;)e+=Ms;return e.slice(
525
- 0,t)}function kc(t){let e=t[0],n=-1;for(let o of t){let r=JSON.stringify(o)?.length??0;r>n&&(n=r,e=o);}return e}function So(t){if(t.enum&&t.enum.length>0)return {valor:kc(t.enum)};switch(t.type??(t.properties?
526
- "object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:vc(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?
527
- {valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=So(t.items);return n?{valor:Array.from({length:t.maxItems},()=>n.valor)}:void 0}case "ob\
528
- ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[o,r]of Object.entries(t.properties)){let s=So(r);if(!s)return;n[o]=s.valor;}return {valor:n}}default:return}}function wc(t){let e=So(
529
- t);return e?JSON.stringify(e.valor):null}function Bs(t,e){let n=wc(t);return n===null?null:e(n)}var rn=16,Ns=64,Sc=8,Tc="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 js(t,e,n,o={}){
530
- let r=o.minimumSavingsTokens??Sc,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=Io(t,0);}catch(S){return {applied:false,reason:S instanceof
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
531
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;
532
- if(!i)return {applied:false,reason:"nothing to compact"};let a=S=>We(S,i,true),c=S=>We(S,i,false),l=_c(t),u=Ec(t,s.compact,i,l);if(!u.ok)return {applied:false,reason:u.reason};let d=e(JSON.stringify(t)),f=e(JSON.stringify(
533
- s.compact)),m=d-f,h=Number.POSITIVE_INFINITY;for(let S of l){let B=e(JSON.stringify(S))-e(JSON.stringify(a(S)));B<h&&(h=B);}Number.isFinite(h)||(h=0);let g=S=>S/1e3*n.inputPer1k,p=S=>S/1e3*n.outputPer1k,
534
- y=g(r),b=n.outputPer1k>0?(r-m)*n.inputPer1k/n.outputPer1k:Number.NEGATIVE_INFINITY,x=Number.isFinite(b)?b.toFixed(1):"any",T=n.inputPer1k>0?`${(n.outputPer1k/n.inputPer1k).toFixed(1)}x`:"more than",E=o.
535
- evidencia;if(E==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\
536
- e model, not of the schema: ${Tc}. Here the compact contract saves ${m} input tokens and output is billed ${T} input, so it only pays while the output delta stays above ${x} tokens. Measure yours (ben\
537
- chmarks/ab-live.ts) and pass it in`};let R=E.deltaTokens;if(R<0)return {applied:false,reason:`the measured output delta is ${R} tokens: this model writes MORE from a compact contract (${E.procedencia}). T\
538
- he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${T} input, so no schema is big enough to buy it back`};let C=g(m)+p(R),D=n.inputPer1k>0?C*1e3/
539
- n.inputPer1k:m,I=`+${R} tokens (${R>0?"the model wrote LESS":"no measured change"}), ${E.procedencia}`;return C<y?{applied:false,reason:`net saving $${C.toFixed(9)}/request is below the floor of ${r} inp\
540
- ut tokens ($${y.toFixed(9)}): the compact contract saves ${m} input tokens and the measured output delta is ${I}; break-even at ${x}`}:{applied:true,reason:`net saving $${C.toFixed(9)}/request (${D.toFixed(
541
- 1)} input tokens equivalent): the compact contract saves ${m} input tokens and the measured output delta is ${I}; break-even at ${x}`,plan:{compactSchema:s.compact,expand:c,compact:a,renamedKeys:s.renamed,
542
- codedEnumValues:s.coded,schemaTokensOriginal:d,schemaTokensCompact:f,modelledShapeSavingTokens:h,measuredOutputDeltaTokens:R,outputDeltaProvenance:E.procedencia,breakEvenOutputDeltaTokens:b,netSavingUsd:C}}}
543
- function Ec(t,e,n,o){for(let r of o){if(!ae(r,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let s=We(r,n,true);if(!ae(s,e).valid)return {
544
- ok:false,reason:"compact witness does not validate against the compact schema"};if(!Co(We(s,n,false),r))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function $s(t){return t.type==="ob\
545
- ject"||t.type==null&&t.properties!=null}function Fs(t){return t.type==="array"||t.type==null&&t.items!=null}function Rc(t){let e=t.enum;return !e||e.length===0||e.length>Ns||!e.every(n=>typeof n=="stri\
546
- ng")?null:e}function Io(t,e){if(e>rn)throw new RangeError("schema too deep");let n=Rc(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let o=zs(n,true);if(!o)return {compact:t,renamed:0,
547
- coded:0};let r=[...o].filter(([i,a])=>i!==a).length;if(r===0)return {compact:t,renamed:0,coded:0};let s=new Map;for(let[i,a]of o)s.set(a,i);return {compact:{...t,enum:n.map(i=>o.get(i))},node:{enumFwd:o,
548
- enumBack:s},renamed:0,coded:r}}return $s(t)?Cc(t,e):Fs(t)?Ic(t,e):{compact:t,renamed:0,coded:0}}function Cc(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};
549
- let o=0,r=0,s=new Map,i=new Map;for(let[f,m]of n){let h=Io(m,e+1);i.set(f,h.compact),h.node&&s.set(f,h.node),o+=h.renamed,r+=h.coded;}let a=null;t.additionalProperties===false&&(a=zs(n.map(([f])=>f),false));
550
- let c={};for(let[f]of n)c[a?.get(f)??f]=i.get(f);let l={...t,properties:c};t.required&&(l.required=t.required.map(f=>a?.get(f)??f));let u={};if(a){let f=new Map;for(let[h,g]of a)f.set(g,h);let m=false;for(let[
551
- h,g]of a)h!==g&&(m=true);if(m){u.keysFwd=a,u.keysBack=f;for(let[h,g]of a)h!==g&&(o+=1);}}s.size>0&&(u.props=s);let d=!u.keysFwd&&!u.props;return {compact:l,...d?{}:{node:u},renamed:o,coded:r}}function Ic(t,e){
552
- if(!t.items)return {compact:t,renamed:0,coded:0};let n=Io(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function zs(t,e){let n=[
553
- ...t].sort(),o=new Set,r=new Map;n.forEach((i,a)=>{let c=e?i.toUpperCase():i,l=i;for(let u=1;u<i.length;u++){let d=c.slice(0,u);if(!o.has(d)){l=d;break}}if(l===i){let u=a.toString(36);u.length<i.length&&
554
- !o.has(u)&&(l=u);}o.add(l),r.set(i,l);});let s=new Set(t);for(let[i,a]of r)if(a!==i&&s.has(a))return null;return r}function We(t,e,n){let o=n?e.enumFwd:e.enumBack;if(o&&typeof t=="string")return o.get(t)??
555
- t;if(e.items&&Array.isArray(t))return t.map(s=>We(s,e.items,n));let r=n?e.keysFwd:e.keysBack;if((r||e.props)&&Oc(t)){let s={};for(let[i,a]of Object.entries(t)){let c=r?.get(i)??i,l=n?i:c,u=e.props?.get(
556
- l);s[c]=u?We(a,u,n):a;}return s}return t}function Oc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function _c(t){let e=Math.min(Ns,Math.max(1,To(t,0))),n=[];for(let o=0;o<e;o++)n.push(Eo(t,
557
- o,0));return n}function To(t,e){if(e>rn)return 0;let n=t.enum?.length??0;for(let o of Object.values(t.properties??{}))n=Math.max(n,To(o,e+1));return t.items&&(n=Math.max(n,To(t.items,e+1))),n}function Eo(t,e,n){
558
- if(n>rn)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if($s(t)){let o={};for(let[r,s]of Object.entries(t.properties??{}))o[r]=Eo(s,e,n+1);return o}if(Fs(t)){if(t.maxItems===
559
- 0)return [];let o=Math.max(1,t.minItems??1),r=t.maxItems!=null?Math.min(o,t.maxItems):o,s=t.items;return Array.from({length:r},()=>s?Eo(s,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";
560
- let o=Math.max(1,t.minLength??1),r=t.maxLength!=null?Math.min(o,t.maxLength):o;return "x".repeat(r)}case "number":case "integer":{let o=t.minimum??1;return t.maximum!=null&&o>t.maximum&&(o=t.maximum),t.type===
561
- "integer"?Math.round(o):o}case "boolean":return true;case "null":return null;default:return null}}function Ro(t,e){if(e>rn)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.
562
- values(t.properties??{}))if(Ro(n,e+1))return true;return !!(t.items&&Ro(t.items,e+1))}function Co(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.
563
- isArray(t),o=Array.isArray(e);if(n||o){if(!n||!o||t.length!==e.length)return false;for(let i=0;i<t.length;i++)if(!Co(t[i],e[i]))return false;return true}let r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)
564
- return false;for(let i of r)if(!Object.prototype.hasOwnProperty.call(e,i)||!Co(t[i],e[i]))return false;return true}var Ac="2026-08-14",Vs={"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 \
565
- enums)",pares:8}},Dc=fn(Vs);function Pc(t){return pn(Vs,Dc,t)}var sn=class t{deltas=new Map;static clave(e,n){return `${e}\0${n}`}recordar(e,n,o){this.deltas.set(t.clave(e,n),o);}resolver(e,n,o){if(o!=null&&
566
- Number.isFinite(o))return this.recordar(e,n,o),{deltaTokens:o,origen:"caller",procedencia:`measured by the caller for this contract on ${e}`};let r=this.deltas.get(t.clave(e,n));if(r!=null)return {deltaTokens:r,
567
- origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let s=Pc(e);return s?{deltaTokens:s.deltaTokens,origen:"catalogue",procedencia:`measured by Bi\
568
- Velio on ${e} (${Ac}, ${s.pares} paired reps, ${s.contrato}, ${s.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};var _o="[BiVelio Savings: resultado de herramienta antiguo recortado para bajar el coste; los resultados recientes viajan enteros.]",Lc=new TextEncoder;function Mc(t){return Lc.encode(t).length}function Bc(t,e){if(!t)return null;let n=(e??"").trim();if(n===""||n==="{}"||n==="[]")return null;let o;try{let r=JSON.parse(n);if(r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0)return null;
569
- o=Oo(r);}catch{o=n;}return `${t} ${o}`}function Oo(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(Oo).join(",")}]`:`{${Object.keys(t).sort().map(n=>`${JSON.stringify(
570
- n)}:${Oo(t[n])}`).join(",")}}`}function Us(t){let e=new Map,n=new Map;for(let l of t)if(l.role==="assistant"&&l.toolCalls)for(let u of l.toolCalls)u.id&&(e.set(u.id,u.arguments),n.set(u.id,u.name));let o=[],
571
- r=new Map;for(let l=0;l<t.length;l++){let u=t[l];if(u.role!=="tool")continue;o.push(l);let d=(u.toolCallId?n.get(u.toolCallId):void 0)??u.name,f=u.toolCallId?e.get(u.toolCallId):void 0,m=Bc(d,f);m!==null&&
572
- r.set(l,m);}let s=o.length?o[o.length-1]:-1,i=new Map;for(let l of o){let u=r.get(l);if(u===void 0)continue;let d=i.get(u);(d===void 0||l>d)&&i.set(u,l);}let a=[],c=0;for(let l of o){if(l===s)continue;let u=r.
573
- get(l);if(u===void 0||i.get(u)===l)continue;let d=Mc(t[l].content);d<1024||(a.push(l),c+=d);}return {indices:a,bytesOriginales:c}}function qs(t,e){if(e.length===0)return t;let n=new Set(e);return t.map(
574
- (o,r)=>n.has(r)?{...o,content:_o}:o)}function Ao(t,e){if(e?.cacheTier)return e.cacheTier;let n=t.toLowerCase(),o=n.indexOf("/"),r=o>0?n.slice(0,o):"",s=o>=0?n.slice(o+1):n;return r==="openai"||r==="azure-openai"?go:r==="anthropic"?bo(s):
575
- r==="google"||r==="google-vertex"?yo:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(s)?go:s.startsWith("claude")?bo(s):s.startsWith("gemini")?yo:Is}function Hs(t){let e=t.prefix!=null,n=xo({originalTokens:t.originalTokens,
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 "";
624
+ 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&&
630
+ 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,
576
640
  compressedTokens:t.compressedTokens,stablePrefixTokens:t.prefix?.stableTokens??0,prefixHitRate:t.prefix?.hitRate??0,tier:t.tier,...t.compressorCostTokens!=null?{compressorCostTokens:t.compressorCostTokens}:
577
- {}});if(e)return n;let o=t.tier.minimumCacheTokens;return o!=null&&t.originalTokens>=o&&t.compressedTokens<o?{...n,comprimir:false,razon:`compressing would drop the prompt out of the cacheable tier (${t.
578
- compressedTokens} < ${o}) 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 Js(t){let e=u=>u/1e3*t.precio.inputPer1k,n=u=>u/1e3*t.precio.outputPer1k,o=e(t.promptTokens+t.descriptoresLigeros)+n(t.salidaDelSondeo),r=e(t.promptTokens+t.esquemasCompletos)+n(t.salidaFinal),
579
- s=o+e(t.promptTokens+t.esquemasDeLaSegunda)+n(t.salidaFinal),i=r-s,a=o,c=i>0&&i>=a,l;return i<=0?l=`descubrir cuesta m\xE1s de lo que ahorra: el prompt (${t.promptTokens} tokens) se paga dos veces y l\
580
- os esquemas que se evitan (${t.esquemasCompletos-t.esquemasDeLaSegunda}) no lo cubren`:c?l=`se evitan ${t.esquemasCompletos-t.esquemasDeLaSegunda} tokens de esquema en el peor caso, bastante para paga\
581
- r el prompt repetido y el sondeo`:l="la ganancia no cubre el coste de degradar: si el sondeo no elige, la petici\xF3n sale igual con todos los esquemas y el sondeo es coste puro",{aplicar:c,costeDeUnaLlamada:r,
582
- costeDeDosLlamadas:s,ganancia:i,perdidaSiDegrada:a,razon:l}}function Ws(t){let n=(t.description??(Array.isArray(t.intents)?t.intents.join("; "):"")).trim().split(/\r?\n/,1)[0]??"",o=n.length>Ks?n.slice(
583
- 0,Ks-1).trimEnd()+"\u2026":n;return {id:t.id,intents:t.intents,risk:t.risk,...o?{description:o}:{}}}var Ks=200;function Gs(t,e,n){let o=new Map(e.map(c=>[c.id,c])),r=[],s=[],i=new Set;for(let c of t){let l=o.
584
- get(c);if(!l){s.push(c);continue}r.includes(l.id)||(r.push(l.id),l.risk==="read"&&i.size<Math.max(0,n)&&i.add(l.id));}return {tools:e.filter(c=>c.risk!=="read"||i.has(c.id)),reconocidos:r,ignorados:s}}function Ys(t,e){
585
- let n=0,o=[];for(let r of t)r.risk==="read"?o.push(r.tokens):n+=r.tokens;o.sort((r,s)=>s-r);for(let r of o.slice(0,Math.max(0,e)))n+=r;return n}var Do=true,ei=new WeakSet;function Nc(t){typeof t=="object"&&t!==null&&ei.add(t);}function jc(t){return typeof t=="object"&&t!==null&&ei.has(t)}function Qs(t,e){switch(t){case "none":return $c();case "inv\
641
+ {}});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\
653
+ 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)?
660
+ {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)
663
+ 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
+ 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
+ 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.
672
+ 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(){
676
+ 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
+ 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.
681
+ 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,
684
+ 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 \
687
+ (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
+ 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\
691
+ 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?
694
+ {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===
697
+ "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
+ 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){
701
+ 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\
586
717
  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\
587
718
  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 \
588
719
  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\
@@ -590,222 +721,288 @@ status: invalid)":"BiVelio license key is not valid (it does not verify). Check
590
721
  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\
591
722
  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\
592
723
  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\
593
- license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function $c(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 t\
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\
594
725
  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\
595
- cense status: none)"}function Fc(){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 \
596
- path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var an=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new tn;verjaDeCascada;memoriaDelCodebook=new sn;constructor(e){
597
- this.config=e,this.deps=Rs(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>hn()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.verjaDeCascada=new nn(e.modelCascade?.
598
- exploration!=null?{exploracion:e.modelCascade.exploration}:{});}async generate(e){this.assertLicensed();let n={llamadas:0,falloDelProveedor:false};try{return await this.generateOptimized(e,n)}catch(o){if(o instanceof
599
- De||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||jc(o))throw o;return await this.failOpenDirect(e,o)}}async llamarProveedor(e,n){n.llamadas+=1;try{return await this.config.provider.generate(
600
- e)}catch(o){throw n.falloDelProveedor=true,o}}decidirMarcadoDeCache(e,n,o,r,s,i,a){let c={marcar:false,huella:"",mensajesDePrefijo:0,cacheWriteMultiplier:1},l=Wc(n,this.config.compressionEconomics);if(!l)return a.
601
- 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 prefix`}),c;if(!r.setIsStable)
602
- 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 saving); pass the tools you wa\
603
- nt 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 block \u2014 which renders first\
604
- \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 prefix cache."}),c;
605
- if(i<=0)return c;let u=o.slice(0,i),d=this.tokensFor(this.assemblePromptText(u,r.tools),e),f=this.tokensFor(this.assemblePromptText(o,r.tools),e),m=ie(Se({model:n,tools:(r.tools??[]).map(g=>g.id),prefijo:u.
606
- map(g=>`${g.role}:${g.content}`)})),h=this.verjaDeCache.decidir(m,{totalTokens:f,stablePrefixTokens:d,tier:l});return a.record("prefix-cache",h.marcar?"marked":"skipped",{reason:h.razon,stablePrefixTokens:d,
607
- breakEvenHitRate:h.umbral,observedHitRate:h.observada}),h.marcar?{marcar:true,huella:m,mensajesDePrefijo:i,cacheWriteMultiplier:l.cacheWriteMultiplier}:c}decidirCascada(e,n,o,r){let s=o.modelCascade??"o\
608
- ff",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,muestras:0,precioBarato:null,
609
- tasaDeMuestreo:0};if(s==="off")return i;let a=Ps({schema:e.response?.schema,tools:e.tools}),c=Ds(e.model,this.config.modelCascade?.pairs??vo),l=this.precioConocido(e.model),u=c?this.precioConocido(c):
610
- void 0,d=As(u,l),f=ie(Se({tenant:n.tenantId,scope:n.authorizationScope,contract:n.contractId,schema:n.schemaVersion,fuerte:e.model,barato:c,tools:n.toolsetHash})),m=this.verjaDeCascada.estado(f),h={modo:s,
611
- modeloPedido:e.model,modeloServido:e.model,candidato:c,enruta:false,elegible:false,razon:a.razon,fuerza:a.fuerza,bucket:f,economia:d,observada:m&&m.enrutadas>0?m.escaladas/m.enrutadas:null,muestras:m?.enrutadas??
612
- 0,precioBarato:u??null,tasaDeMuestreo:0},g=b=>(r.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(`no cheaper mod\
613
- el 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],...u?[]:[c]];return g(
614
- `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 NOT used here: it\
615
- 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?.shadowSampleRate??
616
- 0));if(s==="shadow")return r.record("model-cascade","shadow",{candidateModel:c,costRatio:d.r,breakEvenEscalationRate:d.equilibrio,verifier:a.fuerza,workload:f,note:"measuring only: the request goes to\
617
- 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};let y=this.
618
- verjaDeCascada.decidir(f,d);return y.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 \
619
- 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.model always \
620
- names the model that answered, and report.qualityStatus reads "bounded_degradation".`),r.record("model-cascade","routed",{candidateModel:c,costRatio:d.r,breakEvenEscalationRate:d.equilibrio,observedEscalationRate:y.
621
- observada,verifier:a.fuerza,workload:f,reason:y.razon}),{...h,modeloServido:c,enruta:true,elegible:true,razon:y.razon,observada:y.observada,muestras:y.muestras,tasaDeMuestreo:0}):(r.record("model-cascade",
622
- "off (gate)",{reason:y.razon,observedEscalationRate:y.observada,breakEvenEscalationRate:d.equilibrio}),{...h,elegible:true,razon:y.razon,observada:y.observada,muestras:y.muestras})}devOpen(){return false}assertLicensed(){
623
- 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,o=typeof e.reason=="function"?e.reason():
624
- void 0;throw new De(Qs(n,o),n)}throw e?new De(Fc(),"invalid"):new De(Qs("none"),"none")}avisar(e,n){this.config.silenceWarnings||G(e,n);}avisarDeTruncado(e,n,o,r,s){let i=e.response?.maxOutputTokens,a=gt(
625
- e)||"(sin contractId)",c=s?" La capa lo ha APUNTADO: las siguientes peticiones de este contrato llevar\xE1n sus l\xEDmites de valor escritos en el prompt, que es lo \xFAnico que puede corregirlo sin tocarte el\
626
- tope. Si aun as\xED se corta, es que la tarea no cabe en el contrato: ensancha el esquema y sube el tope con \xE9l.":"",l=r===null?" El esquema no acota la respuesta (falta `maxLength`/`maxItems`), a\
627
- s\xED que no hay forma de saber de antemano cu\xE1nto necesita: ac\xF3talo y el tope deja de ser una apuesta.":i==null?` El contrato autoriza ~${r} tokens y esta petici\xF3n no declara tope, as\xED que quie\
628
- n cort\xF3 fue un tope del PROVEEDOR (la API de Anthropic exige \`max_tokens\` y el adaptador manda 4096 por defecto). Declara \`maxOutputTokens\` y el corte deja de ser una sorpresa.`:r>i?` El contra\
629
- to autoriza respuestas de hasta ~${r} tokens con este modelo (lo que permiten sus \`maxLength\`/\`maxItems\`) y el tope son ${i}: ninguna respuesta que use lo que el propio esquema permite cabe. Un to\
630
- pe calibrado con otro modelo NO se hereda \u2014 el esquema acota CARACTERES, que son iguales en todas partes, y el tope acota TOKENS, que son distintos en cada tokenizador.`:` El contrato autoriza ~${r}\
631
- tokens y el tope son ${i}, as\xED que el tope no es el problema: este modelo est\xE1 escribiendo m\xE1s de lo que su propio esquema permite (ning\xFAn modo estructurado impone \`maxLength\`).${c}`;this.
632
- avisar(`salida-truncada:${a}:${n}`,`[bvsala] La respuesta se cort\xF3 al agotar \`maxOutputTokens\`${i!=null?` (${i})`:""} con el modelo ${n} y el contrato \xAB${a}\xBB: el proveedor devolvi\xF3 finish_reas\
633
- on "length" y ${o} tokens de salida, as\xED que el JSON no valida. NO se reintenta: con el mismo tope volver\xEDa a cortarse y ser\xEDa una llamada pagada para el mismo fallo.${l}`);}avisarDePalancasSinConfigurar(e){
634
- this.config.silenceWarnings||((e.compression===true||e.compression==="auto")&&!this.config.compressor&&this.avisar("palanca-sin-compresor","[bv-sala] se pidi\xF3 `savings.compression` pero esta capa no tie\
635
- ne compresor, as\xED que NO se comprime nada: el contexto largo viaja y se paga entero. En el informe, `report.compression` sale AUSENTE y `tokens.eliminatedInput` a 0 \u2014 lo mismo que se ve cuando no hab\xED\
636
- a nada que comprimir. El compresor es un sidecar porque a\xF1ade latencia y c\xF3mputo que solo usted debe decidir pagar: ench\xFAfelo con `createSavingsLayer({ compressor })`, cualquier objeto con `compress(\
637
- { text })`. Si su plan no incluye `long_context_compression`, har\xE1 falta adem\xE1s esa funci\xF3n. El resto de la capa sigue ahorrando igual."),e.semanticCache&&!this.deps.semanticCache&&this.avisar(
638
- "palanca-sin-cache-semantica",'[bv-sala] se pidi\xF3 `savings.semanticCache` pero esta capa no tiene cach\xE9 sem\xE1ntica, as\xED que toda pregunta reformulada saldr\xE1 `cache: "miss"` y se pagar\xE1 al proveedor otr\
639
- a vez. No viene por defecto porque necesita un embebedor, que es coste y proveedor suyos: ench\xFAfela con `createSavingsLayer({ semanticCache: new InMemorySemanticCache({ embed }) })`. La cach\xE9 exacta y\
640
- el resto de la capa siguen funcionando.'));}async generateOptimized(e,n={llamadas:0,falloDelProveedor:false}){this.assertLicensed();let o=new st(this.now),r=new je,s=wn(e),i=Tn(s),a=e.savings??{};this.avisarDePalancasSinConfigurar(
641
- a);let c=this.decidirCascada(e,s,a,o),l=this.costModelFor(c.modeloServido);o.record("canonicalize","done",{tenant:s.tenantId,contract:s.contractId}),o.record("policy",i.reasons.join("; ")||"no restric\
642
- tions",{allowExactCache:i.allowExactCache,allowSemanticCache:i.allowSemanticCache});let u=this.tokensFor(this.assembleBaselinePrompt(e),e),d=e.response?.maxOutputTokens??256;if(r.baselineInput=u,r.baselineOutput=
643
- d,r.baselineTools=e.tools?.length??0,a.deterministicResolvers!==false){let g=this.deps.resolvers.try(s);if(g)return r.avoidCall(u,this.tokensFor(g.text,e)),o.record("resolver",g.resolver,{avoided:true}),this.
644
- finish(e,s,{text:g.text,data:g.data,storedAtMs:this.now()},"deterministic",r,l,o,mt(),ht(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(c,{servedModel:e.model}))}let f=Sn(s,{servedModel:c.
645
- modeloServido});if(i.allowExactCache&&a.exactCache!==false){let g=await this.deps.exactCache.get(f);if(g)return r.avoidCall(u,this.tokensFor(g.text,e)),o.record("exact-cache","hit",{ageMs:this.now()-g.storedAtMs}),
646
- this.finish(e,s,g,"exact",r,l,o,mt(),ht(),this.now()-g.storedAtMs,void 0,void 0,void 0,void 0,this.informeDeCascada(c));o.record("exact-cache","miss");}let m=Ho(s,{servedModel:c.modeloServido,deferrable:a.
647
- deferrable===true,toolDiscovery:a.toolDiscovery===true,...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{}}),h=async()=>{try{return await this.expensivePath(n,e,s,i,a,r,l,
648
- o,f,u,c)}catch(g){throw (n.falloDelProveedor||n.llamadas>0)&&Nc(g),g}};if(i.allowSingleflight&&a.singleflight!==false){let{value:g,coalesced:p}=await this.deps.singleflight.run(m,h);return p?(o.record("si\
649
- ngleflight","coalesced",{key:m}),this.asCoalescedFollower(g,u,this.tokensFor(g.text??"",e),l,e)):g}return h()}async expensivePath(e,n,o,r,s,i,a,c,l,u,d){let f=this.entitled("semantic_cache");if(r.allowSemanticCache&&
650
- s.semanticCache&&this.deps.semanticCache&&!f&&c.record("semantic-cache","degraded: feature not licensed (free tier)"),r.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&f){let v=await this.
651
- deps.semanticCache.find(o);if(v)return i.avoidCall(u,this.tokensFor(v.record.answer.text,n)),c.record("semantic-cache","hit",{confidence:v.confidence,similarity:v.similarity}),this.finish(n,o,v.record.
652
- answer,"semantic",i,a,c,mt(),ht(),v.ageMs,v.confidence,void 0,void 0,void 0,this.informeDeCascada(d,{servedModel:n.model}));c.record("semantic-cache","miss");}let m=s.router===false,h=m?mt():this.deps.router.
653
- classify(o);c.record("router",h.executionClass,{confidence:h.confidence,reason:h.reason});let g=m?this.deps.toolSelector.passthrough(n.tools):this.deps.toolSelector.select(o.normalizedText,n.tools,h.executionClass,
654
- o.toolsetHash);if(i.actualTools=g.tools.length,g.droppedIds.length){let v=new Set(g.droppedIds),A=(n.tools??[]).filter(M=>v.has(M.id)).reduce((M,U)=>M+this.tokensFor(Po(U),n),0);i.eliminate(A),c.record(
655
- "tool-selector",g.reason,{dropped:g.droppedIds,eliminatedTokens:A});}i.baselineRetrieval=this.config.retriever?h.rounds:0;let p=await Qo({execution:h.executionClass,query:o.normalizedText,maxRounds:n.retrieval?.
656
- maxRounds??h.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});i.actualRetrieval=
657
- p.rounds,p.retrievedCount>0&&c.record("retrieval",`kept ${p.keptCount}/${p.retrievedCount}`,{rounds:p.rounds});let y=ht(),b=[...n.messages],x=Mo(n.messages),T=false,E=p.docs.length>0?{role:"system",content:`\
658
- Retrieved context \u2014 answer using only this evidence and cite sources by [id]:
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]:
659
808
 
660
- `+p.docs.map((v,A)=>`[${v.source??v.id??`doc${A+1}`}]
661
- ${v.text}`).join(`
809
+ `+v.docs.map((S,A)=>`[${S.source??S.id??`doc${A+1}`}]
810
+ ${S.text}`).join(`
662
811
 
663
- `)}:null,R=gt(n),C=n.response?.maxOutputTokens!=null?Math.floor(n.response.maxOutputTokens*3.2):null,D=this.contratosQueIncumplen.has(R)?Lo(n.response?.schema,"",C):"";if(D&&bt(b,{role:"system",content:`\
664
- JSON limits (not API-enforced): ${D}`}),n.structuredData!==void 0){let v=JSON.stringify(n.structuredData),A=this.tokensFor(v,n);if(s.serialization!==false){y=this.deps.formatSelector.choose(n.structuredData,
665
- {model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let M=this.tokensFor(y.encoded+y.instruction,n);i.compress(A,M),bt(b,{role:"system",content:(y.instruction?y.instruction+`
666
- `:"")+y.encoded}),c.record("serialization",y.chosen,{reason:y.reason,jsonTokens:A,chosenTokens:M});}else bt(b,{role:"system",content:v}),c.record("serialization","json-compact",{reason:"format selector\
667
- disabled; sent compact JSON"});}if(E&&bt(b,E),(s.compression===true||s.compression==="auto")&&r.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let v=this.config.compressionEconomics??
668
- {},A=Ao(n.model,v),M={compressorCostTokens:v.compressorCostTokens??0,...v.minimumContextTokens!=null?{minimumContextTokens:v.minimumContextTokens}:{},...v.minimumNetTokens!=null?{minimumNetTokens:v.minimumNetTokens}:
669
- {}},U=0,L=0;for(let F of b)F.role==="system"?U+=1:L+=this.tokensFor(F.content,n);let ee=this.tokensFor(this.assemblePromptText(b,g.tools),n),te=Ln({...M,contextTokens:L,projectedEliminable:L}),ne=0,de=0,
670
- Xe=false,pe=te.reason;if(te.compress){let F=[];for(let fe of b){if(fe.role==="system"){F.push(fe);continue}let Qe=this.tokensFor(fe.content,n),et=await this.config.compressor.compress({text:fe.content}),
671
- No=!et.skipped&&et.fidelityPassed&&ur(fe.content,et.compressed),jo=No?this.tokensFor(et.compressed,n):Qe;No&&jo<Qe?(F.push({...fe,content:et.compressed}),ne+=Qe,de+=jo):F.push(fe);}let Bo=this.tokensFor(
672
- this.assemblePromptText(F,g.tools),n),Z=Ln({...M,contextTokens:L,projectedEliminable:ne-de}),dn=Hs({originalTokens:ee,compressedTokens:Bo,tier:A,...v.prefix?{prefix:v.prefix}:{},compressorCostTokens:M.
673
- compressorCostTokens});de>=ne?pe="no fidelity-passed net reduction":Z.compress?dn.comprimir?(Xe=true,pe=dn.razon,T=F.slice(0,x).some((fe,Qe)=>fe.content!==b[Qe]?.content),b=F,i.compress(ne,de)):pe=dn.razon:
674
- pe=Z.reason;}Xe||(ne=0,de=0),c.record("compression",Xe?"applied":"skipped",{reason:pe,before:ne,after:de,contextTokens:L,promptTokens:ee,cacheTierMinimum:A.minimumCacheTokens,protectedSystemMessages:U,
675
- prefixRewritten:T}),i.compressionReport={originalTokens:ne,compressedTokens:de,protectedSpans:U,fidelityPassed:true};}if(s.elision!==false&&r.allowElision&&this.entitled("tool_result_elision")){let v=Us(b);
676
- if(v.indices.length>0){let A=this.tokensFor(_o,n),M=0;for(let U of v.indices){let L=this.tokensFor(b[U].content,n);M+=Math.max(0,L-A);}(v.indices.some(U=>U<x)&&(T=true),b=qs(b,v.indices),i.eliminate(
677
- M),i.elididoLocal+=M),c.record("elision","applied",{elided:v.indices.length,eliminatedTokens:M,grossBytes:v.bytesOriginales,live:Do});}else c.record("elision","skipped",{reason:"no old/larg\
678
- e tool_result over the age\xD7size threshold"});}let I=n.response?.schema,S=I&&s.outputCodebook===true?js(I,v=>this.tokensFor(v,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,gt(n),s.outputCodebookMeasuredOutputDeltaTokens)}):
679
- null;S&&c.record("output-codebook",S.applied?"applied":"skipped",{reason:S.reason,...S.applied?{renamedKeys:S.plan.renamedKeys,codedEnumValues:S.plan.codedEnumValues,schemaTokensOriginal:S.plan.schemaTokensOriginal,
680
- schemaTokensCompact:S.plan.schemaTokensCompact,modelledShapeSavingTokens:S.plan.modelledShapeSavingTokens,measuredOutputDeltaTokens:S.plan.measuredOutputDeltaTokens,outputDeltaProvenance:S.plan.outputDeltaProvenance,
681
- breakEvenOutputDeltaTokens:S.plan.breakEvenOutputDeltaTokens,netSavingUsd:S.plan.netSavingUsd,pricedForModel:d.modeloServido}:{}});let B=S?.applied?S.plan.compactSchema:I,k=B?lr(d.modeloServido,B,this.
682
- deps.constraintBackends):{backend:"none",reason:"no output contract"};c.record("constraints",k.backend,{reason:k.reason});let w=this.decidirMarcadoDeCache(n,d.modeloServido,b,g,s.toolDiscovery===true,T?
683
- Mo(b,true):x,c),_=this.now(),P=await this.descubrirHerramientas(e,n,s,g.tools,b,i,a,c),N=P.tools;i.actualTools=N.length;let V={messages:b,...N.length?{tools:N}:{},...B?{schema:B}:{},...n.response?.maxOutputTokens!=
684
- null?{maxOutputTokens:n.response.maxOutputTokens}:{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{},...s.deferrable?{deferrable:true}:{},constraintBackend:k.backend},
685
- O=await this.llamarProveedor({model:d.modeloServido,...V,...w.marcar?{stablePrefixMessages:w.mensajesDePrefijo,promptCacheKey:w.huella}:{}},e);i.actualLlm+=1;let X=v=>{if(!S?.applied)return v;let A=Ge(
686
- v);return A.ok?JSON.stringify(S.plan.expand(A.value)):v},$=X(O.text),Q=O.usage,W=false;if(d.enruta){let v=wo({texto:$,schema:I,finishReason:O.finishReason,pidioHerramientas:(O.toolCalls?.length??0)>0});this.
687
- verjaDeCascada.registrar(d.bucket,!v.acepta),c.record("model-cascade",v.acepta?"accepted":"escalating",{servedModel:d.modeloServido,reason:v.motivo,checks:v.comprobaciones}),v.acepta||(W=true,i.cascadeAttempt(
688
- O.usage,d.precioBarato??a),i.actualLlm+=1,O=await this.llamarProveedor({model:n.model,...V},e),$=X(O.text));}let ue=W?n.model:d.modeloServido,ve=W?this.costModelFor(n.model):a;i.actualInput+=O.usage.inputTokens,
689
- i.actualOutput+=O.usage.outputTokens,S?.applied&&c.record("output-codebook",Ge(O.text).ok?"expanded":"not-expanded (response was not JSON)",Ge(O.text).ok?{localOutputTokensCompact:this.tokensFor(O.text,
690
- n),localOutputTokensExpanded:this.tokensFor($,n),creditedLedger:"none",note:"local count of the served answer in both shapes; not credited to any ledger"}:{}),I&&k.backend==="provider-native"&&O.structuredNatively===
691
- false&&(k={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","none",{downgradedFrom:"p\
692
- rovider-native",reason:k.reason})),i.sentInputLocal=this.tokensFor(this.assemblePromptText(b,N),n),i.removedInputLocal=Math.max(0,u-i.sentInputLocal-i.elididoLocal),i.sentInputLocal+=P.tokensLocalesDelSondeo,
693
- i.estimatorExact=this.estimatorEsExacto(n),O.usage.cachedInputTokens&&i.providerCached(O.usage.cachedInputTokens),w.marcar&&(i.cacheWritePremium(Q.cacheWriteInputTokens??0,w.cacheWriteMultiplier,d.precioBarato??
694
- a),this.verjaDeCache.registrar(w.huella,Q),c.record("prefix-cache","measured",{cacheRead:Q.cachedInputTokens??0,cacheWritePremiumTokens:Q.cacheWriteInputTokens??0}));let ke=null;if(d.modo==="shadow"&&
695
- d.elegible&&d.candidato&&d.precioBarato&&Kc(l,d.tasaDeMuestreo))try{let v=await this.llamarProveedor({model:d.candidato,...V},e);i.actualLlm+=1;let A=i.extraCostUsd;i.cascadeAttempt(v.usage,d.precioBarato);
696
- let M=X(v.text),U=wo({texto:M,schema:I,finishReason:v.finishReason,pidioHerramientas:(v.toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!U.acepta);let L=U.acepta?Ls(M,$):null;ke={coste:i.
697
- extraCostUsd-A,divergio:L?L.divergen:null},c.record("model-cascade",U.acepta?"sample accepted":"sample escalated",{candidateModel:d.candidato,reason:U.motivo,sampleCost:ke.coste,...L?{diverged:L.divergen,
698
- divergence:L.motivo}:{},note:"measurement only: this answer was NEVER served. The escalation rate it feeds is a money figure, not a quality one"});}catch(v){c.record("model-cascade","sample failed (mea\
699
- surement only; the answer is unaffected)",{error:v instanceof Error?v.message:String(v)});}let Ye=$,_e=true,Ze=(O.toolCalls?.length??0)>0;if(Ze&&(_e=null,I&&c.record("validation","n/a: model requested to\
700
- ol calls (the output contract applies to the final answer)")),I&&!Ze){let v=Ge($),A=v.ok?ae(v.value,I):{valid:false,errors:[{path:"$",message:"not valid JSON"}]};v.ok&&v.rescatado!=null&&A.valid&&($=v.rescatado,
701
- c.record("validation","rescued-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&&Jc(A.errors)&&this.contratosQueIncumplen.
702
- add(gt(n));let M=O.finishReason==="length",U=!A.valid&&A.errors.some(L=>/not a valid regular expression/.test(L.message));if(!A.valid&&U)c.record("validation","repair-skipped",{reason:"schema defect (\
703
- uncompilable pattern); no output can satisfy it, a retry is a wasted call",errors:A.errors}),this.avisar("esquema-roto","[bvsala] El contrato de respuesta tiene un `pattern` que no es un regex valido,\
704
- asi que ninguna respuesta puede cumplirlo. NO se reintenta (seria una llamada pagada para el mismo fallo). Corrige el `pattern` del esquema.");else if(!A.valid&&M){let L=Bs(I,ne=>this.tokensFor(ne,n)),
705
- ee=n.response?.maxOutputTokens??null,te=L!==null&&ee!=null&&L<=ee;te&&this.contratosQueIncumplen.add(gt(n)),c.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry\
706
- with the same cap would truncate again",maxOutputTokens:n.response?.maxOutputTokens??null,outputTokens:O.usage.outputTokens,model:ue,...L!==null?{schemaAllowsTokens:L}:{},learnedValueLimits:te}),this.
707
- avisarDeTruncado(n,ue,O.usage.outputTokens,L,te);}else if(!A.valid&&k.backend==="none"){let L=A.errors.slice(0,5).map(Z=>`- ${Z.path}: ${Z.message}`).join(`
708
- `),ee=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
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.
709
860
 
710
861
  Previous reply:
711
- ${$}
862
+ ${B}
712
863
 
713
864
  Problems found:
714
- ${L}
865
+ ${N}
715
866
 
716
- Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],te=this.tokensFor(this.assemblePromptText(ee),n),ne=i.sentInputLocal>0?i.actualInput/i.sentInputLocal:1,de=Math.
717
- round(ne*te),Xe=Math.min(O.usage.outputTokens,n.response?.maxOutputTokens??Number.POSITIVE_INFINITY),pe=de/1e3*ve.inputPer1k+Xe/1e3*ve.outputPer1k,F=this.config.skipRepairAboveBaseline?i.estimateCost(
718
- ve):void 0;if(F!=null&&F.baselineEstimate>0&&F.actual+pe>F.baselineEstimate&&F!=null)c.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the inva\
719
- lid answer is served as-is and reported as invalid",errors:A.errors,baselineUsd:F.baselineEstimate,actualUsd:F.actual,repairEstimateUsd:pe}),this.avisar("reparacion-mas-cara-que-el-baseline",`[bvsala]\
720
- 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 ~$${F.baselineEstimate}, already spent ~$${F.actual}\
721
- , repair ~$${pe.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\
722
- 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}),O=await this.llamarProveedor({model:ue,
723
- messages:ee,schema:I,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),i.actualLlm+=1,i.actualInput+=O.usage.inputTokens,i.actualOutput+=O.usage.outputTokens,i.repairOutput+=
724
- O.usage.outputTokens,i.repairInput+=O.usage.inputTokens,i.sentInputLocal+=te,$=O.text;let Z=Ge($);A=Z.ok?ae(Z.value,I):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},Z.ok&&(Ye=Z.value,Z.rescatado!=
725
- null&&A.valid&&($=Z.rescatado));}}else v.ok&&(Ye=v.value);_e=A.valid,c.record("validation",_e?"valid":"invalid");}let ti=this.now()-_,ni=Uc(Ye),ln={text:$,data:Ye,rendered:ni,storedAtMs:this.now()},we=this.
726
- informeDeDiferido(s,O,ve);we&&c.record("deferred-tier",we.credited?"credited":"not-credited",{...we.requestedTier?{requestedTier:we.requestedTier}:{},...we.servedTier?{servedTier:we.servedTier}:{},creditedLedger:"\
727
- none",reason:we.reason});try{let v=P.aplicado,A=O.finishReason==="length",M=_e!==!1&&!Ze&&!v&&!A;M||c.record("cache-write",Ze?"skipped: tool-call turn (an action request must not be replayed from cach\
728
- e)":_e===!1?"skipped: response fails its output contract":A?'skipped: answer cut off by the output cap (finish_reason "length"); replaying half an answer would bill it as a 100% avoided call':"skipped\
729
- : answered with a reduced tool view (tool discovery), so it must not be replayed");let U=W?Sn(o,{servedModel:ue}):l;if(M&&r.allowExactCache&&s.exactCache!==!1){let ee=this.config.exactCacheTtlMs??864e5,
730
- te=r.maxCacheAgeMs==null?ee:Math.min(ee,r.maxCacheAgeMs);await this.deps.exactCache.set(U,ln,te);}let L=ue!==n.model;M&&!L&&r.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache?await this.deps.
731
- semanticCache.store(o,ln):M&&L&&s.semanticCache&&c.record("cache-write","semantic write skipped: a cheaper model answered, and this cache keys on the model the caller asked for");}catch(v){c.record("ca\
732
- che-write","failed (non-fatal; answer already served)",{error:v instanceof Error?v.message:String(v)});}let un=this.finish(n,o,ln,"miss",i,ve,c,h,y,void 0,void 0,_e,k.backend,ti,this.informeDeCascada(d,
733
- {servedModel:ue,...d.enruta?{escalated:W}:{},...d.elegible&&d.precioBarato?{estimatedSwapSaving:Hc(i,W,d.precioBarato,this.costModelFor(n.model))}:{},...ke?{sampled:true,sampleCost:cn(ke.coste),...ke.divergio!==
734
- null?{divergedOnSample:ke.divergio}:{}}:{},...i.cascadeInput>0||i.cascadeOutput>0?{cascadeInputTokens:i.cascadeInput,cascadeOutputTokens:i.cascadeOutput}:{}}),we);return Ze&&(un.toolCalls=O.toolCalls),
735
- O.finishReason!==void 0&&(un.finishReason=O.finishReason),un}async descubrirHerramientas(e,n,o,r,s,i,a,c){let l={tools:r,tokensLocalesDelSondeo:0,aplicado:false};if(o.toolDiscovery!==true)return l;if(r.length<
736
- 2)return c.record("tool-discovery","skipped (nothing to discover)",{candidates:r.length}),l;let u=p=>this.tokensFor(Po(p),n),d=r.map(Ws),f=Js({promptTokens:this.tokensFor(this.assemblePromptText(s),n),
737
- esquemasCompletos:r.reduce((p,y)=>p+u(y),0),descriptoresLigeros:d.reduce((p,y)=>p+u(y),0),esquemasDeLaSegunda:Ys(r.map(p=>({risk:p.risk,tokens:u(p)})),3),salidaFinal:n.response?.maxOutputTokens??256,salidaDelSondeo:96,
738
- precio:a});if(!f.aplicar)return c.record("tool-discovery","skipped (not worth a second call)",{reason:f.razon,oneCall:f.costeDeUnaLlamada,twoCalls:f.costeDeDosLlamadas}),l;let m,h=this.tokensFor(this.
739
- assemblePromptText(s,d),n);try{m=await this.llamarProveedor({model:n.model,messages:s,tools:d,maxOutputTokens:96,...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{}},
740
- e);}catch(p){return c.record("tool-discovery","failed (falling back to a single call with every schema)",{error:p instanceof Error?p.message:String(p)}),l}i.actualLlm+=1,i.actualInput+=m.usage.inputTokens,
741
- i.actualOutput+=m.usage.outputTokens,i.discoveryInput+=m.usage.inputTokens,i.discoveryOutput+=m.usage.outputTokens;let g=Gs((m.toolCalls??[]).map(p=>p.name),r,3);return g.reconocidos.length===0?(c.record(
742
- "tool-discovery","degraded: probe named no known tool",{finishReason:m.finishReason??null,...g.ignorados.length?{unknownNames:g.ignorados}:{}}),{tools:r,tokensLocalesDelSondeo:h,aplicado:false}):(c.record(
743
- "tool-discovery","applied (two provider calls)",{chosen:g.reconocidos,sent:g.tools.map(p=>p.id),candidates:r.length,...g.ignorados.length?{unknownNames:g.ignorados}:{}}),{tools:g.tools,tokensLocalesDelSondeo:h,
744
- aplicado:true})}informeDeCascada(e,n={}){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?
745
- {candidateModel:e.candidato}:{},...e.economia?{costRatio:ft(e.economia.r),breakEvenEscalationRate:ft(e.economia.equilibrio),targetEscalationRate:ft(e.economia.escaladoMaximo)}:{},...e.bucket?{workload:e.
746
- bucket}:{},...e.observada!=null?{escalationRate:ft(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,o){if(e.deferrable!==true)return;let r=n.requestedServiceTier,
747
- s=mr(n.servedServiceTier),i={...r?{requestedTier:r}:{},...s?{servedTier:s.servido}:{},credited:false,creditedLedger:"none",latency:br(r),reason:""};if(!r)return {...i,reason:gr};if(!s)return {...i,reason:`\
748
- asked the provider for the "${r}" 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 "${r}" \
749
- and the provider reports serving "${s.servido}", a tier this layer has no published rate for: nothing is credited`};if(!s.conDescuento)return {...i,reason:`asked for "${r}" and the provider reports ser\
750
- ving "${s.servido}", which 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)),
751
- l=o.cachedInputPer1k??o.inputPer1k,u=(Math.max(0,a.inputTokens)-c)/1e3*o.inputPer1k+c/1e3*l+Math.max(0,a.outputTokens)/1e3*o.outputPer1k,d=hr(s,u);return {...i,credited:true,discountRate:ft(s.factor),...d!=
752
- null?{estimatedTierSaving:cn(d)}:{},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 p\
753
- refix caching rather than replacing it`}}diferidoSinLlamada(e){if(e.savings?.deferrable===true)return {credited:false,creditedLedger:"none",latency:"not applicable: no provider call was made for this reques\
754
- t.",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 it"}}finish(e,n,o,r,s,i,a,c,l,u,d,f,m="\
755
- none",h=0,g,p){let y=e.response?.schema,b=f===null?null:f??(y?ae(o.data,y).valid:true),x=this.buildReport(e,n,r,s,i,a,c,l,u,d,b,m,h,g,p??this.diferidoSinLlamada(e));return {requestId:x.requestId,data:o.data,
756
- text:o.text,...o.rendered!==void 0?{rendered:o.rendered}:{},report:x}}buildReport(e,n,o,r,s,i,a,c,l,u,d,f,m,h,g){let p=r.estimateCost(s),y=i.elapsed(),b=h!=null&&h.servedModel!==h.requestedModel;return {
757
- requestId:this.generateId(),model:h?.servedModel??e.model,calls:{baselineLlm:r.baselineLlm,actualLlm:r.actualLlm,avoidedLlm:r.avoidedLlm,baselineRetrieval:r.baselineRetrieval,actualRetrieval:r.actualRetrieval,
758
- baselineTools:r.baselineTools,actualTools:r.actualTools,retries:r.retries},tokens:{baselineInput:r.baselineInput,actualInput:r.actualInput,eliminatedInput:r.eliminatedInput,compressedInput:r.compressedInput,
759
- baselineOutput:r.publishedBaselineOutput,actualOutput:r.actualOutput,eliminatedOutput:r.eliminatedOutput,...r.providerCachedInput?{providerCachedInput:r.providerCachedInput}:{}},cache:{result:o,...u!==
760
- void 0?{confidence:u}:{},...l!==void 0?{ageMs:l}:{}},routing:{executionClass:a.executionClass,confidence:a.confidence,rounds:r.actualRetrieval,reason:a.reason},serialization:{chosen:c.chosen,candidateTokens:c.
761
- candidateTokens,instructionOverheadTokens:c.instructionOverheadTokens},...r.compressionReport?{compression:r.compressionReport}:{},constraints:{backend:f,schemaVersion:n.schemaVersion,...d===null?{}:{
762
- structurallyValid:d}},qualityStatus:qc(o,d,b),...h?{modelCascade:h}:{},...g?{deferred:g}:{},quality:{...o!=="miss"?{freshnessPassed:!Tn(n).requiresFreshData}:{}},cost:p,latencyMs:{total:y,preprocessing:Math.
763
- max(0,y-m),provider:m},traces:i.all()}}async failOpenDirect(e,n){let o=new st(this.now);o.record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",{error:n instanceof Error?
764
- n.message:String(n)});let r=new je,s=this.costModelFor(e.model),i;try{i=wn(e);}catch{i={schemaVersion:e.response?.version??e.response?.contractId??"none"};}let a=e.response?.schema,c=[...e.messages];e.structuredData!==
765
- void 0&&bt(c,{role:"system",content:JSON.stringify(e.structuredData)});let l=this.now(),u=await this.config.provider.generate({model:e.model,messages:c,...e.tools?.length?{tools:e.tools}:{},...a?{schema:a}:
766
- {},...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),d=this.now()-l;r.baselineLlm=
767
- 1,r.actualLlm=1,r.actualInput=u.usage.inputTokens,r.actualOutput=u.usage.outputTokens,r.baselineInput=u.usage.inputTokens,r.baselineOutput=u.usage.outputTokens,u.usage.cachedInputTokens&&r.providerCached(
768
- u.usage.cachedInputTokens);let f=u.text,m=true,h=(u.toolCalls?.length??0)>0;if(h&&(m=null),a&&!h){let p=Ge(u.text);m=p.ok?ae(p.value,a).valid:false,p.ok&&(f=p.value);}let g=this.buildReport(e,i,"miss",r,s,o,
769
- mt(),ht(),void 0,void 0,m,"none",d,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 schedule\
770
- d exactly as an ordinary one.",reason:"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 t\
771
- rading availability for a discount on a last-resort call is the wrong trade"}:void 0);return {requestId:g.requestId,data:f,text:u.text,...h?{toolCalls:u.toolCalls}:{},...u.finishReason!==void 0?{finishReason:u.
772
- finishReason}:{},report:g}}asCoalescedFollower(e,n,o,r,s){let i=new je;i.avoidCall(n,o);let a=i.estimateCost(r),c=this.generateId(),l=this.diferidoSinLlamada(s),u=l?{deferred:l}:{},{deferred:d,...f}=e.
773
- report;return {...e,requestId:c,report:{...f,requestId:c,calls:{...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:i.baselineInput,actualInput:i.actualInput,eliminatedInput:i.eliminatedInput,
774
- compressedInput:i.compressedInput,baselineOutput:i.publishedBaselineOutput,actualOutput:i.actualOutput,eliminatedOutput:i.eliminatedOutput,...i.providerCachedInput?{providerCachedInput:i.providerCachedInput}:
775
- {}},cache:{result:"singleflight"},...u,cost:a}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,o){let r=e.map(s=>s.content);o!==void 0&&
776
- r.push(JSON.stringify(o));for(let s of n??[])r.push(Po(s));return r.join(`
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(`
777
938
  `)}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;
778
939
  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(
779
- e)}precioConocido(e){let n=this.config.costModels;if(n){let o=n[e];if(o)return o;let r=e.indexOf("/");if(r>=0){let s=n[e.slice(r+1)];if(s)return s}}return xt(e)}costModelFor(e){let n=this.precioConocido(
780
- e);return n||(this.config.defaultCostModel?this.config.defaultCostModel:(this.avisar(`precio-ilustrativo:${e}`,`[bv-sala] no cost model configured for "${e}"; falling back to the ILLUSTRATIVE default \
781
- price. Dollar figures will not match your bill. Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),Es))}};function Ge(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of zc(t))try{
782
- return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function zc(t){let e=[],n=/```[ \t]*[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g;for(let o of t.matchAll(n)){let r=o[1]?.trim();r&&
783
- e.push(r);}for(let o of ["{","["]){let r=t.indexOf(o);if(r===-1)continue;let s=Vc(t,r);s&&e.push(s);}return e}function Vc(t,e){let n=t[e],o=n==="{"?"}":"]",r=0,s=false,i=false;for(let a=e;a<t.length;a+=1){let c=t[a];
784
- if(s){i?i=false:c==="\\"?i=true:c==='"'&&(s=false);continue}if(c==='"'){s=true;continue}if(c===n)r+=1;else if(c===o&&(r-=1,r===0))return t.slice(e,a+1)}}function Uc(t){return typeof t=="string"?t:JSON.stringify(
785
- t,null,2)}function qc(t,e,n=false){if(e===false)return "rejected";if(n)return "bounded_degradation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "\
786
- not_verified"}}function ft(t){return Math.round(t*1e6)/1e6}function cn(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Hc(t,e,n,o){if(e)return cn(-t.extraCostUsd);let r=s=>t.actualInput/1e3*
787
- s.inputPer1k+t.actualOutput/1e3*s.outputPer1k;return cn(r(o)-r(n))}function Kc(t,e){if(!(e>0))return false;if(e>=1)return true;let n=ie(`${t}:cascade-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}
788
- function mt(){return {executionClass:"NO_RETRIEVAL",confidence:1,reason:"n/a (short-circuited)",rounds:0}}function ht(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,
789
- reason:"no structured payload"}}function Lo(t,e="",n=null){if(t==null||typeof t!="object")return "";let o=t,r=[],s=e||"the value",i=h=>typeof o[h]=="number"?o[h]:null,a=i("maxLength"),c=i("minLength"),
790
- l=i("maxItems"),u=i("minItems"),d=i("maximum"),f=i("minimum");if(a!=null){let h=n!=null?Math.min(a,n):a;r.push(`${s}<=${h}ch`);}c!=null&&r.push(`${s}>=${c}ch`),l!=null&&r.push(`${s}<=${l} items`),u!=null&&
791
- r.push(`${s}>=${u} items`),d!=null&&r.push(`${s}<=${d}`),f!=null&&r.push(`${s}>=${f}`),typeof o.pattern=="string"&&r.push(`${s} matches /${o.pattern}/`);let m=o.properties;if(m&&typeof m=="object")for(let[
792
- h,g]of Object.entries(m)){let p=Lo(g,e?`${e}.${h}`:h,n);p&&r.push(p);}if(o.items!==void 0){let h=Lo(o.items,`${s} entries`,n);h&&r.push(h);}return r.join("; ")}function gt(t){let e=t.response;return e?e.
793
- contractId??e.version??JSON.stringify(e.schema??{}).slice(0,200):""}function Jc(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.
794
- 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 bt(t,e){
795
- 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--)
796
- if(t[n].role==="user")return n;return Mo(t,true)}function Wc(t,e){let n=Ao(t,e);return n.cacheReadMultiplier<1?n:null}var Gc=72*3600;function Ef(t){t.licenseGate&&(console.warn("[bvsala] Ignoring the injected `licenseGate`: in the published package a license is only accepted as a `licenseKey` verified against BiVelio\
797
- 's embedded public key. Get yours at https://savings.bivelio.com/dashboard/install"),t={...t,licenseGate:void 0});let n={...t,tokenizer:t.tokenizer??Fo},o,r;if(t.licenseKey&&!t.licenseGate){let a=bs;if(t.licenseServerUrl){let c=new He,l=f=>Yt(f,a,{revocation:c,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??Gc}),u=l(t.licenseKey);n.licenseGate=
798
- {isEntitled:f=>u.isEntitled(f),isActive:()=>u.isActive(),status:()=>u.status(),reason:()=>u.reason()};let d=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;o=new Zt({url:d,publicKeyPem:a,
799
- snapshot:c,getRefreshAfter:()=>u.refreshAfter?.(),...t.now?{nowSeconds:()=>Math.floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.
800
- licensePollIntervalSeconds}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{},...t.licenseRevocation??{}}),o.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(r=new Qt({
801
- url:`${t.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,serviceAccountKey:t.serviceAccountKey,publicKey:a,initialToken:t.licenseKey,revocados:c,onNewToken:f=>{u=l(f);},...t.licenseFetch?{fetchImpl:t.
802
- licenseFetch}:{},...t.now?{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.
803
- leadSeconds}:{}}),r.start());}else n.licenseGate=Ss(t.licenseKey,a,t.now);}let s=new an(n),i;if(t.serviceAccountKey&&t.metering?.enabled!==false){let a=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.
804
- replace(/\/+$/,"")}/api/metering/usage`:void 0);if(a){i=new pt({url:a,serviceAccountKey:t.serviceAccountKey,surface:"sdk",...t.metering?.orgId?{orgId:t.metering.orgId}:{},...t.metering?.flushIntervalMs!=
805
- null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.metering?.maxBatch!=null?{maxBatch:t.metering.maxBatch}:{},...t.metering?.maxBuffer!=null?{maxBuffer:t.metering.maxBuffer}:{},...t.meteringFetch?
806
- {fetchImpl:t.meteringFetch}:t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:
807
- {}});let c=t.metering?.ci??mo();if(t.metering?.seatId)i.setSeat(t.metering.seatId,c);else {let l=i;ho(t.serviceAccountKey).then(u=>l.setSeat(u,c)).catch(()=>{});}i.start();}}return {generate:async a=>{let c=await s.
808
- generate(a);if(i)try{i.record(c.report);}catch{}return c},close:()=>{o?.stop(),r?.stop(),i?.stop();}}}/*! Bundled license information:
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.
962
+ 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.
968
+ 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
+ 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
+ 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\
976
+ 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
+ (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
+ 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\
980
+ 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-\
982
+ 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.
988
+ 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}:
995
+ 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!==
998
+ 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.
1000
+ 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
+ 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:
809
1006
 
810
1007
  @noble/curves/utils.js:
811
1008
  @noble/curves/abstract/modular.js:
@@ -813,4 +1010,4 @@ generate(a);if(i)try{i.record(c.report);}catch{}return c},close:()=>{o?.stop(),r
813
1010
  @noble/curves/abstract/edwards.js:
814
1011
  @noble/curves/ed25519.js:
815
1012
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
816
- */export{wr as AnthropicProvider,mn as BV_SALA_VERSION,yt as CATALOGO,Ji as COMPACT_ROWS_INSTRUCTION,Es as DEFAULT_COST_MODEL,Gc as DEFAULT_MAX_STALENESS_SECONDS,bs as EMBEDDED_PUBLIC_KEY,yn as ExactTokenizer,St as ExecutionRouter,It as FormatSelector,gn as HeuristicEstimator,kt as InMemoryExactCache,Yo as InMemorySemanticCache,Cn as InMemoryToolSetFreezer,De as LicenseError,pl as MODELOS_POR_CODIFICACION,zo as MODELS_BY_ENCODING,Mn as MockProvider,xr as OpenAICompatibleProvider,oi as PRECIOS_AL_DIA,nl as QUALITY_STATUSES,Rn as ResolverRegistry,Zt as RevocationPoller,He as RevocationSnapshot,je as SavingsLedger,Ot as SchemaRegistry,wt as Singleflight,bn as TokenizerRegistry,Tt as ToolSelector,st as TraceCollector,Wo as UMBRAL_LOCAL,pt as UsageEmitter,Bi as adaptiveK,Ri as arithmeticResolver,Sn as buildExactKey,Ho as buildInflightKey,wn as canonicalize,sr as compactRowsSerializer,ur as compresionFiel,Wa as computeNextDelay,vi as cosine,Wi as createCompactRowsSerializer,Zo as createDefaultResolvers,rl as createHandoff,Fu as createMockProvider,Ef as createSavingsLayer,ar as csvSerializer,tr as decodeCompactRows,Mi as dedupe,Fo as defaultTokenizerRegistry,ho as deriveSeatId,fo as deriveStatus,mo as detectCi,Jo as embebedorLocal,eu as emptyState,qi as encodeCompactRows,Oi as evalArithmetic,Tn as evaluatePolicy,Qo as executeRetrievalPlan,Ss as gateFromKey,Ne as heuristicEstimator,Ua as isKeyset,Ae as isStrictCompatible,er as jsonCompactSerializer,Ti as keyTokensMatch,uo as licenseKeyShape,Yt as liveGateFromKey,tu as mergeDelta,kn as modelFamilyOf,En as multisetEqual,ot as negationCount,Pu as noopCompressor,Ue as normalizeLicenseKey,vt as normalizeText,tt as numericTokens,xt as precioDeLista,nu as projectContext,Eu as providerNativeBackend,hn as randomId,ii as registerExactTokenizer,fl as registrarTokenizadorExacto,ji as renderState,lr as resolveConstraintBackend,Rs as resolveDependencies,zd as resolveLicense,ie as sha256,Ln as shouldCompress,Se as stableStringify,Ct as uniformColumns,ae as validateAgainstSchema,xi as vectorLocal,po as verifyCompactSignature,qe as verifyLicenseToken,ws as verifyRevocationList,Du as withProtectedSpans,nt as words};
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};