@bivelio/savings-layer 0.4.29 → 0.4.30

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 bo="2026-09-27",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 vo="2026-09-27",Qt={"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,
@@ -15,79 +15,80 @@ outputPer1k:.02,cachedInputPer1k:2e-4},"claude-opus-4":{inputPer1k:.015,outputPe
15
15
  nnet-4-6":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-5":{inputPer1k:.002,outputPer1k:.01,cachedInputPer1k:2e-4},"claude-fable-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},
16
16
  "claude-fable-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5":{inputPer1k:.01,outputPer1k:.05,
17
17
  cachedInputPer1k:.001},"claude-sonnet-4":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-haiku-4-5":{inputPer1k:.001,outputPer1k:.005,cachedInputPer1k:1e-4},"claude-3-5-sonnet":{inputPer1k:.003,
18
- outputPer1k:.015,cachedInputPer1k:3e-4},"claude-3-5-haiku":{inputPer1k:8e-4,outputPer1k:.004,cachedInputPer1k:8e-5},"claude-3-opus":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"claude-3-\
19
- haiku":{inputPer1k:25e-5,outputPer1k:.00125,cachedInputPer1k:3e-5},"gemini-3.8-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.7-flash":{inputPer1k:75e-5,outputPer1k:.00375,
20
- cachedInputPer1k:75e-6},"gemini-3.6-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.1-flash-lite":{inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:25e-6},"gemini-3-fl\
21
- ash-preview":{inputPer1k:5e-4,outputPer1k:.003,cachedInputPer1k:5e-5},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,
22
- cachedInputPer1k:3e-5},"gemini-3.1-pro-preview":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{
23
- inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}},id={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},
24
- sd={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.7-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,
25
- cachedInputPer1k:15e-5}}],"gemini-3.6-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},ad=Object.fromEntries(Object.keys(Yt).map(t=>[t,[{...id[t],
26
- precio:Yt[t]},...sd[t]??[]]]));var cd=864e13;function Vs(t){let e=t instanceof Date?t.getTime():t,n=typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=cd?e:Date.now();return new Date(n).toISOString().slice(0,10)}function Us(t,e){
27
- for(let n of ad[t]??[])if(!(n.vigenteDesde!==void 0&&e<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&e>=n.vigenteHasta))return n.precio}function vo(t,e,n){if(!n)return;let r=t[n];if(r)return r;let o=n.lastIndexOf("/"),i=o>=0?n.slice(o+1):n,s=t[i];if(s)return s;for(let a of e){if(!i.startsWith(a))continue;let c=i.charAt(a.length);if(c!==
28
- ""&&c!=="-"&&c!=="."&&c!=="_")continue;let u=i.slice(a.length+1);if(!(/^\d/.test(u)&&!/^\d{4}/.test(u)))return t[a]}}function yo(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var ud=["o3-dee\
29
- p-research","o4-mini-deep-research","gpt-5.5-pro","gpt-5.4-pro","gpt-5.2-pro","gpt-5-pro","gpt-5.5-cyber","gemini-3.8-flash-tts","gemini-3.8-flash-lite-tts","gemini-3.1-flash-lite-image"],go={...Yt,...Object.
30
- fromEntries(ud.map(t=>[t,null]))},ld=yo(go);function jn(t,e){let n=Tt(t);return n===void 0?void 0:Us(n,Vs(e))}var dd=Object.fromEntries(Object.keys(go).map(t=>[t,go[t]===null?null:t]));function Tt(t){
31
- return vo(dd,ld,t)??void 0}var pd=/^\d{4}-?\d{2}-?\d{2}$/;function We(t,e){let n=Tt(t);if(n===void 0)return;let r=t.lastIndexOf("/"),o=r>=0?t.slice(r+1):t;if(!(n!==t&&n!==o&&!pd.test(o.slice(n.length+
32
- 1))))return Us(n,Vs(e))}var Me="0.4.29",Nn="x-bvsala-version";var fd=0;function Qt(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++fd,o=Date.now?Date.now():0;for(let i=0;i<
18
+ outputPer1k:.015,cachedInputPer1k:3e-4},"claude-3-5-haiku":{inputPer1k:8e-4,outputPer1k:.004,cachedInputPer1k:8e-5},"claude-3-opus":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"gemini-3.\
19
+ 8-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.7-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.6-flash":{inputPer1k:75e-5,outputPer1k:.00375,
20
+ cachedInputPer1k:75e-6},"gemini-3.1-flash-lite":{inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:25e-6},"gemini-3-flash-preview":{inputPer1k:5e-4,outputPer1k:.003,cachedInputPer1k:5e-5},"gemini-3.\
21
+ 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-preview":{inputPer1k:.002,outputPer1k:.012,
22
+ 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}},ld={"gemini-3.8-flash":{
23
+ vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},dd={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,
24
+ cachedInputPer1k:15e-5}}],"gemini-3.7-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.6-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,
25
+ outputPer1k:.0075,cachedInputPer1k:15e-5}}]},pd=Object.fromEntries(Object.keys(Qt).map(t=>[t,[{...ld[t],precio:Qt[t]},...dd[t]??[]]]));var fd=864e13;function Hs(t){let e=t instanceof Date?t.getTime():t,n=typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=fd?e:Date.now();return new Date(n).toISOString().slice(0,10)}function Ws(t,e){
26
+ for(let n of pd[t]??[])if(!(n.vigenteDesde!==void 0&&e<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&e>=n.vigenteHasta))return n.precio}function yo(t,e,n){if(!n)return;let r=t[n];if(r)return r;let o=n.lastIndexOf("/"),i=o>=0?n.slice(o+1):n,s=t[i];if(s)return s;for(let a of e){if(!i.startsWith(a))continue;let c=i.charAt(a.length);if(c!==
27
+ ""&&c!=="-"&&c!=="."&&c!=="_")continue;let u=i.slice(a.length+1);if(!(/^\d/.test(u)&&!/^\d{4}/.test(u)))return t[a]}}function ko(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var md=["o3-dee\
28
+ p-research","o4-mini-deep-research","gpt-5.5-pro","gpt-5.4-pro","gpt-5.2-pro","gpt-5-pro","gpt-5.5-cyber","gemini-3.8-flash-tts","gemini-3.8-flash-lite-tts","gemini-3.1-flash-lite-image"],bo={...Qt,...Object.
29
+ fromEntries(md.map(t=>[t,null]))},hd=ko(bo);function Nn(t,e){let n=Tt(t);return n===void 0?void 0:Ws(n,Hs(e))}var gd=Object.fromEntries(Object.keys(bo).map(t=>[t,bo[t]===null?null:t]));function Tt(t){
30
+ return yo(gd,hd,t)??void 0}var bd=/^\d{4}-?\d{2}-?\d{2}$/;function Je(t,e){let n=Tt(t);if(n===void 0)return;let r=t.lastIndexOf("/"),o=r>=0?t.slice(r+1):t;if(!(n!==t&&n!==o&&!bd.test(o.slice(n.length+
31
+ 1))))return Ws(n,Hs(e))}var je="0.4.30",$n="x-bvsala-version";var vd=0;function Xt(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++vd,o=Date.now?Date.now():0;for(let i=0;i<
33
32
  16;i++)e[i]=(i<6?r>>>i*8:o>>>(i-6)*8)&255;}e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=[];for(let r=0;r<16;r++)n.push(e[r].toString(16).padStart(2,"0"));return `${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}\
34
- -${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var rg=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function ig(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 ko=class{id;exact=false;constructor(e="heuristic"){this.id=e;}count(e){if(e.length===0)return 0;let n=e.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],r=0;for(let o of n){let i=o[0];if(/\s/.test(i)){let s=(o.
33
+ -${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var lg=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function pg(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 xo=class{id;exact=false;constructor(e="heuristic"){this.id=e;}count(e){if(e.length===0)return 0;let n=e.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],r=0;for(let o of n){let i=o[0];if(/\s/.test(i)){let s=(o.
35
34
  match(/\n/g)??[]).length;r+=s+Math.floor(Math.max(0,o.length-1)/2);}else /[A-Za-z]/.test(i)?r+=Math.max(1,Math.ceil(o.length/4)):/\d/.test(i)?r+=Math.max(1,Math.ceil(o.length/2)):r+=1;}return Math.max(r,
36
- Math.ceil(e.length/4))}},Ct=new ko;var xo=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=Ct){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){
35
+ Math.ceil(e.length/4))}},Ct=new xo;var wo=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=Ct){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){
37
36
  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.
38
- get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},wo=new xo;var So=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}},$n={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini",
39
- "gpt-4.1-nano","o1","o1-mini","o3","o3-mini","o4-mini"],cl100k_base:["gpt-4","gpt-4-turbo","gpt-3.5-turbo","text-embedding-3-small","text-embedding-3-large"]};async function To(t,e={}){let n=e.codificaciones??
40
- ["o200k_base","cl100k_base"],r=false;for(let o of n){let i;try{i=await import(`gpt-tokenizer/encoding/${o}`);}catch{continue}if(typeof i.encode=="function"){t.register(new So(o,i)),r=true;for(let s of $n[o]??
41
- [])t.mapModel(s,o),t.mapModel(`openai/${s}`,o);}}return r}var gg=$n,bg=To;var Ws=2592e6,Js=.95,Ks=8,Et=class{avoidedLlm=0;baselineLlm=1;actualLlm=0;baselineRetrieval=0;actualRetrieval=0;baselineTools=0;actualTools=0;retries=0;baselineInput=0;actualInput=0;eliminatedInput=0;compressedInput=0;baselineOutput=0;actualOutput=0;eliminatedOutput=0;providerCachedInput=0;cacheWriteInputTokens=0;cacheWritePremiumUsd=0;providerCacheWritePremiumUsd=0;sentInputLocal=0;removedInputLocal=0;elididoLocal=0;compactedLocal=0;estimatorExact=false;repairOutput=0;repairInput=0;callsWithoutUsage=0;discoveryInput=0;discoveryOutput=0;extraCostUsd=0;cascadeInput=0;cascadeOutput=0;cascadeAttempt(e,n,r=1){
37
+ get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},So=new wo;var To=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}},Bn={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini",
38
+ "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 Co(t,e={}){let n=e.codificaciones??
39
+ ["o200k_base","cl100k_base"],r=false;for(let o of n){let i;try{i=await import(`gpt-tokenizer/encoding/${o}`);}catch{continue}if(typeof i.encode=="function"){t.register(new To(o,i)),r=true;for(let s of Bn[o]??
40
+ [])t.mapModel(s,o),t.mapModel(`openai/${s}`,o);}}return r}var Sg=Bn,Tg=Co;var Ks=2592e6,Gs=.95,Zs=8,Et=class{avoidedLlm=0;baselineLlm=1;actualLlm=0;baselineRetrieval=0;actualRetrieval=0;baselineTools=0;actualTools=0;retries=0;baselineInput=0;actualInput=0;eliminatedInput=0;compressedInput=0;baselineOutput=0;actualOutput=0;eliminatedOutput=0;providerCachedInput=0;cacheWriteInputTokens=0;cacheWritePremiumUsd=0;providerCacheWritePremiumUsd=0;sentInputLocal=0;removedInputLocal=0;elididoLocal=0;compactedLocal=0;estimatorExact=false;repairOutput=0;repairInput=0;callsWithoutUsage=0;discoveryInput=0;discoveryOutput=0;extraCostUsd=0;cascadeInput=0;cascadeOutput=0;cascadeAttempt(e,n,r=1){
42
41
  this.cascadeInput+=Math.max(0,e.inputTokens),this.cascadeOutput+=Math.max(0,e.outputTokens);let o=Math.max(0,e.cacheWriteInputTokens??0);this.extraCostUsd+=Math.max(0,e.inputTokens)/1e3*n.inputPer1k+Math.
43
42
  max(0,e.outputTokens)/1e3*n.outputPer1k+o/1e3*n.inputPer1k*Math.max(0,r-1);}cacheWritePremium(e,n,r){let o=Math.max(0,e);this.cacheWriteInputTokens+=o,this.cacheWritePremiumUsd+=o/1e3*r.inputPer1k*Math.
44
43
  max(0,n-1);}compressionReport=void 0;eliminate(e){this.eliminatedInput+=Math.max(0,e);}compress(e,n){this.compressedInput+=Math.max(0,e-n);}providerCached(e){this.providerCachedInput+=Math.max(0,e);}providerCacheWritePremium(e,n,r){
45
- let o=Math.max(0,e);this.providerCacheWritePremiumUsd+=o/1e3*r.inputPer1k*Math.max(0,n-1);}reference=null;referenceRejected=null;avoidCallByReference(e){this.avoidCall(e.creditedInputTokens,e.creditedOutputTokens),
46
- this.reference=e;}avoidCall(e,n){this.avoidedLlm+=1,this.actualLlm=0,this.baselineInput=e,this.baselineOutput=n;}get publishedBaselineOutput(){return this.avoidedLlm===0?Math.max(0,this.actualOutput-this.
47
- repairOutput-this.discoveryOutput):this.baselineOutput}estimateCost(e){let n=this.avoidedLlm===0,r="estimated";if(n)if(this.callsWithoutUsage>0)this.baselineInput=0,r="unmeasured";else if(this.actualInput>
48
- 0&&this.sentInputLocal>0){let h=this.actualInput/this.sentInputLocal,m=Math.max(0,this.actualInput-this.repairInput-this.discoveryInput);this.baselineInput=m+Math.round(h*this.removedInputLocal),r=this.
49
- removedInputLocal===0?"measured":"estimated";}else this.actualInput>0?(this.baselineInput=this.actualInput,r="measured"):(this.baselineInput=0,r="unmeasured");let o=n?Math.max(0,this.actualOutput-this.
50
- repairOutput-this.discoveryOutput):this.baselineOutput,i=e.cachedInputPer1k??e.inputPer1k,s=Math.min(this.providerCachedInput,this.actualInput),a=h=>Math.max(0,h-s)/1e3*e.inputPer1k+s/1e3*i,c=n?null:this.
51
- reference,u=n?this.providerCacheWritePremiumUsd:0,l=c?c.tierFactor*(this.baselineInput/1e3*c.cachedInputPer1k+this.baselineOutput/1e3*c.outputPer1k):a(this.baselineInput)+o/1e3*e.outputPer1k+u;c&&(r=l>
52
- 0?"reference":"estimated");let d=a(this.actualInput)+this.actualOutput/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd+u,p=l===0?0:1-d/l;return {baselineEstimate:Hs(l),actual:Hs(d),netSavings:md(
53
- p),basis:r}}};function Hs(t){return Math.round(t*1e10)/1e10}function md(t){return Math.round(t*1e6)/1e6}var hd=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
44
+ let o=Math.max(0,e);this.providerCacheWritePremiumUsd+=o/1e3*r.inputPer1k*Math.max(0,n-1);}unbilledInput=0;unbilledOutput=0;unbilledCachedInput=0;servedUnbilledRefusal=false;unbilledCall(e){this.unbilledInput+=
45
+ Math.max(0,e.inputTokens),this.unbilledOutput+=Math.max(0,e.outputTokens),this.unbilledCachedInput+=Math.max(0,e.cachedInputTokens??0);}reference=null;referenceRejected=null;avoidCallByReference(e){this.
46
+ avoidCall(e.creditedInputTokens,e.creditedOutputTokens),this.reference=e;}avoidCall(e,n){this.avoidedLlm+=1,this.actualLlm=0,this.baselineInput=e,this.baselineOutput=n;}get publishedBaselineOutput(){return this.
47
+ avoidedLlm===0?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):this.baselineOutput}estimateCost(e){let n=this.avoidedLlm===0,r="estimated";if(n)if(this.callsWithoutUsage>0)this.baselineInput=
48
+ 0,r="unmeasured";else if(this.actualInput>0&&this.sentInputLocal>0){let g=this.actualInput/this.sentInputLocal,f=Math.max(0,this.actualInput-this.repairInput-this.discoveryInput);this.baselineInput=f+
49
+ Math.round(g*this.removedInputLocal),r=this.removedInputLocal===0?"measured":"estimated";}else this.actualInput>0?(this.baselineInput=this.actualInput,r="measured"):(this.baselineInput=0,r="unmeasured");
50
+ let o=n?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):this.baselineOutput,i=e.cachedInputPer1k??e.inputPer1k,s=Math.max(0,this.actualInput-this.unbilledInput),a=Math.max(0,this.
51
+ actualOutput-this.unbilledOutput),c=Math.min(Math.max(0,this.providerCachedInput-this.unbilledCachedInput),s),u=g=>Math.max(0,g-c)/1e3*e.inputPer1k+c/1e3*i,l=n?null:this.reference,d=n?this.providerCacheWritePremiumUsd:
52
+ 0,p=this.servedUnbilledRefusal?0:l?l.tierFactor*(this.baselineInput/1e3*l.cachedInputPer1k+this.baselineOutput/1e3*l.outputPer1k):u(this.baselineInput)+o/1e3*e.outputPer1k+d;l&&(r=p>0?"reference":"est\
53
+ imated"),this.servedUnbilledRefusal&&(l?r="estimated":n&&r==="estimated"&&(r="measured"));let h=u(s)+a/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd+d,m=p===0?0:1-h/p;return {baselineEstimate:Js(
54
+ p),actual:Js(h),netSavings:yd(m),basis:r}}};function Js(t){return Math.round(t*1e10)/1e10}function yd(t){return Math.round(t*1e6)/1e6}var kd=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
54
55
  4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
55
56
  1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,
56
- 1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),gd=new TextEncoder;function Re(t,e){return t>>>e|t<<32-e}function Gs(t){let e=gd.encode(t),n=e.length*
57
+ 1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),xd=new TextEncoder;function Ie(t,e){return t>>>e|t<<32-e}function Ys(t){let e=xd.encode(t),n=e.length*
57
58
  8,r=(e.length+8>>6)+1,o=new Uint8Array(r*64);o.set(e),o[e.length]=128;let i=new DataView(o.buffer);i.setUint32(o.length-8,Math.floor(n/4294967296)),i.setUint32(o.length-4,n>>>0);let s=new Uint32Array(
58
59
  [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]=i.getUint32(u+b*4);for(let b=16;b<
59
- 64;b++){let y=a[b-15],k=a[b-2],T=Re(y,7)^Re(y,18)^y>>>3,w=Re(k,17)^Re(k,19)^k>>>10;a[b]=a[b-16]+T+a[b-7]+w|0;}let l=s[0],d=s[1],p=s[2],h=s[3],m=s[4],g=s[5],f=s[6],v=s[7];for(let b=0;b<64;b++){let y=Re(
60
- m,6)^Re(m,11)^Re(m,25),k=m&g^~m&f,T=v+y+k+hd[b]+a[b]|0,w=Re(l,2)^Re(l,13)^Re(l,22),P=l&d^l&p^d&p,x=w+P|0;v=f,f=g,g=m,m=h+T|0,h=p,p=d,d=l,l=T+x|0;}s[0]=s[0]+l|0,s[1]=s[1]+d|0,s[2]=s[2]+p|0,s[3]=s[3]+h|0,
61
- s[4]=s[4]+m|0,s[5]=s[5]+g|0,s[6]=s[6]+f|0,s[7]=s[7]+v|0;}let c="";for(let u=0;u<8;u++)c+=(s[u]>>>0).toString(16).padStart(8,"0");return c}var bd=/\s+/g,vd=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],yd=/[¿?¡!;.,:'"·•]/g,kd=/([a-z])\p{M}+/gu,xd=/(^|\s)\p{M}+/gu,
62
- Co=/\p{L}/u;function me(t){return t>="0"&&t<="9"}function Bn(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,r]of vd)e=e.replace(n,r);return e=e.normalize("NFD").replace(kd,"$1").replace(xd,"$1").
63
- normalize("NFC"),e=e.replace(yd,(n,r,o)=>{let i=o[r-1]??"",s=o[r+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return me(i)&&me(s)?n:"";case "!":return me(i)?n:"";case ".":case ",":return me(i)&&
64
- me(s)||me(s)&&!me(i)&&!Co.test(i)?n:"";case ":":return me(i)&&me(s)?n:"";case "'":case '"':return Co.test(i)&&Co.test(s)||me(i)||me(s)?n:"";default:return me(i)||me(s)?n:""}}),e.replace(bd," ").trim()}function Y(t){
65
- return Gs(t)}function he(t){return JSON.stringify(Eo(t))}function Eo(t){if(Array.isArray(t))return t.map(Eo);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=Eo(t[n]);return e}
66
- return t}function Po(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function wd(t){let e=new Map,n=o=>{if(typeof o!="string"||o==="")return {sin:o??null};let i=e.
60
+ 64;b++){let y=a[b-15],k=a[b-2],T=Ie(y,7)^Ie(y,18)^y>>>3,x=Ie(k,17)^Ie(k,19)^k>>>10;a[b]=a[b-16]+T+a[b-7]+x|0;}let l=s[0],d=s[1],p=s[2],h=s[3],m=s[4],g=s[5],f=s[6],v=s[7];for(let b=0;b<64;b++){let y=Ie(
61
+ m,6)^Ie(m,11)^Ie(m,25),k=m&g^~m&f,T=v+y+k+kd[b]+a[b]|0,x=Ie(l,2)^Ie(l,13)^Ie(l,22),R=l&d^l&p^d&p,D=x+R|0;v=f,f=g,g=m,m=h+T|0,h=p,p=d,d=l,l=T+D|0;}s[0]=s[0]+l|0,s[1]=s[1]+d|0,s[2]=s[2]+p|0,s[3]=s[3]+h|0,
62
+ s[4]=s[4]+m|0,s[5]=s[5]+g|0,s[6]=s[6]+f|0,s[7]=s[7]+v|0;}let c="";for(let u=0;u<8;u++)c+=(s[u]>>>0).toString(16).padStart(8,"0");return c}var wd=/\s+/g,Sd=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],Td=/[¿?¡!;.,:'"·•]/g,Cd=/([a-z])\p{M}+/gu,Ed=/(^|\s)\p{M}+/gu,
63
+ Eo=/\p{L}/u;function he(t){return t>="0"&&t<="9"}function Fn(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,r]of Sd)e=e.replace(n,r);return e=e.normalize("NFD").replace(Cd,"$1").replace(Ed,"$1").
64
+ normalize("NFC"),e=e.replace(Td,(n,r,o)=>{let i=o[r-1]??"",s=o[r+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return he(i)&&he(s)?n:"";case "!":return he(i)?n:"";case ".":case ",":return he(i)&&
65
+ he(s)||he(s)&&!he(i)&&!Eo.test(i)?n:"";case ":":return he(i)&&he(s)?n:"";case "'":case '"':return Eo.test(i)&&Eo.test(s)||he(i)||he(s)?n:"";default:return he(i)||he(s)?n:""}}),e.replace(wd," ").trim()}function Y(t){
66
+ return Ys(t)}function ge(t){return JSON.stringify(Po(t))}function Po(t){if(Array.isArray(t))return t.map(Po);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=Po(t[n]);return e}
67
+ return t}function Ro(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function Pd(t){let e=new Map,n=o=>{if(typeof o!="string"||o==="")return {sin:o??null};let i=e.
67
68
  get(o);return i===void 0&&e.set(o,i=e.size),i},r=t.map(o=>{if(o.role==="assistant")return !o.toolCalls||o.toolCalls.length===0?null:{calls:o.toolCalls.map(a=>({...a.id!=null?{id:n(a.id)}:{},name:a.name,
68
69
  arguments:a.arguments}))};if(o.role!=="tool")return null;let i=o.toolCallId??o.metadata?.tool_call_id,s={...i!==void 0?{id:n(i)}:{},...o.isError===true?{isError:true}:{},...o.name?{name:o.name}:{}};return Object.
69
- keys(s).length>0?s:null});if(!r.every(o=>o===null))return Y(he(r))}function Ro(t){let e=t.context??{},n=wd(t.messages),r=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(`
70
- `),o=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${Bn(s.content)}`).join(`
71
- `),i=(t.tools??[]).map(s=>({id:s.id,risk:s.risk,parameters:s.parameters??null})).sort((s,a)=>s.id.localeCompare(a.id));return {model:t.model,modelFamily:Po(t.model),messages:t.messages,normalizedText:o,
72
- systemPromptHash:Y(r),toolsetHash:Y(he(i)),...n!==void 0?{toolTurnsHash:n}:{},structuredDataHash:t.structuredData!==void 0?Y(he(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.
70
+ keys(s).length>0?s:null});if(!r.every(o=>o===null))return Y(ge(r))}function Do(t){let e=t.context??{},n=Pd(t.messages),r=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(`
71
+ `),o=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${Fn(s.content)}`).join(`
72
+ `),i=(t.tools??[]).map(s=>({id:s.id,risk:s.risk,parameters:s.parameters??null})).sort((s,a)=>s.id.localeCompare(a.id));return {model:t.model,modelFamily:Ro(t.model),messages:t.messages,normalizedText:o,
73
+ systemPromptHash:Y(r),toolsetHash:Y(ge(i)),...n!==void 0?{toolTurnsHash:n}:{},structuredDataHash:t.structuredData!==void 0?Y(ge(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.
73
74
  contractId??"none",contractId:t.response?.contractId??null,temperature:t.temperature??null,seed:t.seed??null,tenantId:e.tenantId??"anonymous",authorizationScope:e.authorizationScope??"default",principal:e.
74
- sessionId??null,locale:e.locale??"und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var Zs="n2";function Ys(t){return t.toolTurnsHash!==void 0?{toolTurns:t.toolTurnsHash}:{}}function Do(t,e={}){let n=e.servedModel??t.model,r=he({tenant:t.tenantId,scope:t.authorizationScope,principal:t.
75
- principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily:Po(n),model:n,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,...Ys(t),data:t.structuredDataHash,
76
- locale:t.locale,temperature:t.temperature,seed:t.seed,knowledgeEpoch:t.knowledgeEpoch,freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${Zs}:${Y(r)}`}function Qs(t,e={}){
77
- let n=he({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,model:e.servedModel??t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.
78
- toolsetHash,...Ys(t),data:t.structuredDataHash,temperature:t.temperature,seed:t.seed,deferrable:e.deferrable===true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:infl\
79
- ight:${Zs}:${Y(n)}`}var Sd=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\
75
+ sessionId??null,locale:e.locale??"und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var Qs="n2";function Xs(t){return t.toolTurnsHash!==void 0?{toolTurns:t.toolTurnsHash}:{}}function Io(t,e={}){let n=e.servedModel??t.model,r=ge({tenant:t.tenantId,scope:t.authorizationScope,principal:t.
76
+ principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily:Ro(n),model:n,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,...Xs(t),data:t.structuredDataHash,
77
+ locale:t.locale,temperature:t.temperature,seed:t.seed,knowledgeEpoch:t.knowledgeEpoch,freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${Qs}:${Y(r)}`}function ea(t,e={}){
78
+ let n=ge({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,model:e.servedModel??t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.
79
+ toolsetHash,...Xs(t),data:t.structuredDataHash,temperature:t.temperature,seed:t.seed,deferrable:e.deferrable===true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:infl\
80
+ ight:${Qs}:${Y(n)}`}var Rd=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\
80
81
  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|\
81
82
  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\
82
83
  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\
83
84
  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\
84
- nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),Td=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nu\
85
+ nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),Dd=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nu\
85
86
  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\
86
87
  |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\
87
88
  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\
88
89
  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\
89
- 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 Fn(t){let e=[],n=t.normalizedText,
90
- r=(t.original.tools??[]).some(b=>b.risk==="write"||b.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||Sd.test(n),i=Td.test(n),s=(t.temperature??0)>.3&&t.seed==null,a=t.messages.
90
+ 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 zn(t){let e=[],n=t.normalizedText,
91
+ r=(t.original.tools??[]).some(b=>b.risk==="write"||b.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||Rd.test(n),i=Dd.test(n),s=(t.temperature??0)>.3&&t.seed==null,a=t.messages.
91
92
  filter(b=>b.role==="user").length,c=(t.original?.tools?.length??0)>0,u=t.messages.some(b=>b.role==="tool"||b.role==="assistant"&&(b.toolCalls?.length??0)>0),l=c||u||a>1,d=t.original?.savings?.semanticCache===
92
93
  "include-agentic";r&&e.push("write/destructive tools present"),o&&e.push("freshness-sensitive request"),i&&e.push("personalized/account-scoped request"),s&&e.push("stochastic sampling (temp>0.3, no se\
93
94
  ed)");let p=o&&(t.freshnessBucket==null||t.freshnessBucket==="any"),h=t.freshnessBucket==="live",m=i&&t.principal==null,g=!s&&!p&&!h&&!m&&!r;r&&e.push("write/destructive tools \u2192 exact cache off (side \
@@ -95,249 +96,249 @@ effects must execute)"),h&&e.push("freshnessBucket=live \u2192 exact cache off (
95
96
  personalized request with no principal (context.sessionId) \u2192 exact cache off");let f=!r&&!o&&!i&&!s&&t.freshnessBucket!=="day"&&(!l||d);l&&!d?e.push('agentic request (tools, tool calls/results or\
96
97
  more than one user turn) \u2192 semantic cache off by default (opt in with savings.semanticCache: "include-agentic")'):l&&d&&e.push('agentic request admitted to the semantic cache by savings.semantic\
97
98
  Cache: "include-agentic" (write, freshness, personalization and sampling vetoes still apply)');let v=!r&&!o&&!i&&!s&&t.freshnessBucket!=="day";return {allowExactCache:g,allowSemanticCache:f,allowElision:v,
98
- allowSingleflight:!r&&!m,allowCompression:true,requiresFreshData:o,hasSideEffects:r,isPersonalized:i,isAgentic:l,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var zn=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.
99
- now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),Xs(n.value)):null}async set(e,n,r){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let o=this.store.keys().
100
- next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:Xs(n),expiresAtMs:r!=null?this.now()+r:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};function Xs(t){
101
- try{return structuredClone(t)}catch{return t}}var qn=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.
99
+ allowSingleflight:!r&&!m,allowCompression:true,requiresFreshData:o,hasSideEffects:r,isPersonalized:i,isAgentic:l,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var qn=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.
100
+ now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),ta(n.value)):null}async set(e,n,r){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let o=this.store.keys().
101
+ next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:ta(n),expiresAtMs:r!=null?this.now()+r:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};function ta(t){
102
+ try{return structuredClone(t)}catch{return t}}var Vn=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.
102
103
  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.
103
- waiters.get(e)??1)+1),n}get activeKeys(){return this.inflight.size}};function tn(t){return !Number.isFinite(t)||t<0?-1:t>=1?1e3:Math.floor(t*1e3+1e-9)}var nn=t=>t/1e3;function Cd(t,e,n){if(e>=t)return 1;if(e<0)return 0;if(n<=0)return 1;if(n>=1)return 0;let r=Math.log(n),
104
- o=Math.log1p(-n),i=t*o,s=[i],a=i;for(let u=0;u<e;u++)i+=Math.log(t-u)-Math.log(u+1)+r-o,s.push(i),i>a&&(a=i);let c=0;for(let u of s)c+=Math.exp(u-a);return Math.min(1,Math.exp(a+Math.log(c)))}function Ao(t,e,n,r){
105
- return t<=0||e>=t*n?false:Cd(t,e,n)<=r}function Hn(t,e){return Math.ceil(Math.log(e)/Math.log1p(-t))}function Vn(t,e){return 6*t/(Math.PI*Math.PI*(e+1)*(e+1))}var Je=class{total=new Uint32Array(1001);erroneas=new Uint32Array(
104
+ waiters.get(e)??1)+1),n}get activeKeys(){return this.inflight.size}};function nn(t){return !Number.isFinite(t)||t<0?-1:t>=1?1e3:Math.floor(t*1e3+1e-9)}var rn=t=>t/1e3;function Id(t,e,n){if(e>=t)return 1;if(e<0)return 0;if(n<=0)return 1;if(n>=1)return 0;let r=Math.log(n),
105
+ o=Math.log1p(-n),i=t*o,s=[i],a=i;for(let u=0;u<e;u++)i+=Math.log(t-u)-Math.log(u+1)+r-o,s.push(i),i>a&&(a=i);let c=0;for(let u of s)c+=Math.exp(u-a);return Math.min(1,Math.exp(a+Math.log(c)))}function Oo(t,e,n,r){
106
+ return t<=0||e>=t*n?false:Id(t,e,n)<=r}function Wn(t,e){return Math.ceil(Math.log(e)/Math.log1p(-t))}function Un(t,e){return 6*t/(Math.PI*Math.PI*(e+1)*(e+1))}var Ke=class{total=new Uint32Array(1001);erroneas=new Uint32Array(
106
107
  1001);n=0;anotar(e,n){this.total[e]++,n||this.erroneas[e]++,this.n++;}copiarDe(e){this.total.set(e.total),this.erroneas.set(e.erroneas),this.n=e.n;}acumulados(){let e=new Uint32Array(1002),n=new Uint32Array(
107
- 1002);for(let r=1e3;r>=0;r--)e[r]=e[r+1]+this.total[r],n[r]=n[r+1]+this.erroneas[r];return {n:e,e:n}}};function Ed(t,e,n){let{n:r,e:o}=t.acumulados(),i=null;for(let s=1e3;s>=0;s--)Ao(r[s],o[s],e,n)&&(i=
108
- s);if(i==null)return null;for(;i<1e3&&t.total[i]===0;)i++;return i}function Oo(t,e,n){let r=[];for(let o of [1,1/4,1/16,1/64,1/256]){let i=Ed(t,e,n*o);i!=null&&r.push(i);}return r}function Mo(t,e,n,r){let{
109
- n:o,e:i}=t.acumulados(),s=[...new Set(e)].sort((c,u)=>u-c),a=null;for(let c of s){if(!Ao(o[c],i[c],n,r))break;a={indice:c,retenidas:o[c],erroneas:i[c]};}return a}var en=class t{constructor(e,n){this.delta=
110
- e;this.alfa=n;this.primeraMirada=2*Hn(e,Vn(n,0));}delta;alfa;seleccion=new Je;retenida=new Je;etiquetas=0;miradas=0;candidatoPrevio=null;certificado=null;primeraMirada;etiquetasDeLaMirada(e){return Io(
108
+ 1002);for(let r=1e3;r>=0;r--)e[r]=e[r+1]+this.total[r],n[r]=n[r+1]+this.erroneas[r];return {n:e,e:n}}};function _d(t,e,n){let{n:r,e:o}=t.acumulados(),i=null;for(let s=1e3;s>=0;s--)Oo(r[s],o[s],e,n)&&(i=
109
+ s);if(i==null)return null;for(;i<1e3&&t.total[i]===0;)i++;return i}function Mo(t,e,n){let r=[];for(let o of [1,1/4,1/16,1/64,1/256]){let i=_d(t,e,n*o);i!=null&&r.push(i);}return r}function Lo(t,e,n,r){let{
110
+ n:o,e:i}=t.acumulados(),s=[...new Set(e)].sort((c,u)=>u-c),a=null;for(let c of s){if(!Oo(o[c],i[c],n,r))break;a={indice:c,retenidas:o[c],erroneas:i[c]};}return a}var tn=class t{constructor(e,n){this.delta=
111
+ e;this.alfa=n;this.primeraMirada=2*Wn(e,Un(n,0));}delta;alfa;seleccion=new Ke;retenida=new Ke;etiquetas=0;miradas=0;candidatoPrevio=null;certificado=null;primeraMirada;etiquetasDeLaMirada(e){return _o(
111
112
  this.primeraMirada,e)}exportar(){return {labeled:this.etiquetas,looks:this.miradas,previousCandidate:this.candidatoPrevio,certified:this.certificado?{floorIndex:this.certificado.indice,heldOut:this.certificado.
112
- retenidas,wrong:this.certificado.erroneas}:null,selection:ea(this.seleccion),heldOut:ea(this.retenida)}}static restaurar(e,n,r,o){let i=new t(e,n),s=f=>{throw new we(`importCalibration: ${o}: ${f}`)};
113
- (r===null||typeof r!="object"||Array.isArray(r))&&s("not an object");let a=r,c=a.labeled;Xt(c)||s("`labeled` must be a non-negative integer");let u=c,l=ta(a.selection,`${o}.selection`),d=ta(a.heldOut,
114
- `${o}.heldOut`);(l.n!==Math.ceil(u/2)||d.n!==Math.floor(u/2))&&s(`the two halves hold ${l.n} and ${d.n} labels, but ${u} labels split by arrival order give ${Math.ceil(u/2)} and ${Math.floor(u/2)}`);let p=Pd(
113
+ retenidas,wrong:this.certificado.erroneas}:null,selection:na(this.seleccion),heldOut:na(this.retenida)}}static restaurar(e,n,r,o){let i=new t(e,n),s=f=>{throw new Te(`importCalibration: ${o}: ${f}`)};
114
+ (r===null||typeof r!="object"||Array.isArray(r))&&s("not an object");let a=r,c=a.labeled;en(c)||s("`labeled` must be a non-negative integer");let u=c,l=ra(a.selection,`${o}.selection`),d=ra(a.heldOut,
115
+ `${o}.heldOut`);(l.n!==Math.ceil(u/2)||d.n!==Math.floor(u/2))&&s(`the two halves hold ${l.n} and ${d.n} labels, but ${u} labels split by arrival order give ${Math.ceil(u/2)} and ${Math.floor(u/2)}`);let p=Ad(
115
116
  i.primeraMirada,u);a.looks!==p&&s(`\`looks\` is ${String(a.looks)}, but ${u} labels have already spent ${p} tests of the confidence budget; a state cannot start that spending over`);let h=a.previousCandidate;
116
- h!==null&&!_o(h)&&s("`previousCandidate` must be null or a grid index");let m=a.certified,g=null;if(m!==null){(m===void 0||typeof m!="object"||Array.isArray(m))&&s("`certified` must be null or an obje\
117
- ct");let f=m;_o(f.floorIndex)||s("`certified.floorIndex` must be a grid index"),(!Xt(f.heldOut)||!Xt(f.wrong))&&s("`certified.heldOut` and `certified.wrong` must be non-negative integers"),g={indice:f.
118
- floorIndex,retenidas:f.heldOut,erroneas:f.wrong},p===0&&s("a floor is certified but no test has run yet"),h!==g.indice&&s("`previousCandidate` must be the certified floor");let v=p-1,b=Io(i.primeraMirada,
119
- v),y=Math.floor(b/2);(g.retenidas>y||g.erroneas>g.retenidas)&&s("the certificate counts more held-out labels than there were when it was issued"),Ao(g.retenidas,g.erroneas,e,Vn(n,v))||s("the certifica\
120
- te does not pass the test it claims to have passed");let{n:k,e:T}=d.acumulados(),w=k[g.indice]-g.retenidas,P=T[g.indice]-g.erroneas;(w<0||P<0||P>w||w>d.n-y)&&s("the held-out labels at the floor do not\
117
+ h!==null&&!Ao(h)&&s("`previousCandidate` must be null or a grid index");let m=a.certified,g=null;if(m!==null){(m===void 0||typeof m!="object"||Array.isArray(m))&&s("`certified` must be null or an obje\
118
+ ct");let f=m;Ao(f.floorIndex)||s("`certified.floorIndex` must be a grid index"),(!en(f.heldOut)||!en(f.wrong))&&s("`certified.heldOut` and `certified.wrong` must be non-negative integers"),g={indice:f.
119
+ floorIndex,retenidas:f.heldOut,erroneas:f.wrong},p===0&&s("a floor is certified but no test has run yet"),h!==g.indice&&s("`previousCandidate` must be the certified floor");let v=p-1,b=_o(i.primeraMirada,
120
+ v),y=Math.floor(b/2);(g.retenidas>y||g.erroneas>g.retenidas)&&s("the certificate counts more held-out labels than there were when it was issued"),Oo(g.retenidas,g.erroneas,e,Un(n,v))||s("the certifica\
121
+ te does not pass the test it claims to have passed");let{n:k,e:T}=d.acumulados(),x=k[g.indice]-g.retenidas,R=T[g.indice]-g.erroneas;(x<0||R<0||R>x||x>d.n-y)&&s("the held-out labels at the floor do not\
121
122
  extend the ones the certificate counted");}else p===0&&h!==null&&s("`previousCandidate` is set but no test has run yet");return i.seleccion.copiarDe(l),i.retenida.copiarDe(d),i.etiquetas=u,i.miradas=p,
122
- i.candidatoPrevio=h,i.certificado=g,i}anotar(e,n){let r=tn(e);r<0||((this.etiquetas%2===0?this.seleccion:this.retenida).anotar(r,n),this.etiquetas++,this.etiquetas>=this.etiquetasDeLaMirada(this.miradas)&&
123
- this.mirar());}mirar(){let e=Vn(this.alfa,this.miradas);this.miradas++;let n=Oo(this.seleccion,this.delta,e),r=this.candidatoPrevio==null?n:[...n,this.candidatoPrevio],o=Mo(this.retenida,r,this.delta,e);
123
+ i.candidatoPrevio=h,i.certificado=g,i}anotar(e,n){let r=nn(e);r<0||((this.etiquetas%2===0?this.seleccion:this.retenida).anotar(r,n),this.etiquetas++,this.etiquetas>=this.etiquetasDeLaMirada(this.miradas)&&
124
+ this.mirar());}mirar(){let e=Un(this.alfa,this.miradas);this.miradas++;let n=Mo(this.seleccion,this.delta,e),r=this.candidatoPrevio==null?n:[...n,this.candidatoPrevio],o=Lo(this.retenida,r,this.delta,e);
124
125
  this.certificado=o,this.candidatoPrevio=o?.indice??n[n.length-1]??this.candidatoPrevio;}get suelo(){return this.certificado?.indice??null}resumen(){return {suelo:this.suelo,etiquetas:this.etiquetas,retenidas:this.
125
- retenida.n,retenidasEnSuelo:this.certificado?.retenidas??0,erroneasEnSuelo:this.certificado?.erroneas??0,miradas:this.miradas,minimasParaLaSiguiente:Hn(this.delta,Vn(this.alfa,this.miradas)),etiquetasParaLaSiguiente:this.
126
- etiquetasDeLaMirada(this.miradas)}}},we=class extends Error{constructor(e){super(`[bvsala] ${e}`),this.name="CalibrationStateError";}},na="bvsala.semantic-calibration",Un=1,ra=["single_shot","agentic"];
127
- function oa(t,e){let n={};for(let r of ra){let o=e.get(r);o&&(n[r]=o.exportar());}return {format:na,version:Un,embedder:t.embedder,verifier:t.verifier,judge:t.judge,config:{maxErrorRate:t.maxErrorRate,confidence:t.
128
- confidence,similarityThreshold:t.similarityThreshold,grid:1e3},segments:n}}function ia(t,e){let n=l=>{throw new we(`importCalibration: ${l}`)};(t===null||typeof t!="object"||Array.isArray(t))&&n("the \
129
- state must be an object");let r=t;r.format!==na&&n(`not a semantic calibration state (format ${JSON.stringify(r.format)})`);let o=r.version;typeof o=="number"&&o>Un&&n(`this state was exported by a ne\
130
- wer SDK (version ${o}); this one reads version ${Un}`),o!==Un&&n(`unknown state version ${JSON.stringify(o)}`);let i=r.config??{},s=[],a=(l,d,p)=>{d!==p&&s.push(`${l}: ${JSON.stringify(d)} in the stat\
126
+ retenida.n,retenidasEnSuelo:this.certificado?.retenidas??0,erroneasEnSuelo:this.certificado?.erroneas??0,miradas:this.miradas,minimasParaLaSiguiente:Wn(this.delta,Un(this.alfa,this.miradas)),etiquetasParaLaSiguiente:this.
127
+ etiquetasDeLaMirada(this.miradas)}}},Te=class extends Error{constructor(e){super(`[bvsala] ${e}`),this.name="CalibrationStateError";}},oa="bvsala.semantic-calibration",Hn=1,ia=["single_shot","agentic"];
128
+ function sa(t,e){let n={};for(let r of ia){let o=e.get(r);o&&(n[r]=o.exportar());}return {format:oa,version:Hn,embedder:t.embedder,verifier:t.verifier,judge:t.judge,config:{maxErrorRate:t.maxErrorRate,confidence:t.
129
+ confidence,similarityThreshold:t.similarityThreshold,grid:1e3},segments:n}}function aa(t,e){let n=l=>{throw new Te(`importCalibration: ${l}`)};(t===null||typeof t!="object"||Array.isArray(t))&&n("the \
130
+ state must be an object");let r=t;r.format!==oa&&n(`not a semantic calibration state (format ${JSON.stringify(r.format)})`);let o=r.version;typeof o=="number"&&o>Hn&&n(`this state was exported by a ne\
131
+ wer SDK (version ${o}); this one reads version ${Hn}`),o!==Hn&&n(`unknown state version ${JSON.stringify(o)}`);let i=r.config??{},s=[],a=(l,d,p)=>{d!==p&&s.push(`${l}: ${JSON.stringify(d)} in the stat\
131
132
  e, ${JSON.stringify(p)} here`);};a("embedder",r.embedder,e.embedder),a("verifier",r.verifier,e.verifier),a("judge",r.judge,e.judge),a("maxErrorRate",i.maxErrorRate,e.maxErrorRate),a("confidence",i.confidence,
132
133
  e.confidence),a("similarityThreshold",i.similarityThreshold,e.similarityThreshold),a("grid",i.grid,1e3),s.length>0&&n(`the state was recorded under a different setup (${s.join("; ")}). A floor certifi\
133
134
  ed under one setup says nothing about another: start a new calibration instead`);let c=r.segments;(c===null||typeof c!="object"||Array.isArray(c))&&n("`segments` must be an object");let u=new Map;for(let[
134
- l,d]of Object.entries(c))ra.includes(l)||n(`unknown segment ${JSON.stringify(l)}`),u.set(l,en.restaurar(e.maxErrorRate,1-e.confidence,d,`segments.${l}`));return u}function Io(t,e){return Math.ceil(t*1.5**
135
- e)}function Pd(t,e){let n=0;for(;Io(t,n)<=e;)n++;return n}function Xt(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=4294967295}function _o(t){return typeof t=="number"&&Number.isInteger(
136
- t)&&t>=0&&t<=1e3}function ea(t){let e=[];for(let n=0;n<=1e3;n++)t.total[n]>0&&e.push([n,t.total[n],t.erroneas[n]]);return e}function ta(t,e){let n=i=>{throw new we(`importCalibration: ${e}: ${i}`)};Array.
137
- isArray(t)||n("must be an array of [gridIndex, labels, wrong]");let r=new Je,o=-1;for(let i of t){(!Array.isArray(i)||i.length!==3)&&n("each entry must be [gridIndex, labels, wrong]");let[s,a,c]=i;(!_o(
138
- s)||s<=o)&&n("grid indices must be increasing integers in [0, 1000]"),(!Xt(a)||a===0)&&n("label counts must be positive integers"),(!Xt(c)||c>a)&&n("wrong counts must be integers between 0 and the lab\
139
- el count"),r.total[s]=a,r.erroneas[s]=c,r.n+=a,o=s;}return r.n>4294967295&&n("too many labels"),r}function Wn(t){let{maxErrorRate:e}=t,n=t.confidence??.95,r=t.auditRate??.05;if(!(e>0&&e<=.5))throw new RangeError(
135
+ l,d]of Object.entries(c))ia.includes(l)||n(`unknown segment ${JSON.stringify(l)}`),u.set(l,tn.restaurar(e.maxErrorRate,1-e.confidence,d,`segments.${l}`));return u}function _o(t,e){return Math.ceil(t*1.5**
136
+ e)}function Ad(t,e){let n=0;for(;_o(t,n)<=e;)n++;return n}function en(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=4294967295}function Ao(t){return typeof t=="number"&&Number.isInteger(
137
+ t)&&t>=0&&t<=1e3}function na(t){let e=[];for(let n=0;n<=1e3;n++)t.total[n]>0&&e.push([n,t.total[n],t.erroneas[n]]);return e}function ra(t,e){let n=i=>{throw new Te(`importCalibration: ${e}: ${i}`)};Array.
138
+ isArray(t)||n("must be an array of [gridIndex, labels, wrong]");let r=new Ke,o=-1;for(let i of t){(!Array.isArray(i)||i.length!==3)&&n("each entry must be [gridIndex, labels, wrong]");let[s,a,c]=i;(!Ao(
139
+ s)||s<=o)&&n("grid indices must be increasing integers in [0, 1000]"),(!en(a)||a===0)&&n("label counts must be positive integers"),(!en(c)||c>a)&&n("wrong counts must be integers between 0 and the lab\
140
+ el count"),r.total[s]=a,r.erroneas[s]=c,r.n+=a,o=s;}return r.n>4294967295&&n("too many labels"),r}function Jn(t){let{maxErrorRate:e}=t,n=t.confidence??.95,r=t.auditRate??.05;if(!(e>0&&e<=.5))throw new RangeError(
140
141
  `calibration.maxErrorRate must be in (0, 0.5]; got ${e}`);if(!(n>.5&&n<1))throw new RangeError(`calibration.confidence must be in (0.5, 1); got ${n}`);if(!(r>=0&&r<1))throw new RangeError(`calibration\
141
- .auditRate must be in [0, 1); got ${r}`);return {maxErrorRate:e,confidence:n,auditRate:r}}function sa(t){let e=t>>>0;return ()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>
142
- 7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function Lo(t,e){let n=o=>o!==null&&typeof o=="object";if(n(t.data)&&n(e.data))return Jn(t.data)===Jn(e.data);let r=o=>o.trim().replace(/\s+/g," ");return r(t.text)===r(e.text)}function Jn(t){if(Array.
143
- isArray(t))return `[${t.map(Jn).join(",")}]`;if(t!==null&&typeof t=="object"){let e=t;return `{${Object.keys(e).sort().filter(n=>e[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Jn(e[n])}`).join(",")}}`}return JSON.
144
- stringify(t)??"null"}function Fg(t,e){let{maxErrorRate:n,confidence:r}=Wn(e),o=1-r,i=new Je,s=new Je,a=sa(1592642065),c=0;for(let l of t){let d=tn(l.score),p=a()<.5;d<0||((p?i:s).anotar(d,l.correct),c++);}
145
- let u=Mo(s,Oo(i,n,o),n,o);return {maxErrorRate:n,confidence:r,floor:u?nn(u.indice):null,labeled:c,heldOut:s.n,heldOutAtFloor:u?.retenidas??0,wrongHeldOutAtFloor:u?.erroneas??0,minHeldOutToCertify:Hn(n,
146
- o)}}function Rd(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 Dd(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(
147
- Boolean)}function Id(t){let e=new Array(256).fill(0),n=Dd(t);if(n.length===0)return e;let r=new Map;for(let i=0;i<n.length;i++){let s=n[i];if(r.set(s,(r.get(s)??0)+1),i+1<n.length){let a=`${s}\0${n[i+
148
- 1]}`;r.set(a,(r.get(a)??0)+1);}}for(let[i,s]of r){let a=Rd(i),c=a%256,u=a>>>31===1?-1:1;e[c]+=u*(1+Math.log(s));}let o=0;for(let i of e)o+=i*i;if(o=Math.sqrt(o),o===0)return e;for(let i=0;i<e.length;i++)
149
- e[i]/=o;return e}function aa(t){return Id(t)}var ca=.72;function _d(t,e){if(t.length!==e.length)return 0;let n=t.length,r=0,o=0,i=0;for(let s=0;s<n;s++){let a=t[s],c=e[s];r+=a*c,o+=a*a,i+=c*c;}return o===0||i===0?0:r/(Math.sqrt(o)*Math.sqrt(i))}var Ad=new Set(
142
+ .auditRate must be in [0, 1); got ${r}`);return {maxErrorRate:e,confidence:n,auditRate:r}}function ca(t){let e=t>>>0;return ()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>
143
+ 7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function jo(t,e){let n=o=>o!==null&&typeof o=="object";if(n(t.data)&&n(e.data))return Kn(t.data)===Kn(e.data);let r=o=>o.trim().replace(/\s+/g," ");return r(t.text)===r(e.text)}function Kn(t){if(Array.
144
+ isArray(t))return `[${t.map(Kn).join(",")}]`;if(t!==null&&typeof t=="object"){let e=t;return `{${Object.keys(e).sort().filter(n=>e[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Kn(e[n])}`).join(",")}}`}return JSON.
145
+ stringify(t)??"null"}function Jg(t,e){let{maxErrorRate:n,confidence:r}=Jn(e),o=1-r,i=new Ke,s=new Ke,a=ca(1592642065),c=0;for(let l of t){let d=nn(l.score),p=a()<.5;d<0||((p?i:s).anotar(d,l.correct),c++);}
146
+ let u=Lo(s,Mo(i,n,o),n,o);return {maxErrorRate:n,confidence:r,floor:u?rn(u.indice):null,labeled:c,heldOut:s.n,heldOutAtFloor:u?.retenidas??0,wrongHeldOutAtFloor:u?.erroneas??0,minHeldOutToCertify:Wn(n,
147
+ o)}}function Od(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 Md(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(
148
+ Boolean)}function Ld(t){let e=new Array(256).fill(0),n=Md(t);if(n.length===0)return e;let r=new Map;for(let i=0;i<n.length;i++){let s=n[i];if(r.set(s,(r.get(s)??0)+1),i+1<n.length){let a=`${s}\0${n[i+
149
+ 1]}`;r.set(a,(r.get(a)??0)+1);}}for(let[i,s]of r){let a=Od(i),c=a%256,u=a>>>31===1?-1:1;e[c]+=u*(1+Math.log(s));}let o=0;for(let i of e)o+=i*i;if(o=Math.sqrt(o),o===0)return e;for(let i=0;i<e.length;i++)
150
+ e[i]/=o;return e}function ua(t){return Ld(t)}var la=.72;function jd(t,e){if(t.length!==e.length)return 0;let n=t.length,r=0,o=0,i=0;for(let s=0;s<n;s++){let a=t[s],c=e[s];r+=a*c,o+=a*a,i+=c*c;}return o===0||i===0?0:r/(Math.sqrt(o)*Math.sqrt(i))}var Nd=new Set(
150
151
  ["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\
151
- \xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),Od=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what",
152
+ \xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),$d=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what",
152
153
  "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",
153
154
  "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\
154
155
  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",
155
156
  "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",
156
- "aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function rn(t){return (t.
157
- match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function jo(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)
158
- return false;n.set(r,o-1);}return true}function on(t){return t.split(/\s+/).filter(Boolean)}function sn(t){return t.filter(e=>Ad.has(e.replace(/'/g,""))||e.endsWith("n't")).length}var Md=/^(system|user|assistant|tool):/;
159
- function ua(t){return t.split(`
160
- `).map(e=>{let n=Md.exec(e);return n?{rol:n[1],texto:e.slice(n[0].length)}:{rol:"",texto:e}})}function Ld(t,e){let n=ua(t),r=ua(e);if(n.length!==r.length)return false;for(let o=0;o<n.length;o++)if(n[o].rol!==
161
- r[o].rol||!jd(n[o].texto,r[o].texto))return false;return true}function jd(t,e){if(!jo(rn(t),rn(e)))return false;let n=on(t),r=on(e);if(sn(n)!==sn(r))return false;let o=u=>u.length>1&&!Od.has(u)&&!/^\d/.test(u),i=new Set(
162
- n.filter(o)),s=new Set(r.filter(o));if(i.size===0&&s.size===0)return true;let a=0;for(let u of i)s.has(u)&&a++;let c=i.size+s.size-a;return c===0?true:a/c>=.75}var Nd="lexical-256-v1",$d="same-answer-v1",la=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;embebedorPropio;calibracion;estados=new Map;nombres;pendientes=new Set;aceptacionExplicita;constructor(e={}){
163
- let n=e.embed==null;if(this.embebedorPropio=n,this.embed=e.embed??aa,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??(n?ca:.9),this.acceptThreshold=e.acceptThreshold??.85,this.aceptacionExplicita=
157
+ "aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function on(t){return (t.
158
+ match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function No(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)
159
+ return false;n.set(r,o-1);}return true}function sn(t){return t.split(/\s+/).filter(Boolean)}function an(t){return t.filter(e=>Nd.has(e.replace(/'/g,""))||e.endsWith("n't")).length}var Bd=/^(system|user|assistant|tool):/;
160
+ function da(t){return t.split(`
161
+ `).map(e=>{let n=Bd.exec(e);return n?{rol:n[1],texto:e.slice(n[0].length)}:{rol:"",texto:e}})}function Fd(t,e){let n=da(t),r=da(e);if(n.length!==r.length)return false;for(let o=0;o<n.length;o++)if(n[o].rol!==
162
+ r[o].rol||!zd(n[o].texto,r[o].texto))return false;return true}function zd(t,e){if(!No(on(t),on(e)))return false;let n=sn(t),r=sn(e);if(an(n)!==an(r))return false;let o=u=>u.length>1&&!$d.has(u)&&!/^\d/.test(u),i=new Set(
163
+ n.filter(o)),s=new Set(r.filter(o));if(i.size===0&&s.size===0)return true;let a=0;for(let u of i)s.has(u)&&a++;let c=i.size+s.size-a;return c===0?true:a/c>=.75}var qd="lexical-256-v1",Vd="same-answer-v1",pa=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;embebedorPropio;calibracion;estados=new Map;nombres;pendientes=new Set;aceptacionExplicita;constructor(e={}){
164
+ let n=e.embed==null;if(this.embebedorPropio=n,this.embed=e.embed??ua,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??(n?la:.9),this.acceptThreshold=e.acceptThreshold??.85,this.aceptacionExplicita=
164
165
  e.acceptThreshold!=null,this.nombres={...e.embedderId!=null?{embedder:e.embedderId}:{},...e.verifierId!=null?{verifier:e.verifierId}:{},...e.calibration?.judgeId!=null?{judge:e.calibration.judgeId}:{}},
165
- this.ttlMs=e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now()),e.calibration){let r=Wn(e.calibration);this.calibracion={...r,judge:e.calibration.judge??Lo,perRecordFloors:e.calibration.
166
+ this.ttlMs=e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now()),e.calibration){let r=Jn(e.calibration);this.calibracion={...r,judge:e.calibration.judge??jo,perRecordFloors:e.calibration.
166
167
  perRecordFloors??true,random:e.calibration.random??Math.random};}}get calibrated(){return this.calibracion!=null}async find(e){return this.calibracion?(await this.lookup(e)).hit:this.mejorCandidata(e,true)}async mejorCandidata(e,n){
167
168
  if(this.records.length===0)return null;let r=await this.embed(e.normalizedText),o=null;for(let i of this.records){if(i.tenantId!==e.tenantId||i.authorizationScope!==e.authorizationScope||i.principal!==
168
169
  e.principal||i.knowledgeEpoch!==e.knowledgeEpoch||i.contractId!==e.contractId||i.model!==e.model||i.systemPromptHash!==e.systemPromptHash||i.structuredDataHash!==e.structuredDataHash||i.locale!==e.locale||
169
170
  i.schemaVersion!==e.schemaVersion||i.safetyPolicyVersion!==e.safetyPolicyVersion||i.toolsetHash!==e.toolsetHash||i.toolTurnsHash!==e.toolTurnsHash||i.temperature!==e.temperature||i.seed!==e.seed||this.
170
- ttlMs!=null&&this.now()-i.storedAtMs>this.ttlMs)continue;let s=_d(r,i.embedding);if(s<this.similarityThreshold||!Ld(e.normalizedText,i.query))continue;let a=this.verify?await this.verify(e.normalizedText,
171
+ ttlMs!=null&&this.now()-i.storedAtMs>this.ttlMs)continue;let s=jd(r,i.embedding);if(s<this.similarityThreshold||!Fd(e.normalizedText,i.query))continue;let a=this.verify?await this.verify(e.normalizedText,
171
172
  i.query):s,c=Math.min(s,a);n&&c<this.acceptThreshold||(!o||c>o.confidence)&&(o={record:i,similarity:s,verifierScore:a,confidence:c,ageMs:this.now()-i.storedAtMs,similarityFloor:this.similarityThreshold,
172
173
  acceptFloor:this.acceptThreshold,embedder:this.embebedorPropio?"built_in":"custom",verifierRan:this.verify!=null});}return o}async lookup(e,n={}){let r=this.calibracion;if(!r)return {hit:await this.mejorCandidata(
173
174
  e,true),probe:null};let o=n.agentic?"agentic":"single_shot",i=await this.mejorCandidata(e,false);if(!i)return {hit:null,probe:null};let s=this.estadoDe(o),a=s.suelo,c=i.confidence,u=p=>({hit:null,probe:{reason:p,
174
- score:c,segment:o,record:i.record}});if(a==null)return u("calibrating");if(tn(c)<a||this.aceptacionExplicita&&c<this.acceptThreshold)return u("below_floor");if(r.perRecordFloors&&i.record.failedAtScore!=
175
- null&&c<=i.record.failedAtScore)return u("record_floor");if(r.auditRate>0&&r.random()<r.auditRate)return u("audit");let l=nn(a),d=s.resumen();return {hit:{...i,acceptFloor:this.aceptacionExplicita?Math.
175
+ score:c,segment:o,record:i.record}});if(a==null)return u("calibrating");if(nn(c)<a||this.aceptacionExplicita&&c<this.acceptThreshold)return u("below_floor");if(r.perRecordFloors&&i.record.failedAtScore!=
176
+ null&&c<=i.record.failedAtScore)return u("record_floor");if(r.auditRate>0&&r.random()<r.auditRate)return u("audit");let l=rn(a),d=s.resumen();return {hit:{...i,acceptFloor:this.aceptacionExplicita?Math.
176
177
  max(l,this.acceptThreshold):l,calibration:{maxErrorRate:r.maxErrorRate,confidence:r.confidence,floor:l,heldOutAtFloor:d.retenidasEnSuelo,wrongHeldOutAtFloor:d.erroneasEnSuelo,labeled:d.etiquetas,segment:o}},
177
178
  probe:null}}observe(e,n){let r=this.etiquetar(e,n);return this.pendientes.add(r),r.finally(()=>this.pendientes.delete(r)),r}async etiquetar(e,n){let r=this.calibracion;if(!r)return null;let o;try{o=await r.
178
179
  judge(e.record.answer,n)===!0;}catch{return null}return this.estadoDe(e.segment).anotar(e.score,o),!o&&r.perRecordFloors&&(e.record.failedAtScore=Math.max(e.record.failedAtScore??-1/0,e.score)),o}async settled(){
179
180
  for(;this.pendientes.size>0;)await Promise.allSettled([...this.pendientes]);}calibrationStatus(e="single_shot"){let n=this.calibracion;if(!n)return null;let r=this.estadoDe(e).resumen();return {maxErrorRate:n.
180
- maxErrorRate,confidence:n.confidence,floor:r.suelo==null?null:nn(r.suelo),labeled:r.etiquetas,heldOut:r.retenidas,heldOutAtFloor:r.retenidasEnSuelo,wrongHeldOutAtFloor:r.erroneasEnSuelo,minHeldOutToCertify:r.
181
- minimasParaLaSiguiente,nextTestAt:r.etiquetasParaLaSiguiente}}exportCalibration(){return oa(this.identidad("exportCalibration"),this.estados)}importCalibration(e){let n=this.identidad("importCalibrati\
182
- on"),r=e;if(typeof e=="string")try{r=JSON.parse(e);}catch{throw new we("importCalibration: the state is a string but not JSON")}let o=ia(r,n);for(let[i]of o){let s=this.estados.get(i);if(s&&s.resumen().
183
- etiquetas>0)throw new we(`importCalibration: this cache has already recorded ${s.resumen().etiquetas} labels in the ${i} segment; import right after constructing it`)}for(let[i,s]of o)this.estados.set(
184
- i,s);}identidad(e){let n=this.calibracion;if(!n)throw new we(`${e}: this cache runs without \`calibration\``);let r=(a,c)=>{throw new we(`${e}: pass \`${a}\` naming your ${c}, so that a saved calibrati\
185
- on is only ever restored under the same one`)},o=this.embebedorPropio?`built_in:${Nd}`:`custom:${this.nombres.embedder??r("embedderId","embed function")}`,i=this.verify==null?null:`custom:${this.nombres.
186
- verifier??r("verifierId","verifier")}`,s=n.judge===Lo?`built_in:${$d}`:`custom:${this.nombres.judge??r("calibration.judgeId","judge")}`;return {embedder:o,verifier:i,judge:s,maxErrorRate:n.maxErrorRate,
187
- confidence:n.confidence,similarityThreshold:this.similarityThreshold}}estadoDe(e){let n=this.estados.get(e);if(!n){let r=this.calibracion;n=new en(r.maxErrorRate,1-r.confidence),this.estados.set(e,n);}
181
+ maxErrorRate,confidence:n.confidence,floor:r.suelo==null?null:rn(r.suelo),labeled:r.etiquetas,heldOut:r.retenidas,heldOutAtFloor:r.retenidasEnSuelo,wrongHeldOutAtFloor:r.erroneasEnSuelo,minHeldOutToCertify:r.
182
+ minimasParaLaSiguiente,nextTestAt:r.etiquetasParaLaSiguiente}}exportCalibration(){return sa(this.identidad("exportCalibration"),this.estados)}importCalibration(e){let n=this.identidad("importCalibrati\
183
+ on"),r=e;if(typeof e=="string")try{r=JSON.parse(e);}catch{throw new Te("importCalibration: the state is a string but not JSON")}let o=aa(r,n);for(let[i]of o){let s=this.estados.get(i);if(s&&s.resumen().
184
+ etiquetas>0)throw new Te(`importCalibration: this cache has already recorded ${s.resumen().etiquetas} labels in the ${i} segment; import right after constructing it`)}for(let[i,s]of o)this.estados.set(
185
+ i,s);}identidad(e){let n=this.calibracion;if(!n)throw new Te(`${e}: this cache runs without \`calibration\``);let r=(a,c)=>{throw new Te(`${e}: pass \`${a}\` naming your ${c}, so that a saved calibrati\
186
+ on is only ever restored under the same one`)},o=this.embebedorPropio?`built_in:${qd}`:`custom:${this.nombres.embedder??r("embedderId","embed function")}`,i=this.verify==null?null:`custom:${this.nombres.
187
+ verifier??r("verifierId","verifier")}`,s=n.judge===jo?`built_in:${Vd}`:`custom:${this.nombres.judge??r("calibration.judgeId","judge")}`;return {embedder:o,verifier:i,judge:s,maxErrorRate:n.maxErrorRate,
188
+ confidence:n.confidence,similarityThreshold:this.similarityThreshold}}estadoDe(e){let n=this.estados.get(e);if(!n){let r=this.calibracion;n=new tn(r.maxErrorRate,1-r.confidence),this.estados.set(e,n);}
188
189
  return n}async store(e,n){let r=await this.embed(e.normalizedText);this.records.length>=this.maxRecords&&this.records.shift(),this.records.push({embedding:r,query:e.normalizedText,answer:n,tenantId:e.
189
190
  tenantId,authorizationScope:e.authorizationScope,principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.structuredDataHash,
190
191
  locale:e.locale,schemaVersion:e.schemaVersion,safetyPolicyVersion:e.safetyPolicyVersion,toolsetHash:e.toolsetHash,...e.toolTurnsHash!==void 0?{toolTurnsHash:e.toolTurnsHash}:{},temperature:e.temperature,
191
192
  seed:e.seed,storedAtMs:this.now()});}invalidateEpoch(e){let n=0;for(let r=this.records.length-1;r>=0;r--)this.records[r].knowledgeEpoch===e&&(this.records.splice(r,1),n++);return n}get size(){return this.
192
- records.length}};var da=class{entradas=new Map;maxEntries;now;constructor(e={}){this.maxEntries=Math.max(1,e.maxEntries??1024),this.now=e.now??(()=>Date.now());}async get(e){let n=this.entradas.get(e);return n?this.now()>
193
+ records.length}};var fa=class{entradas=new Map;maxEntries;now;constructor(e={}){this.maxEntries=Math.max(1,e.maxEntries??1024),this.now=e.now??(()=>Date.now());}async get(e){let n=this.entradas.get(e);return n?this.now()>
193
194
  n.vence?(this.entradas.delete(e),null):n.valor:null}async set(e,n,r){if(this.entradas.delete(e),this.entradas.size>=this.maxEntries){let o=this.entradas.keys().next().value;o!==void 0&&this.entradas.delete(
194
- o);}this.entradas.set(e,{valor:n,vence:this.now()+r});}get size(){return this.entradas.size}};var No=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}},
195
- Bd={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]??Fd(t.normalizedText))?.trim();if(!n)return null;
196
- let r=qd(n);return r===null||!Number.isFinite(r)?null:{text:zd(r),data:{value:r},resolver:"arithmetic"}}};function Fd(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function zd(t){
197
- return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function qd(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],r=[],o={"+":1,"-":1,
195
+ o);}this.entradas.set(e,{valor:n,vence:this.now()+r});}get size(){return this.entradas.size}};var $o=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}},
196
+ Ud={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]??Hd(t.normalizedText))?.trim();if(!n)return null;
197
+ let r=Jd(n);return r===null||!Number.isFinite(r)?null:{text:Wd(r),data:{value:r},resolver:"arithmetic"}}};function Hd(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function Wd(t){
198
+ return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function Jd(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],r=[],o={"+":1,"-":1,
198
199
  "*":2,"/":2,"%":2},i=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===
199
200
  0?false:(n.push(u/c),true);case "%":return c===0?false:(n.push(u%c),true);default:return false}},s=true;for(let a of e)if(/^\d/.test(a))n.push(Number(a)),s=false;else if(a==="(")r.push(a),s=true;else if(a===")"){for(;r.length&&
200
201
  r[r.length-1]!=="(";)if(!i(r.pop()))return null;if(r.pop()!=="(")return null;s=false;}else {if(s)return null;for(;r.length&&r[r.length-1]!=="("&&o[r[r.length-1]]>=o[a];)if(!i(r.pop()))return null;r.push(a),
201
- s=true;}for(;r.length;){let a=r.pop();if(a==="("||!i(a))return null}return n.length===1?n[0]:null}function pa(){return new No().register(Bd)}var Vd=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,fa=/\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,
202
- Ud=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,Kn=class{classifier;maxRounds;constructor(e={}){this.
202
+ s=true;}for(;r.length;){let a=r.pop();if(a==="("||!i(a))return null}return n.length===1?n[0]:null}function ma(){return new $o().register(Ud)}var Kd=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,ha=/\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,
203
+ Gd=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,Gn=class{classifier;maxRounds;constructor(e={}){this.
203
204
  classifier=e.classifier,this.maxRounds=e.maxRounds??2;}classify(e){let n=e.original.retrieval?.mode,r=e.normalizedText;if((e.original.tools??[]).some(s=>s.risk==="write"||s.risk==="destructive")&&/\b(create|update|delete|send|pay|book|cancel|crea|actualiza|elimina|env[ií]a|paga)\b/i.
204
- test(r))return Le("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return Le("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(Ud.test(r)&&!fa.test(r))return Le("NO_RETRIEVAL",
205
- .8,"self-contained transformation",0);let i=this.classifier?.classify(r);return i&&i.confidence>=.75?Le(i.executionClass,i.confidence,"local classifier",Hd(i.executionClass,this.maxRounds)):n==="singl\
206
- e"?Le("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?Le("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):Vd.test(r)?Le("MULTI_HOP_RETRIEVAL",.7,"comparison/compoun\
207
- d question",Math.min(this.maxRounds,2)):fa.test(r)?Le("SINGLE_RETRIEVAL",.65,"single factual lookup",1):Le("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function Hd(t,e){return t===
208
- "SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function Le(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var Wd=["claude-fable-5-1","claude-mythos-5-1","claude-fable-5","claude-mythos-5","claude-opus-5-5","claude-opus-5","claude-opus-4-8","claude-opus-4-7","claude-opus-4-6","claude-sonnet-4-6","claude-op\
209
- us-4-5-20251101","claude-sonnet-4-5-20250929","claude-haiku-4-5-20251001"],ma={herramientas:10,tokensDeEsquemas:1e4},ha=5,Jd={regex:200,bm25:500},ga=1e4,Gn={bm25:{type:"tool_search_tool_bm25_20251119",
210
- name:"tool_search_tool_bm25"},regex:{type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"}},Kd="bvsala_contract";function ba(t){let e=t.lastIndexOf("/");return (e>=0?t.slice(e+1):t).toLowerCase()}
211
- function $o(t){let e=r=>r.replace(/-\d{8}$/,""),n=e(ba(t));return Wd.some(r=>e(r)===n)}function Bo(t){let e={modo:"off",siempreCargadas:[],variante:"bm25"};if(t===void 0)return e;let n=r=>r==="off"||r===
205
+ test(r))return Ne("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return Ne("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(Gd.test(r)&&!ha.test(r))return Ne("NO_RETRIEVAL",
206
+ .8,"self-contained transformation",0);let i=this.classifier?.classify(r);return i&&i.confidence>=.75?Ne(i.executionClass,i.confidence,"local classifier",Zd(i.executionClass,this.maxRounds)):n==="singl\
207
+ e"?Ne("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?Ne("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):Kd.test(r)?Ne("MULTI_HOP_RETRIEVAL",.7,"comparison/compoun\
208
+ d question",Math.min(this.maxRounds,2)):ha.test(r)?Ne("SINGLE_RETRIEVAL",.65,"single factual lookup",1):Ne("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function Zd(t,e){return t===
209
+ "SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function Ne(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var Yd=["claude-fable-5-1","claude-mythos-5-1","claude-fable-5","claude-mythos-5","claude-opus-5-5","claude-opus-5","claude-opus-4-8","claude-opus-4-7","claude-opus-4-6","claude-sonnet-4-6","claude-op\
210
+ us-4-5-20251101","claude-sonnet-4-5-20250929","claude-haiku-4-5-20251001"],ga={herramientas:10,tokensDeEsquemas:1e4},ba=5,Qd={regex:200,bm25:500},va=1e4,Zn={bm25:{type:"tool_search_tool_bm25_20251119",
211
+ name:"tool_search_tool_bm25"},regex:{type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"}},Xd="bvsala_contract";function ya(t){let e=t.lastIndexOf("/");return (e>=0?t.slice(e+1):t).toLowerCase()}
212
+ function Bo(t){let e=r=>r.replace(/-\d{8}$/,""),n=e(ya(t));return Yd.some(r=>e(r)===n)}function Fo(t){let e={modo:"off",siempreCargadas:[],variante:"bm25"};if(t===void 0)return e;let n=r=>r==="off"||r===
212
213
  "auto"||r==="always";return typeof t=="string"?n(t)?{...e,modo:t}:e:typeof t!="object"||t===null||!n(t.mode)?e:{modo:t.mode,siempreCargadas:Array.isArray(t.alwaysLoaded)?[...new Set(t.alwaysLoaded.filter(
213
- r=>typeof r=="string"))]:[],variante:t.variant==="regex"?"regex":"bm25"}}function an(t){return !t.some(e=>Array.isArray(e.intents)&&e.intents.length>0)&&!t.some(e=>typeof e.risk=="string")}function va(t){
214
+ r=>typeof r=="string"))]:[],variante:t.variant==="regex"?"regex":"bm25"}}function cn(t){return !t.some(e=>Array.isArray(e.intents)&&e.intents.length>0)&&!t.some(e=>typeof e.risk=="string")}function ka(t){
214
215
  let{opciones:e}=t,n=e.variante,r=(y,k={})=>({aplicar:false,razon:y,variante:n,siempreCargadas:[],diferidas:0,tokensDiferidos:0,...k});if(e.modo==="off")return r("toolSearch is off");if(t.herramientas.length===
215
216
  0)return r("no tools in this request");if(t.capacidad===void 0)return r("this provider is not an adapter of this package that can send the provider's tool search; OpenAI documents tool search for its \
216
- Responses and Agents APIs, not for Chat Completions, which is what the OpenAI-compatible adapter speaks");if(!$o(t.modelo))return r(`${ba(t.modelo)} is not in the provider's tool search model compatib\
217
+ Responses and Agents APIs, not for Chat Completions, which is what the OpenAI-compatible adapter speaks");if(!Bo(t.modelo))return r(`${ya(t.modelo)} is not in the provider's tool search model compatib\
217
218
  ility table`);if(t.hayContrato)return r("this request carries an output contract, which travels as a forced tool on this provider; combining it with deferred tools is not documented, so the selector k\
218
- eeps this request");if(t.cascadaActiva)return r("the model cascade is on: the cheaper model and the escalation would both have to support tool search");let o=Gn[n];if(t.herramientas.some(y=>y.id===o.name))
219
- return r(`one of your tools is already named \`${o.name}\``);let i=new Set(t.herramientas.map(y=>y.id)),s=e.siempreCargadas.filter(y=>i.has(y)&&y!==Kd),a=new Set(s),c=t.herramientas.filter(y=>!a.has(y.
220
- id)),u=c.reduce((y,k)=>y+k.tokens,0),l={siempreCargadas:s,diferidas:c.length,tokensDiferidos:u};if(c.length===0)return r("every tool is in `alwaysLoaded`: nothing to defer",l);if(c.length>ga)return r(
221
- `${c.length} tools to defer, over the provider's limit of ${ga}`,l);if(e.modo==="always")return {aplicar:true,variante:n,...l,razon:`toolSearch "always": ${c.length} tool(s) deferred behind the provider'\
219
+ eeps this request");if(t.cascadaActiva)return r("the model cascade is on: the cheaper model and the escalation would both have to support tool search");let o=Zn[n];if(t.herramientas.some(y=>y.id===o.name))
220
+ return r(`one of your tools is already named \`${o.name}\``);let i=new Set(t.herramientas.map(y=>y.id)),s=e.siempreCargadas.filter(y=>i.has(y)&&y!==Xd),a=new Set(s),c=t.herramientas.filter(y=>!a.has(y.
221
+ id)),u=c.reduce((y,k)=>y+k.tokens,0),l={siempreCargadas:s,diferidas:c.length,tokensDiferidos:u};if(c.length===0)return r("every tool is in `alwaysLoaded`: nothing to defer",l);if(c.length>va)return r(
222
+ `${c.length} tools to defer, over the provider's limit of ${va}`,l);if(e.modo==="always")return {aplicar:true,variante:n,...l,razon:`toolSearch "always": ${c.length} tool(s) deferred behind the provider'\
222
223
  s ${n} search, ${s.length} always loaded; no size or cost check (you chose it)`};if(t.capacidad!=="oficial")return r(`the adapter is not talking to the provider's own API host; a proxy may not forward\
223
- the search blocks. Use toolSearch "always" if yours does`,l);let d=t.herramientas.reduce((y,k)=>y+k.tokens,0);if(t.herramientas.length<ma.herramientas&&d<=ma.tokensDeEsquemas)return r(`${t.herramientas.
224
+ the search blocks. Use toolSearch "always" if yours does`,l);let d=t.herramientas.reduce((y,k)=>y+k.tokens,0);if(t.herramientas.length<ga.herramientas&&d<=ga.tokensDeEsquemas)return r(`${t.herramientas.
224
225
  length} tools and about ${d} tokens of definitions: under the provider's documented threshold (10 or more tools, or more than 10k tokens), where standard tool calling fits better`,l);let p=t.precio.inputPer1k/
225
- 1e3,h=t.precio.outputPer1k/1e3,m=Math.min(1,Math.max(0,t.lecturaDeCache)),g=c.map(y=>y.tokens).sort((y,k)=>k-y).slice(0,ha).reduce((y,k)=>y+k,0),f=m*p*u,v=p*g+h*Jd[n],b={ahorroDelPrefijo:f,costeDeUnaBusqueda:v};
226
- return f<v?r(`deferring ${u} tokens of definitions saves ${f.toFixed(6)} per request even with a warm prompt cache, less than one worst-case search costs (${v.toFixed(6)}: the ${ha} largest definition\
226
+ 1e3,h=t.precio.outputPer1k/1e3,m=Math.min(1,Math.max(0,t.lecturaDeCache)),g=c.map(y=>y.tokens).sort((y,k)=>k-y).slice(0,ba).reduce((y,k)=>y+k,0),f=m*p*u,v=p*g+h*Qd[n],b={ahorroDelPrefijo:f,costeDeUnaBusqueda:v};
227
+ return f<v?r(`deferring ${u} tokens of definitions saves ${f.toFixed(6)} per request even with a warm prompt cache, less than one worst-case search costs (${v.toFixed(6)}: the ${ba} largest definition\
227
228
  s uncached plus the longest query); the selector keeps this request`,{...l,...b}):{aplicar:true,variante:n,...l,...b,razon:`${c.length} tool(s) deferred behind the provider's ${n} search (${u} tokens of\
228
229
  definitions out of the cached prefix): it pays even if every request searches once with a warm cache (${f.toFixed(6)} saved vs ${v.toFixed(6)} worst-case search). The provider's counter measures it; \
229
- the layer credits nothing for it`}}function ya(t,e,n){return n||an(t)?[...t]:t.filter(r=>e||r.risk==="read")}var Fo=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});}},Zn=class{maxTools;scoreIntentMatch;learningTurns;freezer;constructor(e={}){
230
- this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??Gd,this.learningTurns=e.learningTurns??16,this.freezer=e.freezer??new Fo;}passthrough(e){if(!e||e.length===0)return {tools:[],droppedIds:[],
230
+ the layer credits nothing for it`}}function xa(t,e,n){return n||cn(t)?[...t]:t.filter(r=>e||r.risk==="read")}var zo=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});}},Yn=class{maxTools;scoreIntentMatch;learningTurns;freezer;constructor(e={}){
231
+ this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??ep,this.learningTurns=e.learningTurns??16,this.freezer=e.freezer??new zo;}passthrough(e){if(!e||e.length===0)return {tools:[],droppedIds:[],
231
232
  reason:"no tools provided",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.
232
233
  length}/${e.length}, 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:[],
233
- reason:"no tools provided",setIsStable:true};if(an(n)){let f=this.passthrough(n);return {...f,reason:`catalogue declares no \`intents\` and no \`risk\`: nothing to select on, passed through (${f.tools.length}\
234
+ reason:"no tools provided",setIsStable:true};if(cn(n)){let f=this.passthrough(n);return {...f,reason:`catalogue declares no \`intents\` and no \`risk\`: nothing to select on, passed through (${f.tools.length}\
234
235
  /${n.length}, capped at maxTools=${this.maxTools}). Declare ToolDescriptor.intents/risk to enable pruning`}}let i=r==="TOOL_ACTION",s=n.filter(f=>i||f.risk==="read"),a=f=>i&&f.risk!=="read",c=s.filter(
235
236
  f=>!a(f)),u=s.filter(f=>a(f)),l=u.map(f=>({tool:f,score:this.scoreIntentMatch(e,f)})).sort((f,v)=>v.score-f.score).map(f=>f.tool),d=c.map(f=>({tool:f,score:this.scoreIntentMatch(e,f)})).filter(f=>f.score>
236
237
  0).sort((f,v)=>v.score-f.score).map(f=>f.tool),h=[...l.slice(0,this.maxTools),...d.slice(0,Math.max(0,this.maxTools-u.length))].map(f=>({tool:f})).map(f=>f.tool).sort((f,v)=>f.id<v.id?-1:f.id>v.id?1:0);
237
- if(o!==void 0){let f=this.freezer.read(o),v=(f?.turns??0)+1;if(f&&v>this.learningTurns){let y=new Set(f.ids),k=n.filter(w=>y.has(w.id));this.freezer.record(o,f.ids,v);let T=new Set(k.map(w=>w.id));return {
238
- tools:k,droppedIds:n.filter(w=>!T.has(w.id)).map(w=>w.id),reason:`frozen tool set after ${this.learningTurns} turns (${k.length}/${n.length}): it no longer depends on this request's text, so the prefi\
238
+ if(o!==void 0){let f=this.freezer.read(o),v=(f?.turns??0)+1;if(f&&v>this.learningTurns){let y=new Set(f.ids),k=n.filter(x=>y.has(x.id));this.freezer.record(o,f.ids,v);let T=new Set(k.map(x=>x.id));return {
239
+ tools:k,droppedIds:n.filter(x=>!T.has(x.id)).map(x=>x.id),reason:`frozen tool set after ${this.learningTurns} turns (${k.length}/${n.length}): it no longer depends on this request's text, so the prefi\
239
240
  x cache survives`,setIsStable:true}}let b=[...new Set([...f?.ids??[],...h.map(y=>y.id)])].sort().slice(0,this.maxTools);this.freezer.record(o,b,v);}let m=new Set(h.map(f=>f.id)),g=n.filter(f=>!m.has(f.id)).
240
- map(f=>f.id);return {tools:h,droppedIds:g,reason:`selected ${h.length}/${n.length} by intent match (writes ${i?"allowed":"blocked"})`,setIsStable:g.length===0}}};function Gd(t,e){let n=Bn(t),r=0;for(let o of Array.
241
- isArray(e.intents)?e.intents:[]){let i=Bn(o);i&&(n.includes(i)?r+=2:i.split(/\s+/).some(s=>s.length>3&&n.includes(s))&&(r+=1));}return r}function Zd(t){let e=new Set,n=[];for(let r of t){let o=r.hash??Qd(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function Yd(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((s,a)=>(a.score??
241
+ map(f=>f.id);return {tools:h,droppedIds:g,reason:`selected ${h.length}/${n.length} by intent match (writes ${i?"allowed":"blocked"})`,setIsStable:g.length===0}}};function ep(t,e){let n=Fn(t),r=0;for(let o of Array.
242
+ isArray(e.intents)?e.intents:[]){let i=Fn(o);i&&(n.includes(i)?r+=2:i.split(/\s+/).some(s=>s.length>3&&n.includes(s))&&(r+=1));}return r}function tp(t){let e=new Set,n=[];for(let r of t){let o=r.hash??rp(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function np(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((s,a)=>(a.score??
242
243
  0)-(s.score??0));if(r.length<=n)return r;let o=r[0]?.score??0;if(o<=0)return r.slice(0,e.maxDocuments);let i=[];for(let s of r){let a=(s.score??0)/o;if(i.length<n||a>=.4&&i.length<e.maxDocuments)i.push(
243
- s);else break}return i}async function ka(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};
244
- let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,r=[];for(let s=0;s<n;s++){let a=await e.retriever.retrieve(t.query,t.maxDocuments*2);r.push(...a);}let o=r.length;r=Zd(r),e.reranker&&
245
- (r=await e.reranker.rerank(t.query,r));let i=Yd(r,{maxDocuments:t.maxDocuments});return {docs:i,rounds:n,retrievedCount:o,keptCount:i.length}}function Qd(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function h0(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function g0(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{
246
- ...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&np(o)?Object.assign(n.userPreferences,
247
- o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let i=ep(n,r);i?i.push(...o.map(String)):n.confirmedFacts[r]=o;}for(let r of e.remove??[])delete n.confirmedFacts[r],delete n.userPreferences[r],
248
- tp(n,r);return n}function b0(t){let e=t.rawTurns??3,n=[],r=Xd(t.state);r&&n.push({role:"system",content:`Conversation state:
249
- ${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function Xd(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`fa\
244
+ s);else break}return i}async function wa(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};
245
+ let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,r=[];for(let s=0;s<n;s++){let a=await e.retriever.retrieve(t.query,t.maxDocuments*2);r.push(...a);}let o=r.length;r=tp(r),e.reranker&&
246
+ (r=await e.reranker.rerank(t.query,r));let i=np(r,{maxDocuments:t.maxDocuments});return {docs:i,rounds:n,retrievedCount:o,keptCount:i.length}}function rp(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function w0(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function S0(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{
247
+ ...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&ap(o)?Object.assign(n.userPreferences,
248
+ o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let i=ip(n,r);i?i.push(...o.map(String)):n.confirmedFacts[r]=o;}for(let r of e.remove??[])delete n.confirmedFacts[r],delete n.userPreferences[r],
249
+ sp(n,r);return n}function T0(t){let e=t.rawTurns??3,n=[],r=op(t.state);r&&n.push({role:"system",content:`Conversation state:
250
+ ${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function op(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`fa\
250
251
  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(
251
252
  "; ")}`),t.openItems.length&&e.push(`open: ${t.openItems.join("; ")}`),e.join(`
252
- `)}function ep(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 tp(t,e){
253
- for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function np(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var xa={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function wa(t,e={}){let n=e.delimiter??",",r=e.indent??" ",i=t.split(`
254
- `).filter(c=>c.trim().length>0).map(c=>({indent:rp(c,r),content:c.slice(Sa(c,r))}));if(i.length===0)return {};let s=i[0];if(s.indent===0){let c=s.content.match(/^\[(\d+)\]\{(.*)\}:\s*$/);if(c){let l=Pt(
255
- c[2],n),d=Number(c[1]),p=[];for(let h=0,m=1;h<d&&m<i.length;h++,m++){let g=i[m];if(g.indent!==1)break;let f=Pt(g.content,n),v={};l.forEach((b,y)=>{v[b]=cn(f[y]??"null");}),p.push(v);}return p}let u=s.content.
256
- match(/^\[(\d+)\]:\s*(.*)$/);if(u){let l=u[2];return Number(u[1])===0||l.trim()===""?[]:Pt(l,n).map(cn)}}let[a]=Ta(i,0,0,n);return a}function Sa(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}
257
- function rp(t,e){return Sa(t,e)/e.length}function Ta(t,e,n,r){let o={},i=e;for(;i<t.length;){let s=t[i];if(s.indent<n)break;if(s.indent>n){i++;continue}let a=op(s.content,r);if(!a){i++;continue}let{key:c,
253
+ `)}function ip(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 sp(t,e){
254
+ for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function ap(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Sa={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function Ta(t,e={}){let n=e.delimiter??",",r=e.indent??" ",i=t.split(`
255
+ `).filter(c=>c.trim().length>0).map(c=>({indent:cp(c,r),content:c.slice(Ca(c,r))}));if(i.length===0)return {};let s=i[0];if(s.indent===0){let c=s.content.match(/^\[(\d+)\]\{(.*)\}:\s*$/);if(c){let l=Pt(
256
+ c[2],n),d=Number(c[1]),p=[];for(let h=0,m=1;h<d&&m<i.length;h++,m++){let g=i[m];if(g.indent!==1)break;let f=Pt(g.content,n),v={};l.forEach((b,y)=>{v[b]=un(f[y]??"null");}),p.push(v);}return p}let u=s.content.
257
+ match(/^\[(\d+)\]:\s*(.*)$/);if(u){let l=u[2];return Number(u[1])===0||l.trim()===""?[]:Pt(l,n).map(un)}}let[a]=Ea(i,0,0,n);return a}function Ca(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}
258
+ function cp(t,e){return Ca(t,e)/e.length}function Ea(t,e,n,r){let o={},i=e;for(;i<t.length;){let s=t[i];if(s.indent<n)break;if(s.indent>n){i++;continue}let a=up(s.content,r);if(!a){i++;continue}let{key:c,
258
259
  kind:u}=a;if(u.type==="scalar")o[c]=u.value,i++;else if(u.type==="inlineArray")o[c]=u.values,i++;else if(u.type==="emptyArray")o[c]=[],i++;else if(u.type==="table"){let l=[];i++;for(let d=0;d<u.count&&
259
- i<t.length;d++,i++){let p=t[i];if(p.indent!==n+1)break;let h=Pt(p.content,r),m={};u.columns.forEach((g,f)=>{m[g]=cn(h[f]??"null");}),l.push(m);}o[c]=l;}else {let[l,d]=Ta(t,i+1,n+1,r);o[c]=l,i=d;}}return [o,
260
- i]}function op(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:Yn(n[1]),kind:{type:"table",count:Number(n[2]),columns:Pt(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){
261
- let i=Number(r[2]),s=r[3];return i===0||s.trim()===""?{key:Yn(r[1]),kind:{type:"emptyArray"}}:{key:Yn(r[1]),kind:{type:"inlineArray",values:Pt(s,e).map(cn)}}}let o=t.match(/^([^:]+):\s*(.*)$/);if(o){let i=Yn(
262
- o[1]),s=o[2];return s===""?{key:i,kind:{type:"object"}}:{key:i,kind:{type:"scalar",value:cn(s)}}}return null}function Pt(t,e){let n=[],r="",o=false;for(let i=0;i<t.length;i++){let s=t[i];o?s==='"'?t[i+1]===
263
- '"'?(r+='"',i++):o=false:r+=s:s==='"'?o=true:s===e?(n.push(r),r=""):r+=s;}return n.push(r),n.map(i=>i.trim())}function cn(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,
264
- '"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function Yn(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,
265
- '"'):e}function ip(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return Vo(null,t,0,o,n,r),o.join(`
266
- `)}function Vo(t,e,n,r,o,i){let s=i.repeat(n),a=t===null?"":`${ap(t)}`;if(Array.isArray(e)){sp(a,e,n,r,o,i);return}if(qo(e)){t!==null&&r.push(`${s}${a}:`);let c=t===null?n:n+1;for(let[u,l]of Object.entries(
267
- e))Vo(u,l,c,r,o,i);return}r.push(`${s}${a}: ${Qn(e,o)}`);}function sp(t,e,n,r,o,i){let s=i.repeat(n),a=t===""?"":t;if(e.length===0){r.push(`${s}${a}[0]:`);return}if(e.every(zo)){let d=e.map(p=>Qn(p,o)).
268
- join(o);r.push(`${s}${a}[${e.length}]: ${d}`);return}let c=Xn(e);if(c){r.push(`${s}${a}[${e.length}]{${c.join(o)}}:`);let d=i.repeat(n+1);for(let p of e){let h=c.map(m=>Qn(p[m],o)).join(o);r.push(`${d}${h}`);}
269
- return}r.push(`${s}${a}[${e.length}]:`);let u=n+1,l=i.repeat(u);for(let d of e)if(zo(d))r.push(`${l}- ${Qn(d,o)}`);else {let p=[];Vo(null,d,0,p,o,i);let[h,...m]=p;r.push(`${l}- ${h??""}`);for(let g of m)
270
- r.push(`${l}${i}${g}`);}}function Xn(t){if(t.length===0)return null;let e=t[0];if(!qo(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(!qo(
271
- o))return null;let i=Object.keys(o);if(i.slice().sort().join("\0")!==r)return null;for(let s of i)if(!zo(o[s]))return null}return n}function ap(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:Ca(t)}function Qn(t,e){
260
+ i<t.length;d++,i++){let p=t[i];if(p.indent!==n+1)break;let h=Pt(p.content,r),m={};u.columns.forEach((g,f)=>{m[g]=un(h[f]??"null");}),l.push(m);}o[c]=l;}else {let[l,d]=Ea(t,i+1,n+1,r);o[c]=l,i=d;}}return [o,
261
+ i]}function up(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:Qn(n[1]),kind:{type:"table",count:Number(n[2]),columns:Pt(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){
262
+ let i=Number(r[2]),s=r[3];return i===0||s.trim()===""?{key:Qn(r[1]),kind:{type:"emptyArray"}}:{key:Qn(r[1]),kind:{type:"inlineArray",values:Pt(s,e).map(un)}}}let o=t.match(/^([^:]+):\s*(.*)$/);if(o){let i=Qn(
263
+ o[1]),s=o[2];return s===""?{key:i,kind:{type:"object"}}:{key:i,kind:{type:"scalar",value:un(s)}}}return null}function Pt(t,e){let n=[],r="",o=false;for(let i=0;i<t.length;i++){let s=t[i];o?s==='"'?t[i+1]===
264
+ '"'?(r+='"',i++):o=false:r+=s:s==='"'?o=true:s===e?(n.push(r),r=""):r+=s;}return n.push(r),n.map(i=>i.trim())}function un(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,
265
+ '"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function Qn(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,
266
+ '"'):e}function lp(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return Uo(null,t,0,o,n,r),o.join(`
267
+ `)}function Uo(t,e,n,r,o,i){let s=i.repeat(n),a=t===null?"":`${pp(t)}`;if(Array.isArray(e)){dp(a,e,n,r,o,i);return}if(Vo(e)){t!==null&&r.push(`${s}${a}:`);let c=t===null?n:n+1;for(let[u,l]of Object.entries(
268
+ e))Uo(u,l,c,r,o,i);return}r.push(`${s}${a}: ${Xn(e,o)}`);}function dp(t,e,n,r,o,i){let s=i.repeat(n),a=t===""?"":t;if(e.length===0){r.push(`${s}${a}[0]:`);return}if(e.every(qo)){let d=e.map(p=>Xn(p,o)).
269
+ join(o);r.push(`${s}${a}[${e.length}]: ${d}`);return}let c=er(e);if(c){r.push(`${s}${a}[${e.length}]{${c.join(o)}}:`);let d=i.repeat(n+1);for(let p of e){let h=c.map(m=>Xn(p[m],o)).join(o);r.push(`${d}${h}`);}
270
+ return}r.push(`${s}${a}[${e.length}]:`);let u=n+1,l=i.repeat(u);for(let d of e)if(qo(d))r.push(`${l}- ${Xn(d,o)}`);else {let p=[];Uo(null,d,0,p,o,i);let[h,...m]=p;r.push(`${l}- ${h??""}`);for(let g of m)
271
+ r.push(`${l}${i}${g}`);}}function er(t){if(t.length===0)return null;let e=t[0];if(!Vo(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(!Vo(
272
+ o))return null;let i=Object.keys(o);if(i.slice().sort().join("\0")!==r)return null;for(let s of i)if(!qo(o[s]))return null}return n}function pp(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:Pa(t)}function Xn(t,e){
272
273
  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(`
273
- `)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?Ca(n):n}function Ca(t){return `"${t.replace(/"/g,'""')}"`}function zo(t){return t===null||typeof t=="string"||typeof t==
274
- "number"||typeof t=="boolean"}function qo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var cp="Data is the compact encoder: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; ea\
275
- 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 up(t={}){return {format:"compact-rows",supports(){return true},
276
- encode(e){return ip(e,t)},instruction(){return cp},decode(e){return wa(e,t)}}}var Ea=up();var Ra={format:"csv",supports(t){return Array.isArray(t)&&Xn(t)!==null},encode(t){let e=t,n=Xn(e),r=n.map(Pa).join(","),o=e.map(i=>n.map(s=>Pa(i[s])).join(","));return [r,...o].join(`
277
- `)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function Pa(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,
278
- '""')}"`:e}var er=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[xa,Ea,Ra],this.minSavingsTokens=e.minimumSavingsTokens??
274
+ `)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?Pa(n):n}function Pa(t){return `"${t.replace(/"/g,'""')}"`}function qo(t){return t===null||typeof t=="string"||typeof t==
275
+ "number"||typeof t=="boolean"}function Vo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var fp="Data is the compact encoder: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; ea\
276
+ 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 mp(t={}){return {format:"compact-rows",supports(){return true},
277
+ encode(e){return lp(e,t)},instruction(){return fp},decode(e){return Ta(e,t)}}}var Ra=mp();var Ia={format:"csv",supports(t){return Array.isArray(t)&&er(t)!==null},encode(t){let e=t,n=er(e),r=n.map(Da).join(","),o=e.map(i=>n.map(s=>Da(i[s])).join(","));return [r,...o].join(`
278
+ `)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function Da(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,
279
+ '""')}"`:e}var tr=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[Sa,Ra,Ia],this.minSavingsTokens=e.minimumSavingsTokens??
279
280
  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(
280
- e))continue;let l=u.encode(e);if(u.format!=="json-compact"&&!lp(u,l,e))continue;let d=u.instruction(e),p=this.tokenizer.count(l,r),h=d?this.tokenizer.count(d,r):0,m=this.qualityPenalty(n.model??"",u.format);
281
+ e))continue;let l=u.encode(e);if(u.format!=="json-compact"&&!hp(u,l,e))continue;let d=u.instruction(e),p=this.tokenizer.count(l,r),h=d?this.tokenizer.count(d,r):0,m=this.qualityPenalty(n.model??"",u.format);
281
282
  o.push({format:u.format,encoded:l,instruction:d,payloadTokens:p,instructionTokens:h,penalty:m,total:p+h+m});}let i=o.find(u=>u.format==="json-compact"),s={};for(let u of o)s[u.format]=u.total;if(!i){let u=o[0];
282
- return u?Da(u,s,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:s,instructionOverheadTokens:0,reason:"no serializer supported payload; defa\
283
+ return u?_a(u,s,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:s,instructionOverheadTokens:0,reason:"no serializer supported payload; defa\
283
284
  ulted to JSON"}}let a=i,c="json baseline (no challenger cleared thresholds)";for(let u of o){if(u.format==="json-compact")continue;let l=i.total-u.total,d=i.total===0?0:l/i.total;l>=this.minSavingsTokens&&
284
- d>=this.minSavingsRatio&&u.total<a.total&&(a=u,c=`${u.format} saved ${l} tokens (${(d*100).toFixed(1)}%) vs json`);}return Da(a,s,c)}};function lp(t,e,n){if(!t.decode)return false;try{return Uo(t.decode(e),
285
- n)}catch{return false}}function Uo(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.
286
- length)return false;for(let s=0;s<t.length;s++)if(!Uo(t[s],e[s]))return false;return true}let o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)return false;for(let s of o)if(!Object.prototype.hasOwnProperty.
287
- call(e,s)||!Uo(t[s],e[s]))return false;return true}function Da(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function de(t,e,n="$"){let r=[];return Ho(t,e,n,r),{valid:r.length===0,errors:r}}function dp(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
288
- string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function Ho(t,e,n,r){switch(e.enum&&!e.enum.some(i=>gp(i,t))&&r.push({path:n,message:"value not in enum"}),
289
- e.type??dp(t)){case "object":pp(t,e,n,r);break;case "array":fp(t,e,n,r);break;case "string":mp(t,e,n,r);break;case "number":case "integer":hp(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,
290
- message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function pp(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,
285
+ d>=this.minSavingsRatio&&u.total<a.total&&(a=u,c=`${u.format} saved ${l} tokens (${(d*100).toFixed(1)}%) vs json`);}return _a(a,s,c)}};function hp(t,e,n){if(!t.decode)return false;try{return Ho(t.decode(e),
286
+ n)}catch{return false}}function Ho(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.
287
+ length)return false;for(let s=0;s<t.length;s++)if(!Ho(t[s],e[s]))return false;return true}let o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)return false;for(let s of o)if(!Object.prototype.hasOwnProperty.
288
+ call(e,s)||!Ho(t[s],e[s]))return false;return true}function _a(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function pe(t,e,n="$"){let r=[];return Wo(t,e,n,r),{valid:r.length===0,errors:r}}function gp(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
289
+ string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function Wo(t,e,n,r){switch(e.enum&&!e.enum.some(i=>xp(i,t))&&r.push({path:n,message:"value not in enum"}),
290
+ e.type??gp(t)){case "object":bp(t,e,n,r);break;case "array":vp(t,e,n,r);break;case "string":yp(t,e,n,r);break;case "number":case "integer":kp(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,
291
+ message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function bp(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,
291
292
  message:"expected object"});return}let o=t;for(let i of e.required??[])i in o||r.push({path:`${n}.${i}`,message:"missing required property"});if(e.additionalProperties===false&&e.properties){let i=new Set(
292
293
  Object.keys(e.properties));for(let s of Object.keys(o))i.has(s)||r.push({path:`${n}.${s}`,message:"additional property not allowed"});}if(e.properties)for(let[i,s]of Object.entries(e.properties))i in o&&
293
- Ho(o[i],s,`${n}.${i}`,r);}function fp(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\
294
- ms ${e.maxItems}`}),e.minItems!=null&&t.length<e.minItems&&r.push({path:n,message:`array below minItems ${e.minItems}`}),e.items&&t.forEach((o,i)=>Ho(o,e.items,`${n}[${i}]`,r));}function mp(t,e,n,r){if(typeof t!=
294
+ Wo(o[i],s,`${n}.${i}`,r);}function vp(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\
295
+ ms ${e.maxItems}`}),e.minItems!=null&&t.length<e.minItems&&r.push({path:n,message:`array below minItems ${e.minItems}`}),e.items&&t.forEach((o,i)=>Wo(o,e.items,`${n}[${i}]`,r));}function yp(t,e,n,r){if(typeof t!=
295
296
  "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.
296
297
  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\
297
- sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function hp(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}
298
+ sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function kp(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}
298
299
  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.
299
- minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function gp(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var tr=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 Wo(
300
- e,n,r),r}};function Wo(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??{}))Wo(o,`${e}\
301
- .${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&Wo(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: s\
302
- tring should set maxLength or use an enum`);}function Ia(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\
303
- ate + repair"}}function F0(t=()=>true){return {id:"provider-native",supports:t}}function Jo(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;
304
- return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function J0(t){return {async compress(e){let n=e.protectedSpans??[],r=e.text,o=[];n.forEach((c,u)=>{
300
+ minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function xp(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var nr=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 Jo(
301
+ e,n,r),r}};function Jo(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??{}))Jo(o,`${e}\
302
+ .${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&Jo(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: s\
303
+ tring should set maxLength or use an enum`);}function Aa(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\
304
+ ate + repair"}}function J0(t=()=>true){return {id:"provider-native",supports:t}}function Ko(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;
305
+ return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function eb(t){return {async compress(e){let n=e.protectedSpans??[],r=e.text,o=[];n.forEach((c,u)=>{
305
306
  let l=`\0PROTECT_${u}\0`;o.push({token:l,span:c}),r=r.split(c.text).join(l);});let i=await t.compress({text:r,...e.targetRatio!=null?{targetRatio:e.targetRatio}:{}}),s=i.compressed,a=true;for(let{token:c,
306
307
  span:u}of o){if(!s.includes(c)){a=false;break}s=s.split(c).join(u.text);}return a?{...i,compressed:s,protectedSpans:n.length,fidelityPassed:true}:{compressed:e.text,originalTokens:i.originalTokens,compressedTokens:i.
307
- originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var K0={async compress(t){return {compressed:t.text,originalTokens:0,
308
- compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function _a(t,e){let n=s=>s.toLowerCase().replace(/[.,;:!¡?¿()[\]{}"«»…]/g,
308
+ originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var tb={async compress(t){return {compressed:t.text,originalTokens:0,
309
+ compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function Oa(t,e){let n=s=>s.toLowerCase().replace(/[.,;:!¡?¿()[\]{}"«»…]/g,
309
310
  " ").replace(/\s+/g," ").trim(),o=n((s=>{let a=new Set,c=[];for(let u of s.split(`
310
311
  `)){let l=u.trim();l&&a.has(l)||(l&&a.add(l),c.push(u));}return c.join(`
311
- `)})(t)),i=n(e);return !(!jo(rn(o),rn(i))||sn(on(o))!==sn(on(i)))}var Ko=["ansi","carriage-return","json","repeated-lines"],bp=256,vp=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|[ -/]+[0-~]|[@-_])/g;function yp(t){if(!t.includes("\x1B"))return null;
312
- let e=t.replace(vp,"");return e.length<t.length?e:null}function kp(t){let e="";for(let n of t.split("\r"))e=n+e.slice(n.length);return e}function xp(t){if(!t.includes("\r")||t.includes(`\r
312
+ `)})(t)),i=n(e);return !(!No(on(o),on(i))||an(sn(o))!==an(sn(i)))}var Go=["ansi","carriage-return","json","repeated-lines"],wp=256,Sp=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|[ -/]+[0-~]|[@-_])/g;function Tp(t){if(!t.includes("\x1B"))return null;
313
+ let e=t.replace(Sp,"");return e.length<t.length?e:null}function Cp(t){let e="";for(let n of t.split("\r"))e=n+e.slice(n.length);return e}function Ep(t){if(!t.includes("\r")||t.includes(`\r
313
314
  `))return null;let e=t.split(`
314
- `).map(n=>n.includes("\r")?kp(n):n).join(`
315
- `);return e.length<t.length?e:null}var wp=t=>t===32||t===9||t===10||t===13;function Sp(t){let e=t.trim(),n=e.charCodeAt(0);if(n!==123&&n!==91)return null;let r;try{r=JSON.parse(e);}catch{return null}let o=[],
316
- i=0,s=false;for(let c=0;c<e.length;c++){let u=e.charCodeAt(c);if(s){u===92?c+=1:u===34&&(s=false);continue}if(u===34){s=true;continue}wp(u)&&(c>i&&o.push(e.slice(i,c)),i=c+1);}i<e.length&&o.push(e.slice(i));let a=o.
317
- join("");if(a.length>=t.length)return null;try{if(JSON.stringify(JSON.parse(a))!==JSON.stringify(r))return null}catch{return null}return a}var Ma=/^\[previous line repeated (\d+) more times\]$/,Tp=t=>`\
318
- [previous line repeated ${t} more times]`,Aa=3;function Cp(t){let e=[];for(let n of t.split(`
319
- `)){let r=Ma.exec(n);if(r&&e.length>0){let o=e[e.length-1];for(let i=Number(r[1]);i>0;i--)e.push(o);}else e.push(n);}return e.join(`
320
- `)}function Ep(t){let e=t.split(`
321
- `);if(e.length<Aa||e.some(i=>Ma.test(i)))return null;let n=[],r=0;for(let i=0;i<e.length;){let s=e[i],a=i+1;for(;a<e.length&&e[a]===s;)a++;let c=a-i-1,u=Tp(c);if(c+1>=Aa&&c*(s.length+1)>u.length+1)n.push(
315
+ `).map(n=>n.includes("\r")?Cp(n):n).join(`
316
+ `);return e.length<t.length?e:null}var Pp=t=>t===32||t===9||t===10||t===13;function Rp(t){let e=t.trim(),n=e.charCodeAt(0);if(n!==123&&n!==91)return null;let r;try{r=JSON.parse(e);}catch{return null}let o=[],
317
+ i=0,s=false;for(let c=0;c<e.length;c++){let u=e.charCodeAt(c);if(s){u===92?c+=1:u===34&&(s=false);continue}if(u===34){s=true;continue}Pp(u)&&(c>i&&o.push(e.slice(i,c)),i=c+1);}i<e.length&&o.push(e.slice(i));let a=o.
318
+ join("");if(a.length>=t.length)return null;try{if(JSON.stringify(JSON.parse(a))!==JSON.stringify(r))return null}catch{return null}return a}var ja=/^\[previous line repeated (\d+) more times\]$/,Dp=t=>`\
319
+ [previous line repeated ${t} more times]`,Ma=3;function Ip(t){let e=[];for(let n of t.split(`
320
+ `)){let r=ja.exec(n);if(r&&e.length>0){let o=e[e.length-1];for(let i=Number(r[1]);i>0;i--)e.push(o);}else e.push(n);}return e.join(`
321
+ `)}function _p(t){let e=t.split(`
322
+ `);if(e.length<Ma||e.some(i=>ja.test(i)))return null;let n=[],r=0;for(let i=0;i<e.length;){let s=e[i],a=i+1;for(;a<e.length&&e[a]===s;)a++;let c=a-i-1,u=Dp(c);if(c+1>=Ma&&c*(s.length+1)>u.length+1)n.push(
322
323
  s,u),r+=c;else for(let l=i;l<a;l++)n.push(e[l]);i=a;}if(r===0)return null;let o=n.join(`
323
- `);return Cp(o)!==t?null:o.length<t.length?o:null}var Pp={ansi:yp,"carriage-return":xp,json:Sp,"repeated-lines":Ep};function La(t,e={}){let n=new Set(e.transforms??Ko),r=Math.max(1,e.minSavedChars??256),
324
- o=t,i=[];for(let a of Ko){if(!n.has(a))continue;let c=Pp[a](o);c!=null&&c.length<o.length&&(o=c,i.push(a));}let s=t.length-o.length;return i.length===0?Oa(t,"nothing to compact"):s<r?Oa(t,`compaction w\
325
- ould save ${s} chars, below the ${r} minimum`):{text:o,changed:true,applied:i,originalChars:t.length,compactChars:o.length,reason:`${i.join(", ")}: ${s} chars removed`}}function Oa(t,e){return {text:t,changed:false,
326
- applied:[],originalChars:t.length,compactChars:t.length,reason:e}}var Rp=new Set(["path","paths","file","files","filepath","filename","absolutepath","relativepath","targetfile","notebookpath"]);function Dp(t){
327
- if(!t)return false;let e;try{e=JSON.parse(t);}catch{return false}return !e||typeof e!="object"||Array.isArray(e)?false:Object.keys(e).some(n=>Rp.has(n.toLowerCase().replace(/[_-]/g,"")))}function ja(t,e={}){let n=new Map,
324
+ `);return Ip(o)!==t?null:o.length<t.length?o:null}var Ap={ansi:Tp,"carriage-return":Ep,json:Rp,"repeated-lines":_p};function Na(t,e={}){let n=new Set(e.transforms??Go),r=Math.max(1,e.minSavedChars??256),
325
+ o=t,i=[];for(let a of Go){if(!n.has(a))continue;let c=Ap[a](o);c!=null&&c.length<o.length&&(o=c,i.push(a));}let s=t.length-o.length;return i.length===0?La(t,"nothing to compact"):s<r?La(t,`compaction w\
326
+ ould save ${s} chars, below the ${r} minimum`):{text:o,changed:true,applied:i,originalChars:t.length,compactChars:o.length,reason:`${i.join(", ")}: ${s} chars removed`}}function La(t,e){return {text:t,changed:false,
327
+ applied:[],originalChars:t.length,compactChars:t.length,reason:e}}var Op=new Set(["path","paths","file","files","filepath","filename","absolutepath","relativepath","targetfile","notebookpath"]);function Mp(t){
328
+ if(!t)return false;let e;try{e=JSON.parse(t);}catch{return false}return !e||typeof e!="object"||Array.isArray(e)?false:Object.keys(e).some(n=>Op.has(n.toLowerCase().replace(/[_-]/g,"")))}function $a(t,e={}){let n=new Map,
328
329
  r=-1;t.forEach((s,a)=>{if(s.role==="assistant"){r=a;for(let c of s.toolCalls??[])c.id&&n.set(c.id,{nombre:c.name,argumentos:c.arguments});}});let o=new Set(e.exceptTools??[]),i={compactados:[],vistasDeFichero:0,
329
- exceptuados:0};return t.forEach((s,a)=>{if(s.role!=="tool")return;let c=s.toolCallId?n.get(s.toolCallId):void 0,u=c?.nombre??s.name;if(u&&o.has(u)){i.exceptuados+=1;return}if(!e.compactFileViews&&Dp(c?.
330
- argumentos)){i.vistasDeFichero+=1;return}let l=La(s.content,e);l.changed&&i.compactados.push({indice:a,texto:l.text,aplicadas:l.applied,enLaCola:a>r});}),i}var Na=new WeakSet;function $a(t){Na.add(t);}function Go(t){return typeof t=="object"&&t!==null&&Na.has(t)}var Zo=class{id="mock";options;constructor(e={}){this.options=e,$a(this);}async generate(e,n){let r=e.messages.map(c=>c.content).join(`
330
+ exceptuados:0};return t.forEach((s,a)=>{if(s.role!=="tool")return;let c=s.toolCallId?n.get(s.toolCallId):void 0,u=c?.nombre??s.name;if(u&&o.has(u)){i.exceptuados+=1;return}if(!e.compactFileViews&&Mp(c?.
331
+ argumentos)){i.vistasDeFichero+=1;return}let l=Na(s.content,e);l.changed&&i.compactados.push({indice:a,texto:l.text,aplicadas:l.applied,enLaCola:a>r});}),i}var Ba=new WeakSet;function Fa(t){Ba.add(t);}function Zo(t){return typeof t=="object"&&t!==null&&Ba.has(t)}var Yo=class{id="mock";options;constructor(e={}){this.options=e,Fa(this);}async generate(e,n){let r=e.messages.map(c=>c.content).join(`
331
332
  `),o=Ct.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+=Ct.count(c);}let i,s=false;if(e.schema){let c=this.
332
- options.data??nr(e.schema);i=JSON.stringify(c),s=true;}else i=this.options.answer??`mock-response(${e.model})`;let a=Math.min(e.maxOutputTokens??Number.MAX_SAFE_INTEGER,Ct.count(i));return {text:i,usage:{
333
+ options.data??rr(e.schema);i=JSON.stringify(c),s=true;}else i=this.options.answer??`mock-response(${e.model})`;let a=Math.min(e.maxOutputTokens??Number.MAX_SAFE_INTEGER,Ct.count(i));return {text:i,usage:{
333
334
  inputTokens:o,outputTokens:a,...this.options.cachedInputTokens!=null?{cachedInputTokens:this.options.cachedInputTokens}:{}},structuredNatively:s}}async*generateStream(e){let n=await this.generate(e),r=Math.
334
- 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 nr(t){if(t.enum&&t.enum.length>0)return t.
335
- enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?nr(r):null;}for(let[n,r]of Object.entries(t.properties??{}))n in e||(e[n]=nr(r));return e}case "\
336
- array":return t.items?[nr(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 rb(t){return new Zo(
337
- t)}function Yo(t){let e=t.toLowerCase(),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e}function Ba(t){let e=/^gpt-(\d+)(?:\.(\d+))?(?![\d.])/.exec(t);if(!e)return false;let n=Number(e[1]),r=e[2]===void 0?0:
338
- Number(e[2]);return n>5||n===5&&r>=6}function Ke(t){let e=Yo(t);return e.startsWith("gpt-")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?Ba(e)?1.25:1:e.startsWith("gemini")?1:1.25}function un(t){
339
- return Ba(Yo(t))?1.25:1}function Qo(t){let e=t.toLowerCase();return e.startsWith("claude")||e.startsWith("anthropic/")||Yo(e).startsWith("claude")?2:Ke(t)}var Ip="https://developers.openai.com/api/docs/pricing",_p="https://ai.google.dev/gemini-api/docs/pricing",Xo="2026-09-27",$=t=>({...t,fuente:Ip,consultado:Xo}),De=t=>({...t,fuente:_p,consultado:Xo}),
340
- Ap="https://platform.claude.com/docs/en/about-claude/pricing",te=t=>({...t,fuente:Ap,consultado:Xo}),Op={openai:{flex:{"gpt-5":$({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
335
+ 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 rr(t){if(t.enum&&t.enum.length>0)return t.
336
+ enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?rr(r):null;}for(let[n,r]of Object.entries(t.properties??{}))n in e||(e[n]=rr(r));return e}case "\
337
+ array":return t.items?[rr(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 lb(t){return new Yo(
338
+ t)}function Qo(t){let e=t.toLowerCase(),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e}function za(t){let e=/^gpt-(\d+)(?:\.(\d+))?(?![\d.])/.exec(t);if(!e)return false;let n=Number(e[1]),r=e[2]===void 0?0:
339
+ Number(e[2]);return n>5||n===5&&r>=6}function Ge(t){let e=Qo(t);return e.startsWith("gpt-")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?za(e)?1.25:1:e.startsWith("gemini")?1:1.25}function ln(t){
340
+ return za(Qo(t))?1.25:1}function Xo(t){let e=t.toLowerCase();return e.startsWith("claude")||e.startsWith("anthropic/")||Qo(e).startsWith("claude")?2:Ge(t)}var Lp="https://developers.openai.com/api/docs/pricing",jp="https://ai.google.dev/gemini-api/docs/pricing",ei="2026-09-27",$=t=>({...t,fuente:Lp,consultado:ei}),_e=t=>({...t,fuente:jp,consultado:ei}),
341
+ Np="https://platform.claude.com/docs/en/about-claude/pricing",te=t=>({...t,fuente:Np,consultado:ei}),$p={openai:{flex:{"gpt-5":$({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
341
342
  ni":$({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":$({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":$({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),
342
343
  "gpt-5.4":$({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),
343
344
  "gpt-5.4-mini":$({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),"gpt-5.4-nano":$({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":$({inputPer1k:.0025,cachedInputPer1k:25e-5,
@@ -373,136 +374,138 @@ cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":te({inputPer1k:.00
373
374
  cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":te({inputPer1k:.0075,cachedInputPer1k:75e-5,cacheWritePer1k:.009375,outputPer1k:.0375}),"claude-sonnet-5":te({inputPer1k:.001,cachedInputPer1k:1e-4,
374
375
  cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-4-6":te({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4-5":te({inputPer1k:.0015,cachedInputPer1k:15e-5,
375
376
  cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4":te({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-haiku-4-5":te({inputPer1k:5e-4,cachedInputPer1k:5e-5,
376
- cacheWritePer1k:625e-6,outputPer1k:.0025}),"claude-3-5-haiku":te({inputPer1k:4e-4,cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":De({inputPer1k:375e-6,
377
- outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.5-flash":De({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":De({inputPer1k:15e-5,outputPer1k:.00125,
378
- cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":De({inputPer1k:.001,outputPer1k:.006,cachedInputPer1k:2e-4,largo:{estandar:{inputPer1k:.004,outputPer1k:.018,cachedInputPer1k:4e-4},tier:{inputPer1k:.002,
379
- outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":De({inputPer1k:625e-6,outputPer1k:.005,cachedInputPer1k:125e-6,largo:{estandar:{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},tier:{
380
- inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-flash":De({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":De({inputPer1k:375e-6,outputPer1k:.001875,
381
- cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":De({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":De({inputPer1k:125e-6,
382
- outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-preview":De({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}};function Ge(t){let e=t.lastIndexOf("/");return e>=0?t.slice(e+1):
383
- t}function ln(t){let e=t.toLowerCase(),n=e.indexOf("/"),r=n>0?e.slice(0,n):"",o=Ge(e);return r==="openai"||r==="azure-openai"?"openai":r==="google"||r==="google-vertex"?"google":r==="anthropic"?"anthr\
384
- opic":/^(gpt-|o[1-9](-|$))/.test(o)?"openai":o.startsWith("gemini")?"google":o.startsWith("claude-")?"anthropic":null}function Mp(t){return Date.parse(`${t}T23:59:59.999Z`)}function dn(t,e,n,r=Date.now()){
385
- if(We(n)===void 0)return;let o=Tt(n);if(o===void 0)return;let i=Op[t]?.[e],s=i?i[o]:void 0;if(s&&!(s.vigenteHasta&&r>Mp(s.vigenteHasta)))return s}function rr(t){let e=We(t);if(e)return {...e,cacheWritePer1k:e.
386
- inputPer1k*Ke(Ge(t))}}var Fa={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},za=Math.min(...Object.values(Fa).filter(t=>t<1)),Rt="flex";function ei(t){if(t==null||t==="")return null;let e=Fa[t];return e==
387
- null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}var or=1e10;function ti(t){let e=Math.floor(t*or)/or;return e>t&&(e=(Math.floor(t*or)-1)/or),e<=0?0:e}var ir=t=>typeof t==
388
- "number"&&Number.isFinite(t);function sr(t){let e=ei(t.tierServido);if(!e)return {ok:false,motivo:"no-served-tier"};if(e.factor==null)return {ok:false,motivo:"unknown-tier"};if(!e.conDescuento)return {ok:false,motivo:"\
389
- standard-rate-tier"};let n=t.uso;if(n.complete===false||!ir(n.inputTokens)||!ir(n.outputTokens)||n.cachedInputTokens!=null&&!ir(n.cachedInputTokens)||n.cacheWriteInputTokens!=null&&!ir(n.cacheWriteInputTokens))
390
- return {ok:false,motivo:"incomplete-usage"};let r=rr(t.modelo);if(!r)return {ok:false,motivo:"no-standard-price"};let o=t.origen??ln(t.modelo),i=o?dn(o,e.servido,t.modelo,t.ahoraMs):void 0;if(!i)return {ok:false,
391
- motivo:"no-tier-price"};let s=Math.max(0,n.inputTokens),a=Ke(Ge(t.modelo)),c=n.cachedInputTokens!=null,u=a<=1||n.cacheWriteInputTokens!=null,l=c?Math.min(Math.max(0,n.cachedInputTokens??0),s):0,d=a>1&&
377
+ cacheWritePer1k:625e-6,outputPer1k:.0025}),"claude-3-5-haiku":te({inputPer1k:4e-4,cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":_e({inputPer1k:375e-6,
378
+ outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.5-flash":_e({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":_e({inputPer1k:15e-5,outputPer1k:.00125,
379
+ cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":_e({inputPer1k:.001,outputPer1k:.006,cachedInputPer1k:2e-4,largo:{estandar:{inputPer1k:.004,outputPer1k:.018,cachedInputPer1k:4e-4},tier:{inputPer1k:.002,
380
+ outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":_e({inputPer1k:625e-6,outputPer1k:.005,cachedInputPer1k:125e-6,largo:{estandar:{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},tier:{
381
+ inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-flash":_e({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":_e({inputPer1k:375e-6,outputPer1k:.001875,
382
+ cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":_e({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":_e({inputPer1k:125e-6,
383
+ outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-preview":_e({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}};function Ze(t){let e=t.lastIndexOf("/");return e>=0?t.slice(e+1):
384
+ t}function dn(t){let e=t.toLowerCase(),n=e.indexOf("/"),r=n>0?e.slice(0,n):"",o=Ze(e);return r==="openai"||r==="azure-openai"?"openai":r==="google"||r==="google-vertex"?"google":r==="anthropic"?"anthr\
385
+ opic":/^(gpt-|o[1-9](-|$))/.test(o)?"openai":o.startsWith("gemini")?"google":o.startsWith("claude-")?"anthropic":null}function Bp(t){return Date.parse(`${t}T23:59:59.999Z`)}function pn(t,e,n,r=Date.now()){
386
+ if(Je(n)===void 0)return;let o=Tt(n);if(o===void 0)return;let i=$p[t]?.[e],s=i?i[o]:void 0;if(s&&!(s.vigenteHasta&&r>Bp(s.vigenteHasta)))return s}function or(t){let e=Je(t);if(e)return {...e,cacheWritePer1k:e.
387
+ inputPer1k*Ge(Ze(t))}}var qa={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},Va=Math.min(...Object.values(qa).filter(t=>t<1)),Rt="flex";function ti(t){if(t==null||t==="")return null;let e=qa[t];return e==
388
+ null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}var ir=1e10;function ni(t){let e=Math.floor(t*ir)/ir;return e>t&&(e=(Math.floor(t*ir)-1)/ir),e<=0?0:e}var sr=t=>typeof t==
389
+ "number"&&Number.isFinite(t);function ar(t){let e=ti(t.tierServido);if(!e)return {ok:false,motivo:"no-served-tier"};if(e.factor==null)return {ok:false,motivo:"unknown-tier"};if(!e.conDescuento)return {ok:false,motivo:"\
390
+ standard-rate-tier"};let n=t.uso;if(n.complete===false||!sr(n.inputTokens)||!sr(n.outputTokens)||n.cachedInputTokens!=null&&!sr(n.cachedInputTokens)||n.cacheWriteInputTokens!=null&&!sr(n.cacheWriteInputTokens))
391
+ return {ok:false,motivo:"incomplete-usage"};let r=or(t.modelo);if(!r)return {ok:false,motivo:"no-standard-price"};let o=t.origen??dn(t.modelo),i=o?pn(o,e.servido,t.modelo,t.ahoraMs):void 0;if(!i)return {ok:false,
392
+ motivo:"no-tier-price"};let s=Math.max(0,n.inputTokens),a=Ge(Ze(t.modelo)),c=n.cachedInputTokens!=null,u=a<=1||n.cacheWriteInputTokens!=null,l=c?Math.min(Math.max(0,n.cachedInputTokens??0),s):0,d=a>1&&
392
393
  u?Math.min(Math.max(0,n.cacheWriteInputTokens??0),s-l):0,p=s-l-d,h=Math.max(0,n.outputTokens),m={input:r.inputPer1k,"cached input":r.cachedInputPer1k??r.inputPer1k,"cache write":r.cacheWritePer1k,output:r.
393
394
  outputPer1k},g={input:i.inputPer1k,"cached input":i.cachedInputPer1k,"cache write":i.cacheWritePer1k,output:i.outputPer1k},f=[{tokens:p,posibles:["input",...c?[]:["cached input"],...u?[]:["cache write"]]},
394
395
  {tokens:l,posibles:["cached input"]},{tokens:d,posibles:["cache write"]},{tokens:h,posibles:["output"]}],v=p>0&&f[0].posibles.length>1,b=t.precioDelCliente,y=b?{input:b.inputPer1k,"cached input":b.cachedInputPer1k??
395
396
  b.inputPer1k,"cache write":b.inputPer1k*a,output:b.outputPer1k}:void 0,k=(j,B)=>{let V=B?y[j]:m[j],z=g[j];return z===void 0?{std:V,aplicado:V}:B?{std:V,aplicado:m[j]>0?V*(z/m[j]):V}:{std:V,aplicado:z}},
396
- T=new Set,w=j=>{let B=0,V=0;for(let z of f){if(z.tokens<=0)continue;let ee=z.posibles[0],L=k(ee,j);for(let se of z.posibles.slice(1)){let ae=k(se,j);ae.std-ae.aplicado<L.std-L.aplicado&&(ee=se,L=ae);}g[ee]===
397
- void 0&&z.posibles.length===1&&T.add(ee),B+=z.tokens/1e3*L.std,V+=z.tokens/1e3*L.aplicado;}return {std:B,aplicado:V}},P=w(false),x=P.std-P.aplicado,S=P.std,O=P.aplicado,R=x,C=false;if(b){let j=w(true);S=j.std;let B=j.
398
- std-j.aplicado;C=B>x,R=Math.min(B,x),O=C?j.std-R:j.aplicado;}if(!(R>0))return {ok:false,motivo:"no-difference"};let I=ti(R);if(I<=0)return {ok:false,motivo:"no-difference"};let D=[];if(t.origen===null?D.push("\
399
- the endpoint is not the provider's own API as attested by this package's adapter, so the rate cards it bills cannot be confirmed"):t.tierLeidoDe!=="cuerpo"&&t.tierLeidoDe!=="lote"&&D.push("the served \
400
- tier was read from a response header whose values the provider does not document"),b&&D.push("priced from your costModels: your standard rate times the published tier-to-standard ratio"+(C?", capped a\
401
- t the difference between the two published rate cards":"")),v){let j=[...c?[]:["read from"],...u?[]:["written to"]].join(" or ");D.push(`the provider's usage did not say how many input tokens were ${j}\
402
- its prompt cache, so those tokens are priced at the smallest per-token difference they could have had`);}T.size>0&&D.push(`the provider publishes no ${[...T].join(" or ")} price for this tier, so thos\
403
- e tokens add nothing`);let A=D.length===0;return {ok:true,importe:I,basis:A?"measured":"estimated",costeEstandar:S,costeAplicado:O,factorEfectivo:O/S,motivoBasis:A?`the provider's own usage for this call\
397
+ T=new Set,x=j=>{let B=0,V=0;for(let z of f){if(z.tokens<=0)continue;let ee=z.posibles[0],L=k(ee,j);for(let se of z.posibles.slice(1)){let ae=k(se,j);ae.std-ae.aplicado<L.std-L.aplicado&&(ee=se,L=ae);}g[ee]===
398
+ void 0&&z.posibles.length===1&&T.add(ee),B+=z.tokens/1e3*L.std,V+=z.tokens/1e3*L.aplicado;}return {std:B,aplicado:V}},R=x(false),D=R.std-R.aplicado,I=R.std,E=R.aplicado,S=D,w=false;if(b){let j=x(true);I=j.std;let B=j.
399
+ std-j.aplicado;w=B>D,S=Math.min(B,D),E=w?j.std-S:j.aplicado;}if(!(S>0))return {ok:false,motivo:"no-difference"};let C=ni(S);if(C<=0)return {ok:false,motivo:"no-difference"};let _=[];if(t.origen===null?_.push("\
400
+ the endpoint is not the provider's own API as attested by this package's adapter, so the rate cards it bills cannot be confirmed"):t.tierLeidoDe!=="cuerpo"&&t.tierLeidoDe!=="lote"&&_.push("the served \
401
+ tier was read from a response header whose values the provider does not document"),b&&_.push("priced from your costModels: your standard rate times the published tier-to-standard ratio"+(w?", capped a\
402
+ t the difference between the two published rate cards":"")),v){let j=[...c?[]:["read from"],...u?[]:["written to"]].join(" or ");_.push(`the provider's usage did not say how many input tokens were ${j}\
403
+ its prompt cache, so those tokens are priced at the smallest per-token difference they could have had`);}T.size>0&&_.push(`the provider publishes no ${[...T].join(" or ")} price for this tier, so thos\
404
+ e tokens add nothing`);let O=_.length===0;return {ok:true,importe:C,basis:O?"measured":"estimated",costeEstandar:I,costeAplicado:E,factorEfectivo:E/I,motivoBasis:O?`the provider's own usage for this call\
404
405
  at two published rate cards (${i.fuente}, checked ${i.consultado}), with the served tier read back from the provider's official API`+(t.tierLeidoDe==="lote"?" (its batch record: a batch result is bil\
405
- led at the batch rate card)":""):`estimated: ${D.join("; ")}`,consultado:i.consultado}}function qa(t,e,n){let r=e??ln(t);return r!==null&&dn(r,"batch",t,n)!==void 0}var Lp="slower and variable: OpenAI\
406
+ led at the batch rate card)":""):`estimated: ${_.join("; ")}`,consultado:i.consultado}}function Ua(t,e,n){let r=e??dn(t);return r!==null&&pn(r,"batch",t,n)!==void 0}var Fp="slower and variable: OpenAI\
406
407
  publishes no latency commitment for the flex tier. What IS documented is the failure shape \u2014 the default SDK timeout is 10 minutes and a request that exceeds it returns 408, and when flex capacity is\
407
- short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",jp='slower and variable: Google targets minutes for the Flex tier ("Minutes (1\u201315 min target)\
408
+ short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",zp='slower and variable: Google targets minutes for the Flex tier ("Minutes (1\u201315 min target)\
408
409
  ", https://ai.google.dev/gemini-api/docs/flex-inference) and treats it as sheddable. When Flex capacity is unavailable the request fails with 503 or 429 and is never upgraded to the Standard tier on t\
409
- he server side. Do not put a deferrable request on a user-facing path.',Np="slower and variable, and unknown here: this endpoint is not attested as OpenAI's or Google's own API, so this layer has no p\
410
+ he server side. Do not put a deferrable request on a user-facing path.',qp="slower and variable, and unknown here: this endpoint is not attested as OpenAI's or Google's own API, so this layer has no p\
410
411
  ublished latency statement for it. On those two providers a flex request without capacity fails (429, or 503 on Google) instead of waiting; expect that failure shape. Do not put a deferrable request o\
411
- n a user-facing path.",$p="unchanged: this provider has no cheaper synchronous processing tier, so nothing was asked for and the request was scheduled exactly as it would have been.",Va="this provider\
412
+ n a user-facing path.",Vp="unchanged: this provider has no cheaper synchronous processing tier, so nothing was asked for and the request was scheduled exactly as it would have been.",Ha="this provider\
412
413
  has no cheaper synchronous processing tier, so the request was sent unchanged and nothing is credited; on this provider the deferred discount lives only in the asynchronous batch API, which is not a \
413
- request/response call (with the built-in Anthropic and OpenAI providers, layer.batches.submit() sends such requests there)";function Ua(t,e=null){return t==null||t===""?$p:t===Rt?e==="openai"?Lp:e==="\
414
- google"?jp:Np:`unknown: this layer has no published latency statement for the "${t}" tier. A cheaper tier without capacity usually fails (429 or 503) rather than waiting; do not put a deferrable reque\
415
- st on a user-facing path.`}var Ha=1024;function lt(t,e){return e==="openai"&&ln(Ge(t))==="openai"&&Ke(Ge(t))>1}function ni(t){let e=We(t);if(!e||!(e.inputPer1k>0))return null;let n=(e.cachedInputPer1k??e.inputPer1k)/e.inputPer1k;
416
- return {minimumCacheTokens:Ha,cacheReadMultiplier:n,cacheWriteMultiplier:Ke(Ge(t))}}function Wa(t){let e=t.consultado??bo,n=Math.max(0,t.uso.inputTokens),r=Math.min(Math.max(0,t.uso.cachedInputTokens??
417
- 0),n),o=Math.min(Math.max(0,t.uso.cacheWriteInputTokens??0),n-r),i=n-r-o;if(n<Ha||i<=0)return {importe:0,costeEstandar:0,costeAplicado:0,tokensOrdinarios:Math.max(0,i),consultado:e};let s=i/1e3*t.fila.
418
- cacheWritePer1k,a=i/1e3*t.fila.inputPer1k;return {importe:ti(s-a),costeEstandar:s,costeAplicado:a,tokensOrdinarios:i,consultado:e}}var Ja=new Set;function ye(t,e){Ja.has(t)||(Ja.add(t),console.warn(e));}var Bp={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function pn(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.protocol!==
419
- "https:"||e.port!==""?null:Bp[e.hostname.toLowerCase()]??null}catch{return null}}function ar(t){return pn(t)!==null?"oficial":"no-oficial"}var Ka=Symbol.for("@bivelio/savings-layer:provider-origin");function fn(t){return {esquemaEnFormatoNativo:false,esquemaEstricto:false,esquemaPorPrompt:false,piezasDelAdaptador:t}}var Fp=2;function Dt(t){return Fp*(t??[]).filter(e=>e.parameters==null).length}var cr=new WeakMap;
420
- function It(t,e){return cr.set(t,e),t}function ur(t){return typeof t=="object"&&t!==null?cr.get(t):void 0}var Ga=new WeakMap;function Za(t,e){Ga.set(t,e);}function dt(t){return typeof t=="object"&&t!==
421
- null?Ga.get(t):void 0}var Ya=new WeakMap;function lr(t,e){Ya.set(t,e);}function Qa(t){if(typeof t!="object"||t===null)return;let e=Ya.get(t);if(e!==void 0)return e;try{let n=t[Ka];if(typeof n!="functio\
422
- n")return;let r=n.call(t);return r==="oficial"||r==="no-oficial"?r:void 0}catch{return}}function Xa(t,e){let n=cr.get(t);return n&&cr.set(e,n),e}var ec=new WeakMap;function tc(t,e){ec.set(t,e);}function ri(t){
423
- return typeof t=="object"&&t!==null?ec.get(t):void 0}var nc=new WeakSet;function rc(t){typeof t=="object"&&t!==null&&nc.add(t);}function zp(t){return nc.has(t)}function _t(t,e,n){zp(t)||ye(e,n);}var oc=new WeakMap;function dr(t,e){oc.set(t,e);}function ic(t){return typeof t=="object"&&t!==null?oc.get(t):void 0}function pr(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.
424
- hash="",e.toString().replace(/\/+$/,"")}catch{return t.replace(/\/+$/,"")}}function fr(t){if(!t.startsWith("/")||t.startsWith("//")||/^\/*[a-z][a-z0-9+.-]*:/i.test(t))throw new Error(`[bvsala] interna\
425
- l: a batch request path must be relative to the provider base (got "${t}")`);return t}var oi=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(
414
+ request/response call (with the built-in Anthropic and OpenAI providers, layer.batches.submit() sends such requests there)";function Wa(t,e=null){return t==null||t===""?Vp:t===Rt?e==="openai"?Fp:e==="\
415
+ google"?zp:qp:`unknown: this layer has no published latency statement for the "${t}" tier. A cheaper tier without capacity usually fails (429 or 503) rather than waiting; do not put a deferrable reque\
416
+ st on a user-facing path.`}var Ja=1024;function dt(t,e){return e==="openai"&&dn(Ze(t))==="openai"&&Ge(Ze(t))>1}function ri(t){let e=Je(t);if(!e||!(e.inputPer1k>0))return null;let n=(e.cachedInputPer1k??e.inputPer1k)/e.inputPer1k;
417
+ return {minimumCacheTokens:Ja,cacheReadMultiplier:n,cacheWriteMultiplier:Ge(Ze(t))}}function Ka(t){let e=t.consultado??vo,n=Math.max(0,t.uso.inputTokens),r=Math.min(Math.max(0,t.uso.cachedInputTokens??
418
+ 0),n),o=Math.min(Math.max(0,t.uso.cacheWriteInputTokens??0),n-r),i=n-r-o;if(n<Ja||i<=0)return {importe:0,costeEstandar:0,costeAplicado:0,tokensOrdinarios:Math.max(0,i),consultado:e};let s=i/1e3*t.fila.
419
+ cacheWritePer1k,a=i/1e3*t.fila.inputPer1k;return {importe:ni(s-a),costeEstandar:s,costeAplicado:a,tokensOrdinarios:i,consultado:e}}var Ga=new Set;function ke(t,e){Ga.has(t)||(Ga.add(t),console.warn(e));}var Up={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function fn(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.protocol!==
420
+ "https:"||e.port!==""?null:Up[e.hostname.toLowerCase()]??null}catch{return null}}function cr(t){return fn(t)!==null?"oficial":"no-oficial"}var Za=Symbol.for("@bivelio/savings-layer:provider-origin");function mn(t){return {esquemaEnFormatoNativo:false,esquemaEstricto:false,esquemaPorPrompt:false,piezasDelAdaptador:t}}var Hp=2;function Dt(t){return Hp*(t??[]).filter(e=>e.parameters==null).length}var ur=new WeakMap;
421
+ function It(t,e){return ur.set(t,e),t}function lr(t){return typeof t=="object"&&t!==null?ur.get(t):void 0}var Ya=new WeakMap;function Qa(t,e){Ya.set(t,e);}function pt(t){return typeof t=="object"&&t!==
422
+ null?Ya.get(t):void 0}var Xa=new WeakMap;function dr(t,e){Xa.set(t,e);}function ec(t){if(typeof t!="object"||t===null)return;let e=Xa.get(t);if(e!==void 0)return e;try{let n=t[Za];if(typeof n!="functio\
423
+ n")return;let r=n.call(t);return r==="oficial"||r==="no-oficial"?r:void 0}catch{return}}function tc(t,e){let n=ur.get(t);return n&&ur.set(e,n),e}var nc=new WeakMap;function rc(t,e){nc.set(t,e);}function oi(t){
424
+ return typeof t=="object"&&t!==null?nc.get(t):void 0}var oc=new WeakSet;function ic(t){typeof t=="object"&&t!==null&&oc.add(t);}function Wp(t){return oc.has(t)}function _t(t,e,n){Wp(t)||ke(e,n);}var sc=new WeakMap;function pr(t,e){sc.set(t,e);}function ac(t){return typeof t=="object"&&t!==null?sc.get(t):void 0}function fr(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.
425
+ hash="",e.toString().replace(/\/+$/,"")}catch{return t.replace(/\/+$/,"")}}function mr(t){if(!t.startsWith("/")||t.startsWith("//")||/^\/*[a-z][a-z0-9+.-]*:/i.test(t))throw new Error(`[bvsala] interna\
426
+ l: a batch request path must be relative to the provider base (got "${t}")`);return t}var ii=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(
426
427
  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,
427
428
  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(
428
429
  0)===10&&(o=1));let i=o;for(;o<r.length;){let s=r.charCodeAt(o);if(s!==10&&s!==13){o++;continue}this.linea(this.resto+r.slice(i,o),n),this.resto="",s===13&&(o+1<r.length?r.charCodeAt(o+1)===10&&o++:this.
429
430
  crPendiente=true),o++,i=o;}return this.resto+=r.slice(i),n}linea(e,n){if(e===""){this.despachar(n);return}if(e.charCodeAt(0)===58)return;let r=e.indexOf(":"),o,i;switch(r===-1?(o=e,i=""):(o=e.slice(0,r),
430
431
  i=e.slice(r+1),i.charCodeAt(0)===32&&(i=i.slice(1))),o){case "data":this.datos+=i+`
431
432
  `;break;case "event":this.evento=i;break;case "id":i.includes("\0")||(this.ultimoId=i);break;}}despachar(e){if(this.datos===""){this.evento="";return}e.push({event:this.evento===""?"message":
432
- this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};async function*mr(t){let e=new oi;if(typeof t=="string"){yield*e.push(t),yield*e.
433
- 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 Ze(t){if(t==null||typeof t!="object")return true;let e=t,n=e.properties;if(n&&typeof n=="object"){if(e.additionalProperties!==false)return false;let o=Object.keys(n),i=Array.isArray(e.required)?e.required.
434
- map(String):[];if(o.some(s=>!i.includes(s)))return false;for(let s of Object.values(n))if(!Ze(s))return false}if(e.items!==void 0&&!Ze(e.items))return false;for(let o of ["anyOf","oneOf","allOf"]){let i=e[o];if(Array.
435
- isArray(i)&&i.some(s=>!Ze(s)))return false}let r=e.$defs??e.definitions;return !(r&&typeof r=="object"&&Object.values(r).some(o=>!Ze(o)))}function qp(t){return !/response_format/i.test(t)||/invalid schema/i.
436
- test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.test(t)}function Vp(t){return `Respond with a single JSON object and nothing else: no prose, no\
433
+ this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};async function*hr(t){let e=new ii;if(typeof t=="string"){yield*e.push(t),yield*e.
434
+ 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 Ye(t){if(t==null||typeof t!="object")return true;let e=t,n=e.properties;if(n&&typeof n=="object"){if(e.additionalProperties!==false)return false;let o=Object.keys(n),i=Array.isArray(e.required)?e.required.
435
+ map(String):[];if(o.some(s=>!i.includes(s)))return false;for(let s of Object.values(n))if(!Ye(s))return false}if(e.items!==void 0&&!Ye(e.items))return false;for(let o of ["anyOf","oneOf","allOf"]){let i=e[o];if(Array.
436
+ isArray(i)&&i.some(s=>!Ye(s)))return false}let r=e.$defs??e.definitions;return !(r&&typeof r=="object"&&Object.values(r).some(o=>!Ye(o)))}function Jp(t){return !/response_format/i.test(t)||/invalid schema/i.
437
+ test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.test(t)}function Kp(t){return `Respond with a single JSON object and nothing else: no prose, no\
437
438
  explanation, no markdown code fences. The object must validate against this JSON Schema:
438
- `+JSON.stringify(t)}var Up=/(^|\.)api\.openai\.com$|\.openai\.azure\.com$/i;function ii(t,e,n){return e??Wp(n)?t.replace(/^[^/]+\//,""):t}function Hp(t){let e=pn(t);return e==="openai"||e==="google"?e:
439
- null}var sc="x-gemini-service-tier";function ac(t,e){try{let n=t.headers?.get?.(e);return typeof n=="string"&&n.trim()!==""?n.trim():void 0}catch{return}}function si(t,e,n){if(e.explicitCacheWrites!==
440
- true||!lt(t,n))return null;let r=e.stablePrefixMessages;if(r==null||!Number.isInteger(r)||r<=0||r>e.messages.length)return {puntos:0,indice:-1};let o=e.messages[r-1];return (o.role==="system"||o.role==="u\
441
- ser"||o.role==="tool")&&typeof o.content=="string"&&o.content!==""?{puntos:1,indice:r-1}:{puntos:0,indice:-1}}function Wp(t){try{return Up.test(new URL(t).hostname)}catch{return false}}var cc=class{id;opts;fetchImpl;sinResponseFormat=new Set;streamOptionsRejected=false;origen;constructor(e){
442
- this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch,this.origen=Hp(e.baseUrl),Za(this,this.origen),lr(this,ar(e.baseUrl));let n=(o,i)=>o.schema!=null&&!this.sinResponseFormat.
443
- has(i),r=o=>ii(o,this.opts.stripProviderPrefix,this.opts.baseUrl);dr(this,{protocolo:"openai",origen:this.origen,endpoint:pr(e.baseUrl),cuerpo:o=>{let i=r(o.model);return this.construirCuerpo(i,o,n(o,
444
- i))},leer:(o,i)=>{let s=r(i.model);return this.leerJson(o,void 0,i,n(i,s),s,false)},solicitar:(o,i)=>this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}${fr(o)}`,{method:i.method,headers:{...i.json!==
439
+ `+JSON.stringify(t)}var Gp=/(^|\.)api\.openai\.com$|\.openai\.azure\.com$/i;function si(t,e,n){return e??Yp(n)?t.replace(/^[^/]+\//,""):t}function Zp(t){let e=fn(t);return e==="openai"||e==="google"?e:
440
+ null}var cc="x-gemini-service-tier";function uc(t,e){try{let n=t.headers?.get?.(e);return typeof n=="string"&&n.trim()!==""?n.trim():void 0}catch{return}}function ai(t,e,n){if(e.explicitCacheWrites!==
441
+ true||!dt(t,n))return null;let r=e.stablePrefixMessages;if(r==null||!Number.isInteger(r)||r<=0||r>e.messages.length)return {puntos:0,indice:-1};let o=e.messages[r-1];return (o.role==="system"||o.role==="u\
442
+ ser"||o.role==="tool")&&typeof o.content=="string"&&o.content!==""?{puntos:1,indice:r-1}:{puntos:0,indice:-1}}function Yp(t){try{return Gp.test(new URL(t).hostname)}catch{return false}}var lc=class{id;opts;fetchImpl;sinResponseFormat=new Set;streamOptionsRejected=false;origen;constructor(e){
443
+ this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch,this.origen=Zp(e.baseUrl),Qa(this,this.origen),dr(this,cr(e.baseUrl));let n=(o,i)=>o.schema!=null&&!this.sinResponseFormat.
444
+ has(i),r=o=>si(o,this.opts.stripProviderPrefix,this.opts.baseUrl);pr(this,{protocolo:"openai",origen:this.origen,endpoint:fr(e.baseUrl),cuerpo:o=>{let i=r(o.model);return this.construirCuerpo(i,o,n(o,
445
+ i))},leer:(o,i)=>{let s=r(i.model);return this.leerJson(o,void 0,i,n(i,s),s,false)},solicitar:(o,i)=>this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}${mr(o)}`,{method:i.method,headers:{...i.json!==
445
446
  void 0?{"content-type":"application/json"}:{},...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.headers},...i.json!==void 0?{body:JSON.stringify(i.json)}:i.form?{body:i.
446
- form}:{},...i.signal?{signal:i.signal}:{}})});}async generate(e,n){let r=ii(e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n?.signal,i=e.schema!=null&&!this.sinResponseFormat.has(r),s=await this.
447
- enviar(r,e,i,void 0,o);if(!s.ok&&s.status===400&&i){let a=await gr(s);if(!qp(a))throw new Error(`provider ${s.status}: ${a}`);this.sinResponseFormat.add(r),_t(this,`sin-response-format:${r}`,`[bvsala]\
447
+ form}:{},...i.signal?{signal:i.signal}:{}})});}async generate(e,n){let r=si(e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n?.signal,i=e.schema!=null&&!this.sinResponseFormat.has(r),s=await this.
448
+ enviar(r,e,i,void 0,o);if(!s.ok&&s.status===400&&i){let a=await br(s);if(!Jp(a))throw new Error(`provider ${s.status}: ${a}`);this.sinResponseFormat.add(r),_t(this,`sin-response-format:${r}`,`[bvsala]\
448
449
  Model "${r}" rejects \`response_format\` with a 400: it has no structured outputs. The request is repeated asking for the JSON via prompt (once only: the model is noted and the following requests go st\
449
450
  raight there). The schema still travels and the layer still validates, but the guarantee comes from the layer, not the provider, and the report says so: \`constraints.backend: "none"\`. To recover the n\
450
- ative guarantee, use a model with structured outputs (gpt-4o or later).`),i=false,s=await this.enviar(r,e,false,void 0,o);}if(!s.ok){let a=await gr(s);throw new Error(`provider ${s.status}: ${a}`)}return this.
451
- leer(s,e,i,r)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let x=await this.generate(e);x.text!==""&&(yield {type:"text",delta:x.text}),yield {type:"done",response:x};return}let r=ii(
451
+ ative guarantee, use a model with structured outputs (gpt-4o or later).`),i=false,s=await this.enviar(r,e,false,void 0,o);}if(!s.ok){let a=await br(s);throw new Error(`provider ${s.status}: ${a}`)}return this.
452
+ leer(s,e,i,r)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let D=await this.generate(e);D.text!==""&&(yield {type:"text",delta:D.text}),yield {type:"done",response:D};return}let r=si(
452
453
  e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n.signal,i=!this.streamOptionsRejected,s=await this.enviar(r,e,false,{includeUsage:i,...o?{signal:o}:{}});if(!s.ok&&i&&(s.status===400||s.status===
453
- 422)){let x=await gr(s);if(s.status!==422&&!/stream_options|include_usage/i.test(x))throw new Error(`provider ${s.status}: ${x}`);if(this.opts.requireUsage)throw new Error(`provider ${s.status}: this \
454
- endpoint rejects stream_options, so a streamed answer would carry no usage and requireUsage is set. ${x}`);s=await this.enviar(r,e,false,{includeUsage:false,...o?{signal:o}:{}}),s.ok&&(this.streamOptionsRejected=
454
+ 422)){let D=await br(s);if(s.status!==422&&!/stream_options|include_usage/i.test(D))throw new Error(`provider ${s.status}: ${D}`);if(this.opts.requireUsage)throw new Error(`provider ${s.status}: this \
455
+ endpoint rejects stream_options, so a streamed answer would carry no usage and requireUsage is set. ${D}`);s=await this.enviar(r,e,false,{includeUsage:false,...o?{signal:o}:{}}),s.ok&&(this.streamOptionsRejected=
455
456
  true,_t(this,`sin-stream-options:${this.opts.baseUrl}`,"[bvsala] This endpoint rejects `stream_options`, so streamed answers from it carry no usage: they are reported as `unmeasured` and never billed. U\
456
- se `generate()` for a measured figure, or an endpoint that reports usage when streaming."));}if(!s.ok)throw new Error(`provider ${s.status}: ${await gr(s)}`);if((s.headers.get("content-type")??"").includes(
457
- "application/json")){let x=await this.leer(s,e,false,r);x.text!==""&&(yield {type:"text",delta:x.text}),yield {type:"done",response:x};return}let a=s.body,c=a&&typeof a.getReader=="function"?a:await s.text(),
458
- u="",l=new Map,d,p,h,m=false,g="";for await(let x of mr(c)){if(x.data==="[DONE]")break;let S;try{S=JSON.parse(x.data);}catch{continue}if(S===null||typeof S!="object")continue;if(S.error!=null){let C=S.error,
459
- I=typeof C.message=="string"?C.message:JSON.stringify(S.error);throw new Error(`provider stream error: ${I}`)}let O=S.choices?.[0],R=O?.delta;(hr(R?.reasoning_content)||hr(R?.reasoning))&&(m=true),typeof R?.
460
- content=="string"&&R.content!==""&&(u+=R.content,yield {type:"text",delta:R.content}),typeof R?.refusal=="string"&&(g+=R.refusal);for(let C of R?.tool_calls??[]){let I=typeof C.index=="number"?C.index:
461
- 0,D=l.get(I)??{args:""};!D.id&&typeof C.id=="string"&&C.id!==""&&(D.id=C.id);let A=C.function?.name;!D.name&&typeof A=="string"&&A!==""&&(D.name=A),typeof C.function?.arguments=="string"&&(D.args+=C.function.
462
- arguments),l.set(I,D);}O?.finish_reason!=null&&(d=O.finish_reason),S.usage!=null&&typeof S.usage=="object"&&(p=S.usage),typeof S.service_tier=="string"&&S.service_tier!==""&&(h=S.service_tier);}if(d===void 0)
457
+ se `generate()` for a measured figure, or an endpoint that reports usage when streaming."));}if(!s.ok)throw new Error(`provider ${s.status}: ${await br(s)}`);if((s.headers.get("content-type")??"").includes(
458
+ "application/json")){let D=await this.leer(s,e,false,r);D.text!==""&&(yield {type:"text",delta:D.text}),yield {type:"done",response:D};return}let a=s.body,c=a&&typeof a.getReader=="function"?a:await s.text(),
459
+ u="",l=new Map,d,p,h,m=false,g="";for await(let D of hr(c)){if(D.data==="[DONE]")break;let I;try{I=JSON.parse(D.data);}catch{continue}if(I===null||typeof I!="object")continue;if(I.error!=null){let w=I.error,
460
+ C=typeof w.message=="string"?w.message:JSON.stringify(I.error);throw new Error(`provider stream error: ${C}`)}let E=I.choices?.[0],S=E?.delta;(gr(S?.reasoning_content)||gr(S?.reasoning))&&(m=true),typeof S?.
461
+ content=="string"&&S.content!==""&&(u+=S.content,yield {type:"text",delta:S.content}),typeof S?.refusal=="string"&&(g+=S.refusal);for(let w of S?.tool_calls??[]){let C=typeof w.index=="number"?w.index:
462
+ 0,_=l.get(C)??{args:""};!_.id&&typeof w.id=="string"&&w.id!==""&&(_.id=w.id);let O=w.function?.name;!_.name&&typeof O=="string"&&O!==""&&(_.name=O),typeof w.function?.arguments=="string"&&(_.args+=w.function.
463
+ arguments),l.set(C,_);}E?.finish_reason!=null&&(d=E.finish_reason),I.usage!=null&&typeof I.usage=="object"&&(p=I.usage),typeof I.service_tier=="string"&&I.service_tier!==""&&(h=I.service_tier);}if(d===void 0)
463
464
  throw new Error("provider stream ended before completion (no finish_reason)");let f=typeof p?.prompt_tokens!="number",v=typeof p?.completion_tokens!="number";if(this.opts.requireUsage&&(f||v))throw new Error(
464
- dc(p?.prompt_tokens,p?.completion_tokens));let b=uc(p,m),y=lc(p),k={inputTokens:p?.prompt_tokens??0,outputTokens:p?.completion_tokens??0,...p?.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:p.
465
- prompt_tokens_details.cached_tokens}:{},...y!==void 0?{cacheWriteInputTokens:y}:{},...b!==void 0?{reasoningTokens:b}:{},...f||v?{complete:false}:{}},T=[...l.entries()].sort((x,S)=>x[0]-S[0]).map(([,x])=>({
466
- ...x.id?{id:x.id}:{},name:x.name??"",arguments:x.args})).filter(x=>x.name!==""),w=h?"cuerpo":void 0;!h&&this.origen==="google"&&(h=ac(s,sc),h&&(w="cabecera"));let P=si(r,e,this.origen);yield {type:"don\
467
- e",response:It({text:u,...T.length>0?{toolCalls:T}:{},finishReason:d,...g!==""?{refusal:g}:{},...h?{servedServiceTier:h}:{},usage:k,structuredNatively:false,raw:p??null},{...fn(Dt(e.tools)),origen:this.origen,
468
- ...w?{tierLeidoDe:w}:{},...P?{cacheExplicita:{puntos:P.puntos}}:{}})};}async enviar(e,n,r,o,i){let s=this.construirCuerpo(e,n,r,o);return await this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}/ch\
465
+ fc(p?.prompt_tokens,p?.completion_tokens));let b=dc(p,m),y=pc(p),k={inputTokens:p?.prompt_tokens??0,outputTokens:p?.completion_tokens??0,...p?.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:p.
466
+ prompt_tokens_details.cached_tokens}:{},...y!==void 0?{cacheWriteInputTokens:y}:{},...b!==void 0?{reasoningTokens:b}:{},...f||v?{complete:false}:{}},T=[...l.entries()].sort((D,I)=>D[0]-I[0]).map(([,D])=>({
467
+ ...D.id?{id:D.id}:{},name:D.name??"",arguments:D.args})).filter(D=>D.name!==""),x=h?"cuerpo":void 0;!h&&this.origen==="google"&&(h=uc(s,cc),h&&(x="cabecera"));let R=ai(r,e,this.origen);yield {type:"don\
468
+ e",response:It({text:u,...T.length>0?{toolCalls:T}:{},finishReason:d,...g!==""?{refusal:g}:{},...h?{servedServiceTier:h}:{},usage:k,structuredNatively:false,raw:p??null},{...mn(Dt(e.tools)),origen:this.origen,
469
+ ...x?{tierLeidoDe:x}:{},...R?{cacheExplicita:{puntos:R.puntos}}:{}})};}async enviar(e,n,r,o,i){let s=this.construirCuerpo(e,n,r,o);return await this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}/ch\
469
470
  at/completions`,{method:"POST",headers:{"content-type":"application/json",...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.headers},body:JSON.stringify(s),...o?.signal?
470
471
  {signal:o.signal}:!o&&i?{signal:i}:{}})}construirCuerpo(e,n,r,o){let i=n.messages.map(c=>c.role==="tool"?{role:"tool",content:c.content,tool_call_id:c.toolCallId??c.metadata?.tool_call_id,...c.name?{name:c.
471
472
  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.id??`call_${l}`,type:"function",function:{name:u.name,
472
- arguments:u.arguments}}))}:{role:c.role,content:c.content}),s=si(e,n,this.origen);if(s?.puntos===1){let c=i[s.indice];c.content=[{type:"text",text:c.content,prompt_cache_breakpoint:{mode:"explicit"}}];}
473
- n.schema&&!r&&i.push({role:"system",content:Vp(n.schema)});let a={model:e,messages:i};if(n.maxOutputTokens!=null&&(a.max_tokens=n.maxOutputTokens),n.temperature!=null&&(a.temperature=n.temperature),n.
474
- seed!=null&&(a.seed=n.seed),n.promptCacheKey!=null&&(a.prompt_cache_key=n.promptCacheKey),n.deferrable===true&&(a.service_tier=Rt),s&&(a.prompt_cache_options={mode:"explicit"}),n.schema&&r){let c=Ze(n.schema);
473
+ arguments:u.arguments}}))}:{role:c.role,content:c.content}),s=ai(e,n,this.origen);if(s?.puntos===1){let c=i[s.indice];c.content=[{type:"text",text:c.content,prompt_cache_breakpoint:{mode:"explicit"}}];}
474
+ n.schema&&!r&&i.push({role:"system",content:Kp(n.schema)});let a={model:e,messages:i};if(n.maxOutputTokens!=null&&(a.max_tokens=n.maxOutputTokens),n.temperature!=null&&(a.temperature=n.temperature),n.
475
+ seed!=null&&(a.seed=n.seed),n.promptCacheKey!=null&&(a.prompt_cache_key=n.promptCacheKey),n.deferrable===true&&(a.service_tier=Rt),s&&(a.prompt_cache_options={mode:"explicit"}),n.schema&&r){let c=Ye(n.schema);
475
476
  c||_t(this,"strict-incompatible","[bvsala] The response contract does not meet OpenAI's `strict` mode (in strict, `required` must list ALL the keys in `properties`, and every object needs `additionalP\
476
477
  roperties: false`). The schema is sent with `strict: false`: the model is still guided and the layer still validates, but the guarantee comes from the layer, not the provider. To recover it, make ever\
477
478
  y key in the contract required."),a.response_format={type:"json_schema",json_schema:{name:"bvsala_contract",schema:n.schema,strict:c}};}return n.tools&&n.tools.length>0&&(a.tools=n.tools.map(c=>({type:"\
478
479
  function",function:{name:c.id,...c.description?{description:c.description}:{},parameters:c.parameters??{type:"object",properties:{}}}}))),o&&(a.stream=true,o.includeUsage&&(a.stream_options={include_usage:true})),
479
480
  a}async leer(e,n,r,o){let i=await e.json();return this.leerJson(i,e,n,r,o,this.opts.requireUsage===true)}leerJson(e,n,r,o,i,s){let a=e.choices?.[0]?.message,c=a?.content??"",u=typeof a?.refusal=="string"&&
480
- a.refusal!==""?a.refusal:void 0,l=(a?.tool_calls??[]).map(w=>({...w.id?{id:w.id}:{},name:w.function?.name??"",arguments:w.function?.arguments??""})).filter(w=>w.name!==""),d=e.usage??{},p=d.prompt_tokens??
481
- 0,h=d.completion_tokens??0,m=typeof d.prompt_tokens!="number",g=typeof d.completion_tokens!="number";if(s&&(m||g))throw new Error(dc(d.prompt_tokens,d.completion_tokens));let f=e.choices?.[0]?.finish_reason,
482
- v=typeof e.service_tier=="string"&&e.service_tier!==""?e.service_tier:void 0,b=v?"cuerpo":void 0;!v&&this.origen==="google"&&n&&(v=ac(n,sc),v&&(b="cabecera"));let y=lc(d),k=si(i,r,this.origen),T=uc(d,
483
- hr(a?.reasoning_content)||hr(a?.reasoning));return It({text:c,...l.length>0?{toolCalls:l}:{},...f?{finishReason:f}:{},...u!==void 0?{refusal:u}:{},...v?{servedServiceTier:v}:{},...r.deferrable===true?{requestedServiceTier:Rt}:
481
+ a.refusal!==""?a.refusal:void 0,l=(a?.tool_calls??[]).map(x=>({...x.id?{id:x.id}:{},name:x.function?.name??"",arguments:x.function?.arguments??""})).filter(x=>x.name!==""),d=e.usage??{},p=d.prompt_tokens??
482
+ 0,h=d.completion_tokens??0,m=typeof d.prompt_tokens!="number",g=typeof d.completion_tokens!="number";if(s&&(m||g))throw new Error(fc(d.prompt_tokens,d.completion_tokens));let f=e.choices?.[0]?.finish_reason,
483
+ v=typeof e.service_tier=="string"&&e.service_tier!==""?e.service_tier:void 0,b=v?"cuerpo":void 0;!v&&this.origen==="google"&&n&&(v=uc(n,cc),v&&(b="cabecera"));let y=pc(d),k=ai(i,r,this.origen),T=dc(d,
484
+ gr(a?.reasoning_content)||gr(a?.reasoning));return It({text:c,...l.length>0?{toolCalls:l}:{},...f?{finishReason:f}:{},...u!==void 0?{refusal:u}:{},...v?{servedServiceTier:v}:{},...r.deferrable===true?{requestedServiceTier:Rt}:
484
485
  {},usage:{inputTokens:p,outputTokens:h,...d.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:d.prompt_tokens_details.cached_tokens}:{},...y!==void 0?{cacheWriteInputTokens:y}:{},...T!==void 0?
485
- {reasoningTokens:T}:{},...m||g?{complete:false}:{}},structuredNatively:r.schema!=null&&o,raw:e},{esquemaEnFormatoNativo:r.schema!=null&&o,esquemaEstricto:r.schema!=null&&o&&Ze(r.schema),esquemaPorPrompt:r.
486
- schema!=null&&!o,piezasDelAdaptador:Dt(r.tools),origen:this.origen,...b?{tierLeidoDe:b}:{},...k?{cacheExplicita:{puntos:k.puntos}}:{}})}};function uc(t,e){let n=t?.completion_tokens_details?.reasoning_tokens;
487
- if(!(typeof n!="number"||!Number.isInteger(n)||n<0)&&!(n===0&&e))return n}function lc(t){let e=t?.prompt_tokens_details?.cache_write_tokens;return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:void 0}
488
- function hr(t){return typeof t=="string"&&t!==""}function dc(t,e){return `provider returned incomplete usage (prompt=${t??"absent"}, completion=${e??"absent"}); cannot measure cost. For gateways/stream\
489
- ing, ensure usage reporting is enabled.`}async function gr(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function pc(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:
490
- `+JSON.stringify(t)}function fc(t){let e=[];for(let n of t){if(n.type!=="server_tool_use")continue;let r=n.id,o=n.name;if(typeof r!="string"||typeof o!="string"||!o.startsWith("tool_search_tool"))continue;let i=t.find(u=>u.
486
+ {reasoningTokens:T}:{},...m||g?{complete:false}:{}},structuredNatively:r.schema!=null&&o,raw:e},{esquemaEnFormatoNativo:r.schema!=null&&o,esquemaEstricto:r.schema!=null&&o&&Ye(r.schema),esquemaPorPrompt:r.
487
+ schema!=null&&!o,piezasDelAdaptador:Dt(r.tools),origen:this.origen,...b?{tierLeidoDe:b}:{},...k?{cacheExplicita:{puntos:k.puntos}}:{}})}};function dc(t,e){let n=t?.completion_tokens_details?.reasoning_tokens;
488
+ if(!(typeof n!="number"||!Number.isInteger(n)||n<0)&&!(n===0&&e))return n}function pc(t){let e=t?.prompt_tokens_details?.cache_write_tokens;return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:void 0}
489
+ function gr(t){return typeof t=="string"&&t!==""}function fc(t,e){return `provider returned incomplete usage (prompt=${t??"absent"}, completion=${e??"absent"}); cannot measure cost. For gateways/stream\
490
+ ing, ensure usage reporting is enabled.`}async function br(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function mc(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:
491
+ `+JSON.stringify(t)}function hc(t){let e=[];for(let n of t){if(n.type!=="server_tool_use")continue;let r=n.id,o=n.name;if(typeof r!="string"||typeof o!="string"||!o.startsWith("tool_search_tool"))continue;let i=t.find(u=>u.
491
492
  type==="tool_search_tool_result"&&u.tool_use_id===r),s=i?.content;if(!i||!s||s.type!=="tool_search_tool_search_result"||!Array.isArray(s.tool_references)||s.tool_references.length===0)continue;let a=[],
492
- c=true;for(let u of s.tool_references){if(typeof u?.tool_name!="string"){c=false;break}a.includes(u.tool_name)||a.push(u.tool_name);}c&&e.push({busqueda:o,id:r,uso:n,resultado:i,herramientas:a});}return e}var Jp={
493
- bytes:4*1024*1024,porEntrada:64*1024,claves:4096},br=class{constructor(e=Jp){this.topes=e;}topes;entradas=new Map;bytes=0;recordar(e,n){if(e.length===0||n.length===0)return;let r=JSON.parse(JSON.stringify(
493
+ c=true;for(let u of s.tool_references){if(typeof u?.tool_name!="string"){c=false;break}a.includes(u.tool_name)||a.push(u.tool_name);}c&&e.push({busqueda:o,id:r,uso:n,resultado:i,herramientas:a});}return e}var Qp={
494
+ bytes:4*1024*1024,porEntrada:64*1024,claves:4096},vr=class{constructor(e=Qp){this.topes=e;}topes;entradas=new Map;bytes=0;recordar(e,n){if(e.length===0||n.length===0)return;let r=JSON.parse(JSON.stringify(
494
495
  n)),o=JSON.stringify(r).length;if(o>this.topes.porEntrada)return;let i={pares:r,bytes:o};for(let s of new Set(e))this.quitar(s),this.entradas.set(s,i),this.bytes+=o;for(;this.entradas.size>0&&(this.bytes>
495
496
  this.topes.bytes||this.entradas.size>this.topes.claves);){let s=this.entradas.keys().next().value;this.quitar(s);}}para(e){let n;for(let r of e){let o=this.entradas.get(r);o&&(this.entradas.delete(r),this.
496
- entradas.set(r,o),n??=o);}return n?JSON.parse(JSON.stringify(n.pares)):void 0}get tamano(){return this.entradas.size}quitar(e){let n=this.entradas.get(e);n&&(this.entradas.delete(e),this.bytes-=n.bytes);}};var At=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:0;function mc(t){if(!Array.isArray(t))return null;let e={input:0,output:0,cacheRead:0,cacheWrite:0,cacheWrite1h:0,iteraciones:0};for(let n of t){
497
+ entradas.set(r,o),n??=o);}return n?JSON.parse(JSON.stringify(n.pares)):void 0}get tamano(){return this.entradas.size}quitar(e){let n=this.entradas.get(e);n&&(this.entradas.delete(e),this.bytes-=n.bytes);}};var At=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:0;function gc(t){if(!Array.isArray(t))return null;let e={input:0,output:0,cacheRead:0,cacheWrite:0,cacheWrite1h:0,iteraciones:0};for(let n of t){
497
498
  if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;e.iteraciones++,e.input+=At(r.input_tokens),e.output+=At(r.output_tokens),e.cacheRead+=At(r.cache_read_input_tokens);
498
499
  let o=r.cache_creation,i=At(o?.ephemeral_5m_input_tokens),s=At(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?At(r.cache_creation_input_tokens):i+s;e.cacheWrite+=a,e.cacheWrite1h+=
499
- Math.min(s,a);}return e.iteraciones>0?e:null}function ai(t,e,n){let r=t??{},o=mc(r.iterations),i=hc(r.cache_read_input_tokens,o?.cacheRead),s=hc(r.cache_creation_input_tokens,o?.cacheWrite),a=r.cache_creation?.ephemeral_1h_input_tokens,c=typeof a==
500
+ Math.min(s,a);}return e.iteraciones>0?e:null}function ci(t,e,n){let r=t??{},o=gc(r.iterations),i=bc(r.cache_read_input_tokens,o?.cacheRead),s=bc(r.cache_creation_input_tokens,o?.cacheWrite),a=r.cache_creation?.ephemeral_1h_input_tokens,c=typeof a==
500
501
  "number"||(o?.cacheWrite1h??0)>0?Math.min(Math.max(0,(typeof a=="number"?a:0)+(o?.cacheWrite1h??0)),s??0):void 0,u=(r.input_tokens??0)+(o?.input??0)+(s??0)+(i??0),l=(e??0)+(o?.output??0),d=typeof r.input_tokens!=
501
502
  "number",p=typeof e!="number";return {usage:{inputTokens:u,outputTokens:l,...i!=null?{cachedInputTokens:i}:{},...s!=null?{cacheWriteInputTokens:s}:{},...c!==void 0?{cacheWrite1hInputTokens:c}:{},...n||
502
- p||o?{}:{reasoningTokens:0},...d||p?{complete:false}:{}},entradaAusente:d,salidaAusente:p}}function hc(t,e){return e?(t??0)+e:t}function ci(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
503
- function ui(t,e){let n=Object.fromEntries(Object.entries(e??{}).filter(([,o])=>o!=null)),r=t?.cache_creation||e?.cache_creation?{...t?.cache_creation??{},...e?.cache_creation??{}}:void 0;return {...t??
504
- {},...n,...r?{cache_creation:r}:{}}}function li(t){return t==="thinking"||t==="redacted_thinking"}function di(t){switch(t){case "end_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "\
505
- tool_calls";case "refusal":return "content_filter";default:return t}}var vr=4,Ye="bvsala_contract",Kp={"sin-ids":'[bvsala] A tool conversation reached the Anthropic adapter without its call ids. To send it the way the Messages API expects (`tool_use` blocks in the assi\
503
+ p||o?{}:{reasoningTokens:0},...d||p?{complete:false}:{}},entradaAusente:d,salidaAusente:p}}function bc(t,e){return e?(t??0)+e:t}function ui(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
504
+ function li(t,e){let n=Object.fromEntries(Object.entries(e??{}).filter(([,o])=>o!=null)),r=t?.cache_creation||e?.cache_creation?{...t?.cache_creation??{},...e?.cache_creation??{}}:void 0;return {...t??
505
+ {},...n,...r?{cache_creation:r}:{}}}function di(t){return t==="thinking"||t==="redacted_thinking"}function pi(t){switch(t){case "end_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "\
506
+ tool_calls";case "refusal":return "content_filter";default:return t}}var Xp=new Set([null,"cyber","general_harms"]);function fi(t){if(t.stopReason!=="refusal")return false;let e=t.stopDetails;if(e===null||typeof e!=
507
+ "object"||Array.isArray(e))return false;let n=e;if(n.type!=="refusal"||!("category"in n))return false;let r=n.category;return !(r!==null&&typeof r!="string"||!Xp.has(r)||t.bloques!==0||t.outputTokens!==0||Array.
508
+ isArray(t.iterations)&&t.iterations.length>1)}var yr=4,Qe="bvsala_contract",ef={"sin-ids":'[bvsala] A tool conversation reached the Anthropic adapter without its call ids. To send it the way the Messages API expects (`tool_use` blocks in the assi\
506
509
  stant turn, `tool_result` blocks in the next user turn), each entry of the assistant turn\'s `toolCalls` needs its `id`, and each `role: "tool"` message the `toolCallId` of the call it answers: the sam\
507
510
  e ids that came back in `result.toolCalls`. Without them the exchange is sent as plain text, as in earlier versions: the model reads the results but not its own calls.',"sin-pareja":'[bvsala] A tool e\
508
511
  xchange sent to the Anthropic adapter does not pair up. The Messages API wants one result for every call, right after the assistant turn that made them, and each call\'s `arguments` must be a JSON obje\
@@ -510,38 +513,39 @@ ct. This exchange has a call without its result, a result for a call that turn d
510
513
  . Answer every call of a turn with one `role: "tool"` message carrying its `toolCallId`, before the next user or assistant message.',"no-disponibles":"[bvsala] A tool exchange names a tool this reques\
511
514
  t does not make available to the model: it is missing from `tools` (not passed, or left out by the layer's tool selection), or it is deferred behind tool search and this adapter no longer holds the se\
512
515
  arch that loaded it. The Messages API does not document a `tool_use` block for such a tool as valid, so that exchange is sent as plain text, as in earlier versions. Pass the tool in `tools` on every t\
513
- urn of the conversation to keep the native tool loop."},gc=class{id;opts;fetchImpl;busquedas=new br;constructor(e={}){this.opts=e,this.id=`anthropic:${e.baseUrl??"https://api.anthropic.com/v1"}`,this.
514
- fetchImpl=e.fetchImpl??fetch,tc(this,yr(e.baseUrl)?"oficial":"compatible"),lr(this,ar(e.baseUrl??"https://api.anthropic.com/v1"));let n=this.opts.baseUrl??"https://api.anthropic.com/v1";dr(this,{protocolo:"\
515
- anthropic",origen:tf(n),endpoint:pr(n),cuerpo:r=>this.construirCuerpo(r).body,leer:(r,o)=>this.leerMensaje(r,o,false,false,false,false),solicitar:(r,o)=>{let i=`${n.replace(/\/$/,"")}${fr(r)}`;return this.fetchImpl(
516
+ urn of the conversation to keep the native tool loop."},vc=class{id;opts;fetchImpl;busquedas=new vr;constructor(e={}){this.opts=e,this.id=`anthropic:${e.baseUrl??"https://api.anthropic.com/v1"}`,this.
517
+ fetchImpl=e.fetchImpl??fetch,rc(this,kr(e.baseUrl)?"oficial":"compatible"),dr(this,cr(e.baseUrl??"https://api.anthropic.com/v1"));let n=this.opts.baseUrl??"https://api.anthropic.com/v1";pr(this,{protocolo:"\
518
+ anthropic",origen:cf(n),endpoint:fr(n),cuerpo:r=>this.construirCuerpo(r).body,leer:(r,o)=>this.leerMensaje(r,o,false,false,false,false),solicitar:(r,o)=>{let i=`${n.replace(/\/$/,"")}${mr(r)}`;return this.fetchImpl(
516
519
  i,{method:o.method,headers:{...o.json!==void 0?{"content-type":"application/json"}:{},"anthropic-version":this.opts.apiVersion??"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.
517
- opts.headers},...o.json!==void 0?{body:JSON.stringify(o.json)}:{},...o.signal?{signal:o.signal}:{}})}});}modeloEnElCable(e){return this.opts.stripProviderPrefix??yr(this.opts.baseUrl)?e.replace(/^[^/]+\//,
518
- ""):e}async generate(e,n){let r=this.construirCuerpo(e),o=await this.enviar(r.body,n?.signal);if(!o.ok)throw new Error(`provider ${o.status}: ${await kc(o)}`);return this.leer(o,e,r.contratoNativo,r.turnoAnadido,
519
- r.esquemaPorPrompt,r.reenviadas)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let x=await this.generate(e);x.text!==""&&(yield {type:"text",delta:x.text}),yield {type:"done",response:x};
520
- return}let r=this.construirCuerpo(e),o=r.body;o.stream=true;let i=await this.enviar(o,n.signal);if(!i.ok)throw new Error(`provider ${i.status}: ${await kc(i)}`);if((i.headers.get("content-type")??"").includes(
521
- "application/json")){let x=await this.leer(i,e,r.contratoNativo,r.turnoAnadido,r.esquemaPorPrompt,r.reenviadas);x.text!==""&&(yield {type:"text",delta:x.text}),yield {type:"done",response:x};return}let s=i.
522
- body,a=s&&typeof s.getReader=="function"?s:await i.text(),c="",u=new Map,l,d,p=false,h=false,m,g=false,f,v;for await(let x of mr(a)){let S;try{S=JSON.parse(x.data);}catch{continue}if(S===null||typeof S!="object")
523
- continue;let O=x.event!=="message"?x.event:S.type??x.event;if(O==="message_start")l=S.message?.usage??l,typeof S.message?.id=="string"&&S.message.id!==""&&(f=S.message.id),v=S.message?.diagnostics;else if(O===
524
- "content_block_start"){let R=S.content_block;li(R?.type)&&(g=true),typeof S.index=="number"&&R&&u.set(S.index,{tipo:R.type??"",...typeof R.id=="string"?{id:R.id}:{},...typeof R.name=="string"?{name:R.name}:
525
- {},json:"",...R.content!==void 0?{content:R.content}:{},...e.toolSearch&&(R.type==="server_tool_use"||R.type==="tool_search_tool_result")?{crudo:R}:{}});}else if(O==="content_block_delta"){let R=S.delta;
526
- if(R?.type==="text_delta"&&typeof R.text=="string"&&R.text!=="")c+=R.text,yield {type:"text",delta:R.text};else if(R?.type==="input_json_delta"&&typeof R.partial_json=="string"){let C=typeof S.index=="\
527
- number"?u.get(S.index):void 0;C&&(C.json+=R.partial_json);}}else if(O==="message_delta")p=true,m=S.delta?.stop_reason??m,S.usage&&(d=ui(d,S.usage));else if(O==="message_stop"){h=true;break}else if(O==="err\
528
- or")throw new Error(`provider stream error: ${S.error?.type}: ${S.error?.message}`)}if(!h&&!p)throw new Error("provider stream ended before completion (no message_delta)");let b=ui(l,d),k=(p?ai(b,d?.output_tokens,
529
- g):void 0)?.usage??{inputTokens:0,outputTokens:0,complete:false};if(this.opts.requireUsage&&k.complete===false)throw new Error(yc(p?b.input_tokens:void 0,p?d?.output_tokens:void 0));let T=[...u.entries()].sort(
530
- (x,S)=>x[0]-S[0]).map(([,x])=>x).filter(x=>x.tipo==="tool_use"&&x.name!==Ye).map(x=>({...x.id?{id:x.id}:{},name:x.name??"",arguments:ef(x.json)})).filter(x=>x.name!==""),w=ci(b),P=e.toolSearch?vc([...u.
531
- entries()].sort((x,S)=>x[0]-S[0]).map(([,x])=>({type:x.tipo,name:x.name,content:x.content})),r.reenviadas):void 0;if(e.toolSearch){let x=[];for(let[,S]of [...u.entries()].sort((O,R)=>O[0]-R[0]))if(S.tipo===
532
- "tool_use")x.push({type:"tool_use",id:S.id,name:S.name});else if(S.tipo==="tool_search_tool_result"&&S.crudo)x.push(S.crudo);else if(S.tipo==="server_tool_use"&&S.crudo){let O=S.json===""?S.crudo.input??
533
- {}:Xp(S.json);O!==void 0&&x.push({...S.crudo,input:O});}this.recordarBusquedas(x);}yield {type:"done",response:It({text:c,...T.length>0?{toolCalls:T}:{},...m?{finishReason:di(m)}:{},...w?{servedServiceTier:w}:
534
- {},...P?{toolSearch:P}:{},...f?{providerMessageId:f}:{},...this.diagnosticoDe(e,v),usage:k,structuredNatively:false,raw:{usage:b,stop_reason:m}},fn((r.turnoAnadido?1:0)+Dt(e.tools)))};}async enviar(e,n){let r=(this.
535
- opts.baseUrl??"https://api.anthropic.com/v1").replace(/\/$/,"");return await this.fetchImpl(`${r}/messages`,{method:"POST",headers:{"content-type":"application/json","anthropic-version":this.opts.apiVersion??
536
- "2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},body:JSON.stringify(e),...n?{signal:n}:{}})}construirCuerpo(e){let n=this.reenvioDeBusquedas(e),{system:r,messages:o,
537
- finDelPrefijo:i,prefijoEnSystem:s,turnoAnadido:a}=Gp(e,n?.anteponer,m=>this.avisar(`anthropic-herramientas-${m}`,Kp[m]));if(o.length===0)throw new Error("anthropic: the request has no user/assistant m\
520
+ opts.headers},...o.json!==void 0?{body:JSON.stringify(o.json)}:{},...o.signal?{signal:o.signal}:{}})}});}modeloEnElCable(e){return this.opts.stripProviderPrefix??kr(this.opts.baseUrl)?e.replace(/^[^/]+\//,
521
+ ""):e}async generate(e,n){let r=this.construirCuerpo(e),o=await this.enviar(r.body,n?.signal);if(!o.ok)throw new Error(`provider ${o.status}: ${await wc(o)}`);return this.leer(o,e,r.contratoNativo,r.turnoAnadido,
522
+ r.esquemaPorPrompt,r.reenviadas)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let E=await this.generate(e);E.text!==""&&(yield {type:"text",delta:E.text}),yield {type:"done",response:E};
523
+ return}let r=this.construirCuerpo(e),o=r.body;o.stream=true;let i=await this.enviar(o,n.signal);if(!i.ok)throw new Error(`provider ${i.status}: ${await wc(i)}`);if((i.headers.get("content-type")??"").includes(
524
+ "application/json")){let E=await this.leer(i,e,r.contratoNativo,r.turnoAnadido,r.esquemaPorPrompt,r.reenviadas);E.text!==""&&(yield {type:"text",delta:E.text}),yield {type:"done",response:E};return}let s=i.
525
+ body,a=s&&typeof s.getReader=="function"?s:await i.text(),c="",u=new Map,l,d,p=false,h=false,m,g,f=0,v=false,b,y;for await(let E of hr(a)){let S;try{S=JSON.parse(E.data);}catch{continue}if(S===null||typeof S!="\
526
+ object")continue;let w=E.event!=="message"?E.event:S.type??E.event;if(w==="message_start")l=S.message?.usage??l,typeof S.message?.id=="string"&&S.message.id!==""&&(b=S.message.id),y=S.message?.diagnostics;else if(w===
527
+ "content_block_start"){f+=1;let C=S.content_block;di(C?.type)&&(v=true),typeof S.index=="number"&&C&&u.set(S.index,{tipo:C.type??"",...typeof C.id=="string"?{id:C.id}:{},...typeof C.name=="string"?{name:C.
528
+ name}:{},json:"",...C.content!==void 0?{content:C.content}:{},...e.toolSearch&&(C.type==="server_tool_use"||C.type==="tool_search_tool_result")?{crudo:C}:{}});}else if(w==="content_block_delta"){let C=S.
529
+ delta;if(C?.type==="text_delta"&&typeof C.text=="string"&&C.text!=="")c+=C.text,yield {type:"text",delta:C.text};else if(C?.type==="input_json_delta"&&typeof C.partial_json=="string"){let _=typeof S.index==
530
+ "number"?u.get(S.index):void 0;_&&(_.json+=C.partial_json);}}else if(w==="message_delta")p=true,m=S.delta?.stop_reason??m,S.delta&&"stop_details"in S.delta&&(g=S.delta.stop_details),S.usage&&(d=li(d,S.usage));else if(w===
531
+ "message_stop"){h=true;break}else if(w==="error")throw new Error(`provider stream error: ${S.error?.type}: ${S.error?.message}`)}if(!h&&!p)throw new Error("provider stream ended before completion (no me\
532
+ ssage_delta)");let k=li(l,d),x=(p?ci(k,d?.output_tokens,v):void 0)?.usage??{inputTokens:0,outputTokens:0,complete:false};if(this.opts.requireUsage&&x.complete===false)throw new Error(xc(p?k.input_tokens:void 0,
533
+ p?d?.output_tokens:void 0));let R=[...u.entries()].sort((E,S)=>E[0]-S[0]).map(([,E])=>E).filter(E=>E.tipo==="tool_use"&&E.name!==Qe).map(E=>({...E.id?{id:E.id}:{},name:E.name??"",arguments:af(E.json)})).
534
+ filter(E=>E.name!==""),D=ui(k),I=e.toolSearch?kc([...u.entries()].sort((E,S)=>E[0]-S[0]).map(([,E])=>({type:E.tipo,name:E.name,content:E.content})),r.reenviadas):void 0;if(e.toolSearch){let E=[];for(let[
535
+ ,S]of [...u.entries()].sort((w,C)=>w[0]-C[0]))if(S.tipo==="tool_use")E.push({type:"tool_use",id:S.id,name:S.name});else if(S.tipo==="tool_search_tool_result"&&S.crudo)E.push(S.crudo);else if(S.tipo==="\
536
+ server_tool_use"&&S.crudo){let w=S.json===""?S.crudo.input??{}:sf(S.json);w!==void 0&&E.push({...S.crudo,input:w});}this.recordarBusquedas(E);}yield {type:"done",response:It({text:c,...R.length>0?{toolCalls:R}:
537
+ {},...m?{finishReason:pi(m)}:{},...p&&fi({stopReason:m,stopDetails:g,bloques:f,outputTokens:d?.output_tokens,iterations:k.iterations})?{unbilledRefusal:true}:{},...D?{servedServiceTier:D}:{},...I?{toolSearch:I}:
538
+ {},...b?{providerMessageId:b}:{},...this.diagnosticoDe(e,y),usage:x,structuredNatively:false,raw:{usage:k,stop_reason:m}},mn((r.turnoAnadido?1:0)+Dt(e.tools)))};}async enviar(e,n){let r=(this.opts.baseUrl??
539
+ "https://api.anthropic.com/v1").replace(/\/$/,"");return await this.fetchImpl(`${r}/messages`,{method:"POST",headers:{"content-type":"application/json","anthropic-version":this.opts.apiVersion??"2023-\
540
+ 06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},body:JSON.stringify(e),...n?{signal:n}:{}})}construirCuerpo(e){let n=this.reenvioDeBusquedas(e),{system:r,messages:o,
541
+ finDelPrefijo:i,prefijoEnSystem:s,turnoAnadido:a}=tf(e,n?.anteponer,m=>this.avisar(`anthropic-herramientas-${m}`,ef[m]));if(o.length===0)throw new Error("anthropic: the request has no user/assistant m\
538
542
  essage. The Messages API needs at least one, and system prompts travel in the `system` field \u2014 they do not count.");let c=(e.tools??[]).map(m=>({name:m.id,...m.description?{description:m.description}:
539
- {},input_schema:m.parameters??{type:"object",properties:{}}}));if(e.toolSearch&&c.length>0){let m=new Set(e.toolSearch.alwaysLoaded);for(let g of c)m.has(g.name)||(g.defer_loading=true);c.unshift({...Gn[e.
540
- toolSearch.variant]});}let u=false,l=false,d=false;if(e.schema){let m=c.length>0,g=c.some(v=>v.name===Ye),f=Ze(e.schema);g?(r.push({type:"text",text:pc(e.schema)}),l=true,this.avisar("anthropic-contrato-nombre-oc\
541
- upado",`[bvsala] One of your tools is already named \`${Ye}\`, so the output contract cannot travel as a tool without colliding with it (duplicate tool names are a provider error). The schema is sent a\
543
+ {},input_schema:m.parameters??{type:"object",properties:{}}}));if(e.toolSearch&&c.length>0){let m=new Set(e.toolSearch.alwaysLoaded);for(let g of c)m.has(g.name)||(g.defer_loading=true);c.unshift({...Zn[e.
544
+ toolSearch.variant]});}let u=false,l=false,d=false;if(e.schema){let m=c.length>0,g=c.some(v=>v.name===Qe),f=Ye(e.schema);g?(r.push({type:"text",text:mc(e.schema)}),l=true,this.avisar("anthropic-contrato-nombre-oc\
545
+ upado",`[bvsala] One of your tools is already named \`${Qe}\`, so the output contract cannot travel as a tool without colliding with it (duplicate tool names are a provider error). The schema is sent a\
542
546
  s prompt text instead, which is measurably more expensive on this API. Rename that tool to get the cheaper path.`)):(!f&&!m&&this.avisar("anthropic-strict-incompatible","[bvsala] The response contract\
543
547
  does not meet `strict` mode (in strict, `required` must list ALL the keys in `properties`, and every object needs `additionalProperties: false`). The schema is sent without `strict`: the model is sti\
544
- ll guided and the layer still validates, but the guarantee comes from the layer, not the provider."),u=f&&!m,c.push({name:Ye,description:m?"Return the final answer in the required shape. Use the other\
548
+ ll guided and the layer still validates, but the guarantee comes from the layer, not the provider."),u=f&&!m,c.push({name:Qe,description:m?"Return the final answer in the required shape. Use the other\
545
549
  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,...u?{strict:true}:{}}),m&&(d=this.opts.forceAnswerThroughTool!==
546
550
  false,this.avisar("anthropic-contrato-con-herramientas","[bvsala] This request carries BOTH your tools and an output contract. On Anthropic's Messages API a specific shape is only GUARANTEED by forcing t\
547
551
  hat exact tool, and forcing ours would leave the model unable to call yours. The contract travels as one extra tool"+(d?' and the request is sent with `tool_choice: {type: "any"}`, so the model must a\
@@ -549,63 +553,64 @@ nswer through SOME tool \u2014 yours or the contract \u2014 and can no longer re
549
553
  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, not the provider's (`constrai\
550
554
  nts.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 overhead.")+" Dropping either t\
551
555
  he tools or the contract from this request is what makes the guarantee free.")));}let p={model:this.modeloEnElCable(e.model),max_tokens:e.maxOutputTokens??this.opts.defaultMaxOutputTokens??4096,messages:o};
552
- r.length>0&&(p.system=r),e.temperature!=null&&(p.temperature=e.temperature),c.length>0&&(p.tools=c),u?p.tool_choice={type:"tool",name:Ye}:d&&(p.tool_choice={type:"any"}),e.deferrable===true&&this.avisar(
556
+ r.length>0&&(p.system=r),e.temperature!=null&&(p.temperature=e.temperature),c.length>0&&(p.tools=c),u?p.tool_choice={type:"tool",name:Qe}:d&&(p.tool_choice={type:"any"}),e.deferrable===true&&this.avisar(
553
557
  "anthropic-sin-tier-diferible","[bvsala] This request was declared deferrable, but the Anthropic Messages API has NO cheaper synchronous tier: its `service_tier` chooses between priority capacity (mor\
554
558
  e 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, which is asynchronous and does not fi\
555
- t a request/response call: send such requests with layer.batches.submit() instead.");let h=this.marcarCache(e,r,o,i,s);return e.cacheDiagnostics&&yr(this.opts.baseUrl)&&(p.diagnostics={previous_message_id:e.
556
- cacheDiagnostics.previousMessageId}),this.opts.automaticCache===true&&e.cachePlacement==null&&e.stablePrefixMessages!=null&&h<Math.min(this.opts.maxCacheBreakpoints??vr,vr)&&(p.cache_control={type:"ephe\
557
- meral"}),{body:p,contratoNativo:u,turnoAnadido:a,esquemaPorPrompt:l,reenviadas:n}}reenvioDeBusquedas(e){if(!e.toolSearch||!e.tools||e.tools.length===0)return;let n=new Set(e.tools.map(a=>a.id)),r=Gn[e.
559
+ t a request/response call: send such requests with layer.batches.submit() instead.");let h=this.marcarCache(e,r,o,i,s);return e.cacheDiagnostics&&kr(this.opts.baseUrl)&&(p.diagnostics={previous_message_id:e.
560
+ cacheDiagnostics.previousMessageId}),this.opts.automaticCache===true&&e.cachePlacement==null&&e.stablePrefixMessages!=null&&h<Math.min(this.opts.maxCacheBreakpoints??yr,yr)&&(p.cache_control={type:"ephe\
561
+ meral"}),{body:p,contratoNativo:u,turnoAnadido:a,esquemaPorPrompt:l,reenviadas:n}}reenvioDeBusquedas(e){if(!e.toolSearch||!e.tools||e.tools.length===0)return;let n=new Set(e.tools.map(a=>a.id)),r=Zn[e.
558
562
  toolSearch.variant].name,o=new Set,i=this.busquedas,s={resultados:0,herramientas:[],anteponer(a){let c=(a.toolCalls??[]).map(d=>d.id).filter(d=>typeof d=="string"&&d!=="");if(c.length===0)return;let u=i.
559
563
  para(c);if(!u)return;let l=[];for(let d of u)if(!(d.busqueda!==r||o.has(d.id))&&d.herramientas.every(p=>n.has(p))){o.add(d.id),l.push(d.uso,d.resultado),s.resultados+=1;for(let p of d.herramientas)s.herramientas.
560
- includes(p)||s.herramientas.push(p);}return l.length>0?l:void 0}};return s}recordarBusquedas(e){let n=e.filter(r=>r.type==="tool_use"&&r.name!==Ye).map(r=>r.id).filter(r=>typeof r=="string"&&r!=="");n.
561
- length!==0&&this.busquedas.recordar(n,fc(e));}avisar(e,n){_t(this,e,n);}marcarCache(e,n,r,o,i){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return 0;let s=Math.min(this.opts.maxCacheBreakpoints??
562
- vr,vr);if(s<=0)return 0;let a=s,c=()=>e.cachePlacement?.ttl==="1h"?{type:"ephemeral",ttl:"1h"}:{type:"ephemeral"},u=i>0?n[i-1]:void 0;u&&(u.cache_control=c(),s-=1);let l=r[r.length-1],d=l?.content[l.content.
564
+ includes(p)||s.herramientas.push(p);}return l.length>0?l:void 0}};return s}recordarBusquedas(e){let n=e.filter(r=>r.type==="tool_use"&&r.name!==Qe).map(r=>r.id).filter(r=>typeof r=="string"&&r!=="");n.
565
+ length!==0&&this.busquedas.recordar(n,hc(e));}avisar(e,n){_t(this,e,n);}marcarCache(e,n,r,o,i){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return 0;let s=Math.min(this.opts.maxCacheBreakpoints??
566
+ yr,yr);if(s<=0)return 0;let a=s,c=()=>e.cachePlacement?.ttl==="1h"?{type:"ephemeral",ttl:"1h"}:{type:"ephemeral"},u=i>0?n[i-1]:void 0;u&&(u.cache_control=c(),s-=1);let l=r[r.length-1],d=l?.content[l.content.
563
567
  length-1];if(e.cachePlacement?.tail===true&&s>0&&d&&(d.cache_control=c(),s-=1),s>0&&o){let p=r[o.mensaje]?.content[o.bloque];p&&p.cache_control==null&&(p.cache_control=c(),s-=1);}return a-s}async leer(e,n,r,o,i,s){
564
- let a=await e.json();return this.leerMensaje(a,n,r,o,i,this.opts.requireUsage===true,s)}diagnosticoDe(e,n){if(e.cacheDiagnostics?.previousMessageId==null||!yr(this.opts.baseUrl))return {};if(n===void 0)return {};
568
+ let a=await e.json();return this.leerMensaje(a,n,r,o,i,this.opts.requireUsage===true,s)}diagnosticoDe(e,n){if(e.cacheDiagnostics?.previousMessageId==null||!kr(this.opts.baseUrl))return {};if(n===void 0)return {};
565
569
  if(n===null)return {cacheDiagnostics:{missReason:"none"}};if(typeof n!="object")return {};let r=n.cache_miss_reason;if(r===null)return {cacheDiagnostics:{missReason:"pending"}};if(r===void 0||typeof r!="\
566
570
  object")return {};let o=r.type,i=r.cache_missed_input_tokens;return typeof o!="string"||o===""?{}:{cacheDiagnostics:{missReason:o,...typeof i=="number"&&Number.isFinite(i)&&i>=0?{missedInputTokens:i}:{}}}}leerMensaje(e,n,r,o,i,s,a){
567
- let c=e.content??[],u=c.some(k=>li(k.type)),l=c.filter(k=>k.type==="text").map(k=>k.text??"").join(""),d=c.filter(k=>k.type==="tool_use"&&k.name!==Ye).map(k=>({...k.id?{id:k.id}:{},name:k.name??"",arguments:JSON.
568
- stringify(k.input??{})})).filter(k=>k.name!==""),p=c.find(k=>k.type==="tool_use"&&k.name===Ye),h=p?JSON.stringify(p.input??{}):l,m=e.usage,{usage:g,entradaAusente:f,salidaAusente:v}=ai(m,m?.output_tokens,
569
- u);if(s&&(f||v))throw new Error(yc(m?.input_tokens,m?.output_tokens));let b=ci(m),y=n.toolSearch?vc(c,a):void 0;return n.toolSearch&&this.recordarBusquedas(c),It({text:h,...d.length>0?{toolCalls:d}:{},
570
- ...e.stop_reason?{finishReason:di(e.stop_reason)}:{},...b?{servedServiceTier:b}:{},usage:g,structuredNatively:n.schema!=null&&r,...y?{toolSearch:y}:{},...typeof e.id=="string"&&e.id!==""?{providerMessageId:e.
571
- id}:{},...this.diagnosticoDe(n,e.diagnostics),raw:e},{...fn((o?1:0)+Dt(n.tools)),esquemaPorPrompt:i})}};function Gp(t,e,n){let r=[],o=[],i=t.stablePrefixMessages??0,s,a=0,c=true,u=Qp(t),l=new Set,d=t.messages,
572
- p=g=>{if(g>=i)return;let f=o.length-1;s={mensaje:f,bloque:o[f].content.length-1};},h=(g,f)=>{g.content!==""&&(o.push({role:g.role==="assistant"?"assistant":"user",content:[{type:"text",text:g.content}]}),
573
- p(f));};for(let g=0;g<d.length;g++){let f=d[g];if(f.role==="system"&&c){r.push({type:"text",text:f.content}),g<i&&(a=r.length);continue}if(c=false,f.role!=="assistant"){f.role==="tool"&&n(f.toolCallId?"si\
574
- n-pareja":"sin-ids"),h(f,g);continue}let v=e?e(f):void 0;v&&u.cargar(v);let b=f.content!==""?[{type:"text",text:f.content}]:[],y=f.toolCalls??[],k=g+1;if(y.length>0){for(;k<d.length&&d[k].role==="tool";)
575
- k+=1;let w=Zp(y,d.slice(g+1,k),u,l);if("llamadas"in w){o.push({role:"assistant",content:[...v??[],...b,...w.llamadas]}),p(g);let P={role:"user",content:[]};o.push(P),w.resultados.forEach((x,S)=>{P.content.
576
- push(x),p(g+1+S);}),g=k-1;continue}n(w.motivo);}let T=v?[...v,...b]:b;T.length>0&&(o.push({role:"assistant",content:T}),p(g));for(let w=g+1;w<k;w++)h(d[w],w);g=k-1;}let m=false;return o.length>0&&o[0].role===
577
- "assistant"&&(o.unshift({role:"user",content:[{type:"text",text:"(continue)"}]}),s&&(s={mensaje:s.mensaje+1,bloque:s.bloque}),m=true),{system:r,messages:o,finDelPrefijo:s,prefijoEnSystem:a,turnoAnadido:m}}
578
- function Zp(t,e,n,r){if(t.some(c=>!c.id)||e.some(c=>!c.toolCallId))return {motivo:"sin-ids"};let o=t.map(c=>bc(c.id)),i=new Set(o);if(i.size!==o.length||o.some(c=>r.has(c)))return {motivo:"sin-pareja"};
579
- let s=e.map(c=>bc(c.toolCallId));if(s.length!==o.length||new Set(s).size!==s.length||s.some(c=>!i.has(c)))return {motivo:"sin-pareja"};let a=t.map(c=>Yp(c.arguments));if(a.some(c=>c===void 0))return {motivo:"\
580
- sin-pareja"};if(t.some(c=>!n.tiene(c.name)))return {motivo:"no-disponibles"};for(let c of o)r.add(c);return {llamadas:t.map((c,u)=>({type:"tool_use",id:o[u],name:c.name,input:a[u]})),resultados:e.map((c,u)=>({
581
- type:"tool_result",tool_use_id:s[u],...c.content!==""?{content:c.content}:{},...c.isError===true?{is_error:true}:{}}))}}function bc(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}function Yp(t){let e=n=>typeof n==
582
- "object"&&n!==null&&!Array.isArray(n);if(e(t))return t;if(typeof t=="string"){if(t.trim()==="")return {};try{let n=JSON.parse(t);return e(n)?n:void 0}catch{return}}}function Qp(t){let e=new Set((t.tools??
583
- []).map(r=>r.id));if(!t.toolSearch)return {tiene:r=>e.has(r),cargar:()=>{}};let n=new Set(t.toolSearch.alwaysLoaded.filter(r=>e.has(r)));return {tiene:r=>n.has(r),cargar(r){for(let o of r){if(o.type!=="\
584
- tool_search_tool_result")continue;let i=o.content?.tool_references;if(Array.isArray(i))for(let s of i)typeof s?.tool_name=="string"&&e.has(s.tool_name)&&n.add(s.tool_name);}}}}function yr(t){try{return /(^|\.)api\.anthropic\.com$/i.
585
- test(new URL(t??"https://api.anthropic.com/v1").hostname)}catch{return false}}function vc(t,e){let n=0,r=0,o=[];for(let i of t)if(i.type==="server_tool_use"&&typeof i.name=="string"&&i.name.startsWith("to\
586
- ol_search_tool"))n+=1;else if(i.type==="tool_search_tool_result"){let s=i.content;if(s&&s.type==="tool_search_tool_result_error")r+=1;else if(s&&Array.isArray(s.tool_references))for(let a of s.tool_references)
587
- typeof a?.tool_name=="string"&&!o.includes(a.tool_name)&&o.push(a.tool_name);}return {searches:n,loaded:o,errors:r,...e&&e.resultados>0?{resent:{results:e.resultados,tools:[...e.herramientas]}}:{}}}function Xp(t){
588
- try{return JSON.parse(t)}catch{return}}function ef(t){try{return JSON.stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function yc(t,e){return `provider returned incomplete usage (input=${t??"absen\
589
- t"}, output=${e??"absent"}); cannot measure cost.`}async function kc(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function tf(t){return pn(t)==="anthropic"?"anthropic":null}var mn=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.
590
- now()-this.start}all(){return this.events}};var Qe=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function pi(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function kr(t,e=""){if(typeof t!="number"){let n=e&&
591
- `"${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 Se(t,e,n=""){
592
- let r=pi(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`,u=s+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(u):
593
- new TypeError(u)}return t}function fi(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 wc(t,e){Se(t,void 0,"digestInt\
594
- o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function hn(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function xr(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Sc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",nf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function wr(t){if(Se(t),Sc)return t.toHex();
595
- let e="";for(let n=0;n<t.length;n++)e+=nf[t[n]];return e}var je={_0:48,_9:57,A:65,F:70,a:97,f:102};function xc(t){if(t>=je._0&&t<=je._9)return t-je._0;if(t>=je.A&&t<=je.F)return t-(je.A-10);if(t>=je.a&&
596
- t<=je.f)return t-(je.a-10)}function gn(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Sc)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?
597
- new RangeError(o.message):o}let e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=xc(t.charCodeAt(
598
- i)),a=xc(t.charCodeAt(i+1));if(s===void 0||a===void 0){let c=t[i]+t[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a;}return r}function mi(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];Se(o),e+=o.length;}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let i=t[r];n.set(i,o),o+=i.length;}return n}function Tc(t,e={}){let n=(o,i)=>t(i).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function Cc(t=32){
599
- kr(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(
600
- `"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var Ec=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var Sr=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=
601
- new Uint8Array(e),this.view=xr(this.buffer);}update(e){fi(this),Se(e);let{view:n,buffer:r,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=xr(e);for(;o<=i-s;s+=
602
- o)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){fi(this),
603
- wc(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,hn(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let d=s;d<o;d++)n[d]=0;r.setBigUint64(
604
- o-8,BigInt(this.length*8),i),this.process(r,0);let a=xr(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\
571
+ let c=e.content??[],u=c.some(k=>di(k.type)),l=c.filter(k=>k.type==="text").map(k=>k.text??"").join(""),d=c.filter(k=>k.type==="tool_use"&&k.name!==Qe).map(k=>({...k.id?{id:k.id}:{},name:k.name??"",arguments:JSON.
572
+ stringify(k.input??{})})).filter(k=>k.name!==""),p=c.find(k=>k.type==="tool_use"&&k.name===Qe),h=p?JSON.stringify(p.input??{}):l,m=e.usage,{usage:g,entradaAusente:f,salidaAusente:v}=ci(m,m?.output_tokens,
573
+ u);if(s&&(f||v))throw new Error(xc(m?.input_tokens,m?.output_tokens));let b=ui(m),y=n.toolSearch?kc(c,a):void 0;return n.toolSearch&&this.recordarBusquedas(c),It({text:h,...d.length>0?{toolCalls:d}:{},
574
+ ...e.stop_reason?{finishReason:pi(e.stop_reason)}:{},...fi({stopReason:e.stop_reason,stopDetails:e.stop_details,bloques:Array.isArray(e.content)?e.content.length:0,outputTokens:m?.output_tokens,iterations:m?.
575
+ iterations})?{unbilledRefusal:true}:{},...b?{servedServiceTier:b}:{},usage:g,structuredNatively:n.schema!=null&&r,...y?{toolSearch:y}:{},...typeof e.id=="string"&&e.id!==""?{providerMessageId:e.id}:{},...this.
576
+ diagnosticoDe(n,e.diagnostics),raw:e},{...mn((o?1:0)+Dt(n.tools)),esquemaPorPrompt:i})}};function tf(t,e,n){let r=[],o=[],i=t.stablePrefixMessages??0,s,a=0,c=true,u=of(t),l=new Set,d=t.messages,p=g=>{if(g>=
577
+ i)return;let f=o.length-1;s={mensaje:f,bloque:o[f].content.length-1};},h=(g,f)=>{g.content!==""&&(o.push({role:g.role==="assistant"?"assistant":"user",content:[{type:"text",text:g.content}]}),p(f));};for(let g=0;g<
578
+ d.length;g++){let f=d[g];if(f.role==="system"&&c){r.push({type:"text",text:f.content}),g<i&&(a=r.length);continue}if(c=false,f.role!=="assistant"){f.role==="tool"&&n(f.toolCallId?"sin-pareja":"sin-ids"),
579
+ h(f,g);continue}let v=e?e(f):void 0;v&&u.cargar(v);let b=f.content!==""?[{type:"text",text:f.content}]:[],y=f.toolCalls??[],k=g+1;if(y.length>0){for(;k<d.length&&d[k].role==="tool";)k+=1;let x=nf(y,d.
580
+ slice(g+1,k),u,l);if("llamadas"in x){o.push({role:"assistant",content:[...v??[],...b,...x.llamadas]}),p(g);let R={role:"user",content:[]};o.push(R),x.resultados.forEach((D,I)=>{R.content.push(D),p(g+1+
581
+ I);}),g=k-1;continue}n(x.motivo);}let T=v?[...v,...b]:b;T.length>0&&(o.push({role:"assistant",content:T}),p(g));for(let x=g+1;x<k;x++)h(d[x],x);g=k-1;}let m=false;return o.length>0&&o[0].role==="assistant"&&
582
+ (o.unshift({role:"user",content:[{type:"text",text:"(continue)"}]}),s&&(s={mensaje:s.mensaje+1,bloque:s.bloque}),m=true),{system:r,messages:o,finDelPrefijo:s,prefijoEnSystem:a,turnoAnadido:m}}function nf(t,e,n,r){
583
+ if(t.some(c=>!c.id)||e.some(c=>!c.toolCallId))return {motivo:"sin-ids"};let o=t.map(c=>yc(c.id)),i=new Set(o);if(i.size!==o.length||o.some(c=>r.has(c)))return {motivo:"sin-pareja"};let s=e.map(c=>yc(c.toolCallId));
584
+ if(s.length!==o.length||new Set(s).size!==s.length||s.some(c=>!i.has(c)))return {motivo:"sin-pareja"};let a=t.map(c=>rf(c.arguments));if(a.some(c=>c===void 0))return {motivo:"sin-pareja"};if(t.some(c=>!n.
585
+ tiene(c.name)))return {motivo:"no-disponibles"};for(let c of o)r.add(c);return {llamadas:t.map((c,u)=>({type:"tool_use",id:o[u],name:c.name,input:a[u]})),resultados:e.map((c,u)=>({type:"tool_result",tool_use_id:s[u],
586
+ ...c.content!==""?{content:c.content}:{},...c.isError===true?{is_error:true}:{}}))}}function yc(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}function rf(t){let e=n=>typeof n=="object"&&n!==null&&!Array.isArray(
587
+ n);if(e(t))return t;if(typeof t=="string"){if(t.trim()==="")return {};try{let n=JSON.parse(t);return e(n)?n:void 0}catch{return}}}function of(t){let e=new Set((t.tools??[]).map(r=>r.id));if(!t.toolSearch)
588
+ return {tiene:r=>e.has(r),cargar:()=>{}};let n=new Set(t.toolSearch.alwaysLoaded.filter(r=>e.has(r)));return {tiene:r=>n.has(r),cargar(r){for(let o of r){if(o.type!=="tool_search_tool_result")continue;let i=o.
589
+ content?.tool_references;if(Array.isArray(i))for(let s of i)typeof s?.tool_name=="string"&&e.has(s.tool_name)&&n.add(s.tool_name);}}}}function kr(t){try{return /(^|\.)api\.anthropic\.com$/i.test(new URL(
590
+ t??"https://api.anthropic.com/v1").hostname)}catch{return false}}function kc(t,e){let n=0,r=0,o=[];for(let i of t)if(i.type==="server_tool_use"&&typeof i.name=="string"&&i.name.startsWith("tool_search_too\
591
+ l"))n+=1;else if(i.type==="tool_search_tool_result"){let s=i.content;if(s&&s.type==="tool_search_tool_result_error")r+=1;else if(s&&Array.isArray(s.tool_references))for(let a of s.tool_references)typeof a?.
592
+ tool_name=="string"&&!o.includes(a.tool_name)&&o.push(a.tool_name);}return {searches:n,loaded:o,errors:r,...e&&e.resultados>0?{resent:{results:e.resultados,tools:[...e.herramientas]}}:{}}}function sf(t){
593
+ try{return JSON.parse(t)}catch{return}}function af(t){try{return JSON.stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function xc(t,e){return `provider returned incomplete usage (input=${t??"absen\
594
+ t"}, output=${e??"absent"}); cannot measure cost.`}async function wc(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function cf(t){return fn(t)==="anthropic"?"anthropic":null}var hn=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.
595
+ now()-this.start}all(){return this.events}};var Xe=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function mi(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function xr(t,e=""){if(typeof t!="number"){let n=e&&
596
+ `"${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 Ce(t,e,n=""){
597
+ let r=mi(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`,u=s+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(u):
598
+ new TypeError(u)}return t}function hi(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 Tc(t,e){Ce(t,void 0,"digestInt\
599
+ o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function gn(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function wr(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Cc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",uf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Sr(t){if(Ce(t),Cc)return t.toHex();
600
+ let e="";for(let n=0;n<t.length;n++)e+=uf[t[n]];return e}var $e={_0:48,_9:57,A:65,F:70,a:97,f:102};function Sc(t){if(t>=$e._0&&t<=$e._9)return t-$e._0;if(t>=$e.A&&t<=$e.F)return t-($e.A-10);if(t>=$e.a&&
601
+ t<=$e.f)return t-($e.a-10)}function bn(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Cc)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?
602
+ new RangeError(o.message):o}let e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=Sc(t.charCodeAt(
603
+ i)),a=Sc(t.charCodeAt(i+1));if(s===void 0||a===void 0){let c=t[i]+t[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a;}return r}function gi(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];Ce(o),e+=o.length;}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let i=t[r];n.set(i,o),o+=i.length;}return n}function Ec(t,e={}){let n=(o,i)=>t(i).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function Pc(t=32){
604
+ xr(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(
605
+ `"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var Rc=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var Tr=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=
606
+ new Uint8Array(e),this.view=wr(this.buffer);}update(e){hi(this),Ce(e);let{view:n,buffer:r,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=wr(e);for(;o<=i-s;s+=
607
+ o)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){hi(this),
608
+ Tc(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,gn(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let d=s;d<o;d++)n[d]=0;r.setBigUint64(
609
+ o-8,BigInt(this.length*8),i),this.process(r,0);let a=wr(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\
605
610
  ha2: outputLen bigger than state");for(let d=0;d<u;d++)a.setUint32(4*d,l[d],i);}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||=new this.
606
- constructor,e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};var ne=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Tr=BigInt(4294967295),Pc=BigInt(32);function rf(t,e=false){return e?{h:Number(t&Tr),l:Number(t>>Pc&Tr)}:{h:Number(t>>Pc&Tr)|0,l:Number(t&Tr)|0}}function Rc(t,e=false){let n=t.length,r=new Uint32Array(n),
607
- o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=rf(t[i],e);[r[i],o[i]]=[s,a];}return [r,o]}var hi=(t,e,n)=>t>>>n,gi=(t,e,n)=>t<<32-n|e>>>n,pt=(t,e,n)=>t>>>n|e<<32-n,ft=(t,e,n)=>t<<32-n|e>>>n,bn=(t,e,n)=>t<<64-n|e>>>n-32,vn=(t,e,n)=>t>>>n-32|e<<64-n;function Ie(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var Dc=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Ic=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,_c=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Ac=(t,e,n,r,o)=>e+
608
- n+r+o+(t/2**32|0)|0,Oc=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Mc=(t,e,n,r,o,i)=>e+n+r+o+i+(t/2**32|0)|0;var Lc=Rc(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
611
+ constructor,e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};var ne=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Cr=BigInt(4294967295),Dc=BigInt(32);function lf(t,e=false){return e?{h:Number(t&Cr),l:Number(t>>Dc&Cr)}:{h:Number(t>>Dc&Cr)|0,l:Number(t&Cr)|0}}function Ic(t,e=false){let n=t.length,r=new Uint32Array(n),
612
+ o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=lf(t[i],e);[r[i],o[i]]=[s,a];}return [r,o]}var bi=(t,e,n)=>t>>>n,vi=(t,e,n)=>t<<32-n|e>>>n,ft=(t,e,n)=>t>>>n|e<<32-n,mt=(t,e,n)=>t<<32-n|e>>>n,vn=(t,e,n)=>t<<64-n|e>>>n-32,yn=(t,e,n)=>t>>>n-32|e<<64-n;function Ae(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var _c=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Ac=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Oc=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Mc=(t,e,n,r,o)=>e+
613
+ n+r+o+(t/2**32|0)|0,Lc=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),jc=(t,e,n,r,o,i)=>e+n+r+o+i+(t/2**32|0)|0;var Nc=Ic(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
609
614
  "0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
610
615
  8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
611
616
  0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
@@ -613,158 +618,158 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
613
618
  x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
614
619
  efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
615
620
  eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
616
- 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),sf=Lc[0],af=Lc[1],Xe=new Uint32Array(80),et=new Uint32Array(80),bi=class extends Sr{constructor(e){
621
+ 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),pf=Nc[0],ff=Nc[1],et=new Uint32Array(80),tt=new Uint32Array(80),yi=class extends Tr{constructor(e){
617
622
  super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:u,El:l,Fh:d,Fl:p,Gh:h,Gl:m,Hh:g,Hl:f}=this;return [e,n,r,o,i,s,a,c,u,l,d,p,h,m,g,f]}set(e,n,r,o,i,s,a,c,u,l,d,p,h,m,g,f){this.Ah=
618
623
  e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=d|0,this.Fl=p|0,this.Gh=h|0,this.Gl=m|0,this.Hh=g|0,this.Hl=f|0;}process(e,n){for(let y=0;y<
619
- 16;y++,n+=4)Xe[y]=e.getUint32(n),et[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){let k=Xe[y-15]|0,T=et[y-15]|0,w=pt(k,T,1)^pt(k,T,8)^hi(k,T,7),P=ft(k,T,1)^ft(k,T,8)^gi(k,T,7),x=Xe[y-2]|0,S=et[y-2]|0,O=pt(
620
- x,S,19)^bn(x,S,61)^hi(x,S,6),R=ft(x,S,19)^vn(x,S,61)^gi(x,S,6),C=_c(P,R,et[y-7],et[y-16]),I=Ac(C,w,O,Xe[y-7],Xe[y-16]);Xe[y]=I|0,et[y]=C|0;}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:u,Dl:l,Eh:d,El:p,Fh:h,Fl:m,
621
- Gh:g,Gl:f,Hh:v,Hl:b}=this;for(let y=0;y<80;y++){let k=pt(d,p,14)^pt(d,p,18)^bn(d,p,41),T=ft(d,p,14)^ft(d,p,18)^vn(d,p,41),w=d&h^~d&g,P=p&m^~p&f,x=Oc(b,T,P,af[y],et[y]),S=Mc(x,v,k,w,sf[y],Xe[y]),O=x|0,
622
- R=pt(r,o,28)^bn(r,o,34)^bn(r,o,39),C=ft(r,o,28)^vn(r,o,34)^vn(r,o,39),I=r&i^r&a^i&a,D=o&s^o&c^s&c;v=g|0,b=f|0,g=h|0,f=m|0,h=d|0,m=p|0,{h:d,l:p}=Ie(u|0,l|0,S|0,O|0),u=a|0,l=c|0,a=i|0,c=s|0,i=r|0,s=o|0;
623
- let A=Dc(O,C,D);r=Ic(A,S,R,I),o=A|0;}(({h:r,l:o}=Ie(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=Ie(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Ie(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Ie(this.Dh|0,this.Dl|0,u|0,l|
624
- 0),{h:d,l:p}=Ie(this.Eh|0,this.El|0,d|0,p|0),{h,l:m}=Ie(this.Fh|0,this.Fl|0,h|0,m|0),{h:g,l:f}=Ie(this.Gh|0,this.Gl|0,g|0,f|0),{h:v,l:b}=Ie(this.Hh|0,this.Hl|0,v|0,b|0),this.set(r,o,i,s,a,c,u,l,d,p,h,
625
- m,g,f,v,b);}roundClean(){hn(Xe,et);}destroy(){this.destroyed=true,hn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},vi=class extends bi{Ah=ne[0]|0;Al=ne[1]|0;Bh=ne[2]|0;Bl=ne[3]|0;Ch=ne[4]|0;Cl=ne[5]|
626
- 0;Dh=ne[6]|0;Dl=ne[7]|0;Eh=ne[8]|0;El=ne[9]|0;Fh=ne[10]|0;Fl=ne[11]|0;Gh=ne[12]|0;Gl=ne[13]|0;Hh=ne[14]|0;Hl=ne[15]|0;constructor(){super(64);}};var Cr=Tc(()=>new vi,Ec(3));var K=(t,e,n)=>Se(t,e,n),ki=kr,xi=wr,_e=(...t)=>mi(...t),jc=t=>gn(t),Rr=pi,Nc=t=>Cc(t),Pr=BigInt(0),yi=BigInt(1);function Ot(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"e\
627
- xpected boolean, got type="+typeof t)}return t}function cf(t){if(typeof t=="bigint"){if(!Er(t))throw new RangeError("positive bigint expected, got "+t)}else ki(t);return t}function Ne(t,e=""){if(typeof t!=
628
- "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 $c(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Pr:BigInt("0x"+t)}function wi(t){return $c(wr(t))}function $e(t){return $c(wr(yn(Se(t)).reverse()))}
629
- function Si(t,e){if(kr(e),e===0)throw new RangeError("zero length");t=cf(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return gn(n.padStart(e*2,"0"))}function Bc(t,e){
630
- return Si(t,e).reverse()}function Fc(t,e){if(t=K(t),e=K(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 yn(t){return Uint8Array.from(K(t))}var Er=t=>typeof t=="bigint"&&Pr<=t;function uf(t,e,n){return Er(t)&&Er(e)&&Er(n)&&e<=t&&t<n}function Ti(t,e,n,r){if(!uf(e,n,r))throw new RangeError(
631
- "expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Ci(t){if(t<Pr)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>Pr;t>>=yi,e+=1);return e}var zc=t=>(yi<<BigInt(t))-yi;function mt(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function r(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(t,i))throw new TypeError(
624
+ 16;y++,n+=4)et[y]=e.getUint32(n),tt[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){let k=et[y-15]|0,T=tt[y-15]|0,x=ft(k,T,1)^ft(k,T,8)^bi(k,T,7),R=mt(k,T,1)^mt(k,T,8)^vi(k,T,7),D=et[y-2]|0,I=tt[y-2]|0,E=ft(
625
+ D,I,19)^vn(D,I,61)^bi(D,I,6),S=mt(D,I,19)^yn(D,I,61)^vi(D,I,6),w=Oc(R,S,tt[y-7],tt[y-16]),C=Mc(w,x,E,et[y-7],et[y-16]);et[y]=C|0,tt[y]=w|0;}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:u,Dl:l,Eh:d,El:p,Fh:h,Fl:m,
626
+ Gh:g,Gl:f,Hh:v,Hl:b}=this;for(let y=0;y<80;y++){let k=ft(d,p,14)^ft(d,p,18)^vn(d,p,41),T=mt(d,p,14)^mt(d,p,18)^yn(d,p,41),x=d&h^~d&g,R=p&m^~p&f,D=Lc(b,T,R,ff[y],tt[y]),I=jc(D,v,k,x,pf[y],et[y]),E=D|0,
627
+ S=ft(r,o,28)^vn(r,o,34)^vn(r,o,39),w=mt(r,o,28)^yn(r,o,34)^yn(r,o,39),C=r&i^r&a^i&a,_=o&s^o&c^s&c;v=g|0,b=f|0,g=h|0,f=m|0,h=d|0,m=p|0,{h:d,l:p}=Ae(u|0,l|0,I|0,E|0),u=a|0,l=c|0,a=i|0,c=s|0,i=r|0,s=o|0;
628
+ let O=_c(E,w,_);r=Ac(O,I,S,C),o=O|0;}(({h:r,l:o}=Ae(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=Ae(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Ae(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Ae(this.Dh|0,this.Dl|0,u|0,l|
629
+ 0),{h:d,l:p}=Ae(this.Eh|0,this.El|0,d|0,p|0),{h,l:m}=Ae(this.Fh|0,this.Fl|0,h|0,m|0),{h:g,l:f}=Ae(this.Gh|0,this.Gl|0,g|0,f|0),{h:v,l:b}=Ae(this.Hh|0,this.Hl|0,v|0,b|0),this.set(r,o,i,s,a,c,u,l,d,p,h,
630
+ m,g,f,v,b);}roundClean(){gn(et,tt);}destroy(){this.destroyed=true,gn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},ki=class extends yi{Ah=ne[0]|0;Al=ne[1]|0;Bh=ne[2]|0;Bl=ne[3]|0;Ch=ne[4]|0;Cl=ne[5]|
631
+ 0;Dh=ne[6]|0;Dl=ne[7]|0;Eh=ne[8]|0;El=ne[9]|0;Fh=ne[10]|0;Fl=ne[11]|0;Gh=ne[12]|0;Gl=ne[13]|0;Hh=ne[14]|0;Hl=ne[15]|0;constructor(){super(64);}};var Er=Ec(()=>new ki,Rc(3));var K=(t,e,n)=>Ce(t,e,n),wi=xr,Si=Sr,Oe=(...t)=>gi(...t),$c=t=>bn(t),Dr=mi,Bc=t=>Pc(t),Rr=BigInt(0),xi=BigInt(1);function Ot(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"e\
632
+ xpected boolean, got type="+typeof t)}return t}function mf(t){if(typeof t=="bigint"){if(!Pr(t))throw new RangeError("positive bigint expected, got "+t)}else wi(t);return t}function Be(t,e=""){if(typeof t!=
633
+ "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 Fc(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Rr:BigInt("0x"+t)}function Ti(t){return Fc(Sr(t))}function Fe(t){return Fc(Sr(kn(Ce(t)).reverse()))}
634
+ function Ci(t,e){if(xr(e),e===0)throw new RangeError("zero length");t=mf(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return bn(n.padStart(e*2,"0"))}function zc(t,e){
635
+ return Ci(t,e).reverse()}function qc(t,e){if(t=K(t),e=K(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 kn(t){return Uint8Array.from(K(t))}var Pr=t=>typeof t=="bigint"&&Rr<=t;function hf(t,e,n){return Pr(t)&&Pr(e)&&Pr(n)&&e<=t&&t<n}function Ei(t,e,n,r){if(!hf(e,n,r))throw new RangeError(
636
+ "expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Pi(t){if(t<Rr)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>Rr;t>>=xi,e+=1);return e}var Vc=t=>(xi<<BigInt(t))-xi;function ht(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function r(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(t,i))throw new TypeError(
632
637
  `param "${i}" is invalid: expected own property`);let c=t[i];if(a&&c===void 0)return;let u=typeof c;if(u!==s||c===null)throw new TypeError(`param "${i}" is invalid: expected ${s}, got ${u}`)}let o=(i,s)=>Object.
633
- entries(i).forEach(([a,c])=>r(a,c,s));o(e,false),o(n,true);}var Ei=()=>{throw new Error("not implemented")};var re=BigInt(0),Q=BigInt(1),ht=BigInt(2),Hc=BigInt(3),Wc=BigInt(4),Jc=BigInt(5),lf=BigInt(7),Kc=BigInt(8),df=BigInt(9),Gc=BigInt(16);function W(t,e){if(e<=re)throw new Error("mod: expected positive m\
634
- odulus, got "+e);let n=t%e;return n>=re?n:e+n}function Te(t,e,n){if(e<re)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >re;)r*=r,r%=n;return r}function qc(t,e){if(t===re)throw new Error("invert: expected non-zer\
638
+ entries(i).forEach(([a,c])=>r(a,c,s));o(e,false),o(n,true);}var Ri=()=>{throw new Error("not implemented")};var re=BigInt(0),Q=BigInt(1),gt=BigInt(2),Jc=BigInt(3),Kc=BigInt(4),Gc=BigInt(5),gf=BigInt(7),Zc=BigInt(8),bf=BigInt(9),Yc=BigInt(16);function W(t,e){if(e<=re)throw new Error("mod: expected positive m\
639
+ odulus, got "+e);let n=t%e;return n>=re?n:e+n}function Ee(t,e,n){if(e<re)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >re;)r*=r,r%=n;return r}function Uc(t,e){if(t===re)throw new Error("invert: expected non-zer\
635
640
  o number");if(e<=re)throw new Error("invert: expected positive modulus, got "+e);let n=W(t,e),r=e,o=re,s=Q;for(;n!==re;){let u=r/n,l=r-n*u,d=o-s*u;r=n,n=l,o=s,s=d;}if(r!==Q)throw new Error(
636
- "invert: does not exist");return W(o,e)}function Pi(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function Zc(t,e){let n=t,r=(n.ORDER+Q)/Wc,o=n.pow(e,r);return Pi(n,o,
637
- e),o}function pf(t,e){let n=t,r=(n.ORDER-Jc)/Kc,o=n.mul(e,ht),i=n.pow(o,r),s=n.mul(e,i),a=n.mul(n.mul(s,ht),i),c=n.mul(s,n.sub(a,n.ONE));return Pi(n,c,e),c}function ff(t){let e=Ar(t),n=Yc(t),r=n(e,e.neg(
638
- e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+lf)/Gc;return((a,c)=>{let u=a,l=u.pow(c,s),d=u.mul(l,r),p=u.mul(l,o),h=u.mul(l,i),m=u.eql(u.sqr(d),c),g=u.eql(u.sqr(p),c);l=u.cmov(l,d,m),d=u.cmov(h,p,g);let f=u.
639
- eql(u.sqr(d),c),v=u.cmov(l,d,f);return Pi(u,v,c),v})}function Yc(t){if(t<Hc)throw new Error("sqrt is not defined for small field");let e=t-Q,n=0;for(;e%ht===re;)e/=ht,n++;let r=ht,o=Ar(t);for(;Vc(o,r)===
640
- 1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Zc;let i=o.pow(r,e),s=(e+Q)/ht;return function(c,u){let l=c;if(l.is0(u))return u;if(Vc(l,u)!==1)throw new Error(
641
+ "invert: does not exist");return W(o,e)}function Di(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function Qc(t,e){let n=t,r=(n.ORDER+Q)/Kc,o=n.pow(e,r);return Di(n,o,
642
+ e),o}function vf(t,e){let n=t,r=(n.ORDER-Gc)/Zc,o=n.mul(e,gt),i=n.pow(o,r),s=n.mul(e,i),a=n.mul(n.mul(s,gt),i),c=n.mul(s,n.sub(a,n.ONE));return Di(n,c,e),c}function yf(t){let e=Or(t),n=Xc(t),r=n(e,e.neg(
643
+ e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+gf)/Yc;return((a,c)=>{let u=a,l=u.pow(c,s),d=u.mul(l,r),p=u.mul(l,o),h=u.mul(l,i),m=u.eql(u.sqr(d),c),g=u.eql(u.sqr(p),c);l=u.cmov(l,d,m),d=u.cmov(h,p,g);let f=u.
644
+ eql(u.sqr(d),c),v=u.cmov(l,d,f);return Di(u,v,c),v})}function Xc(t){if(t<Jc)throw new Error("sqrt is not defined for small field");let e=t-Q,n=0;for(;e%gt===re;)e/=gt,n++;let r=gt,o=Or(t);for(;Hc(o,r)===
645
+ 1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Qc;let i=o.pow(r,e),s=(e+Q)/gt;return function(c,u){let l=c;if(l.is0(u))return u;if(Hc(l,u)!==1)throw new Error(
641
646
  "Cannot find square root");let d=n,p=l.mul(l.ONE,i),h=l.pow(u,e),m=l.pow(u,s);for(;!l.eql(h,l.ONE);){if(l.is0(h))return l.ZERO;let g=1,f=l.sqr(h);for(;!l.eql(f,l.ONE);)if(g++,f=l.sqr(f),g===d)throw new Error(
642
- "Cannot find square root");let v=Q<<BigInt(d-g-1),b=l.pow(p,v);d=g,p=l.sqr(b),h=l.mul(h,p),m=l.mul(m,b);}return m}}function mf(t){return t%Wc===Hc?Zc:t%Kc===Jc?pf:t%Gc===df?ff(t):Yc(t)}var Be=(t,e)=>(W(
643
- t,e)&Q)===Q,hf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Qc(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=hf.
644
- reduce((r,o)=>(r[o]="function",r),e);if(mt(t,n),Ne(t.BYTES,"BYTES"),Ne(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\
645
- id field: expected ORDER > 1, got "+t.ORDER);return t}function gf(t,e,n){let r=t;if(n<re)throw new Error("invalid exponent, negatives unsupported");if(n===re)return r.ONE;if(n===Q)return e;let o=r.ONE,
646
- i=e;for(;n>re;)n&Q&&(o=r.mul(o,i)),i=r.sqr(i),n>>=Q;return o}function _r(t,e,n=false){let r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),i=e.reduce((a,c,u)=>r.is0(c)?a:(o[u]=a,r.mul(a,c)),r.ONE),s=r.inv(
647
- i);return e.reduceRight((a,c,u)=>r.is0(c)?a:(o[u]=r.mul(a,o[u]),r.mul(a,c)),s),o}function Vc(t,e){let n=t,r=(n.ORDER-Q)/ht,o=n.pow(e,r),i=n.eql(o,n.ONE),s=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function bf(t,e){if(e!==void 0&&ki(e),t<=re)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);
648
- let n=Ci(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 Uc=new WeakMap,
649
- Ir=class{ORDER;BITS;BYTES;isLE;ZERO=re;ONE=Q;_lengths;_mod;constructor(e,n={}){if(e<=Q)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
647
+ "Cannot find square root");let v=Q<<BigInt(d-g-1),b=l.pow(p,v);d=g,p=l.sqr(b),h=l.mul(h,p),m=l.mul(m,b);}return m}}function kf(t){return t%Kc===Jc?Qc:t%Zc===Gc?vf:t%Yc===bf?yf(t):Xc(t)}var ze=(t,e)=>(W(
648
+ t,e)&Q)===Q,xf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function eu(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=xf.
649
+ reduce((r,o)=>(r[o]="function",r),e);if(ht(t,n),Be(t.BYTES,"BYTES"),Be(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\
650
+ id field: expected ORDER > 1, got "+t.ORDER);return t}function wf(t,e,n){let r=t;if(n<re)throw new Error("invalid exponent, negatives unsupported");if(n===re)return r.ONE;if(n===Q)return e;let o=r.ONE,
651
+ i=e;for(;n>re;)n&Q&&(o=r.mul(o,i)),i=r.sqr(i),n>>=Q;return o}function Ar(t,e,n=false){let r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),i=e.reduce((a,c,u)=>r.is0(c)?a:(o[u]=a,r.mul(a,c)),r.ONE),s=r.inv(
652
+ i);return e.reduceRight((a,c,u)=>r.is0(c)?a:(o[u]=r.mul(a,o[u]),r.mul(a,c)),s),o}function Hc(t,e){let n=t,r=(n.ORDER-Q)/gt,o=n.pow(e,r),i=n.eql(o,n.ONE),s=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Sf(t,e){if(e!==void 0&&wi(e),t<=re)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);
653
+ let n=Pi(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 Wc=new WeakMap,
654
+ _r=class{ORDER;BITS;BYTES;isLE;ZERO=re;ONE=Q;_lengths;_mod;constructor(e,n={}){if(e<=Q)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
650
655
  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.
651
- freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=bf(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
656
+ freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=Sf(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
652
657
  048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,Object.freeze(this);}create(e){return W(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got\
653
658
  "+typeof e);return re<=e&&e<this.ORDER}is0(e){return e===re}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&Q)===Q}neg(e){return W(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return W(
654
- e*e,this.ORDER)}add(e,n){return W(e+n,this.ORDER)}sub(e,n){return W(e-n,this.ORDER)}mul(e,n){return W(e*n,this.ORDER)}pow(e,n){return gf(this,e,n)}div(e,n){return W(e*qc(n,this.ORDER),this.ORDER)}sqrN(e){
655
- return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return qc(e,this.ORDER)}sqrt(e){let n=Uc.get(this);return n||Uc.set(this,n=mf(this.ORDER)),n(this,e)}toBytes(e){return this.
656
- isLE?Bc(e,this.BYTES):Si(e,this.BYTES)}fromBytes(e,n=false){K(e);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes\
657
- : expected "+r+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,i?0:u.length-e.length),e=u;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?$e(e):
658
- wi(e);if(a&&(c=W(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return _r(this,e)}cmov(e,n,r){return Ot(r,"condition"),r?n:e}};Object.
659
- freeze(Ir.prototype);function Ar(t,e={}){return new Ir(t,e)}var Or=BigInt(0),_i=BigInt(1);function Xc(t,e){let n=e.negate();return t?n:e}function Lr(t,e){let n=_r(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function ru(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
660
- throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ri(t,e){ru(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=zc(t),s=BigInt(t);return {windows:n,windowSize:r,mask:i,maxNumber:o,
661
- shiftBy:s}}function eu(t,e,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(t&o),c=t>>s;a>r&&(a-=i,c+=_i);let u=e*r,l=u+Math.abs(a)-1,d=a===0,p=a<0,h=e%2!==0;return {nextN:c,offset:l,isZero:d,
662
- isNeg:p,isNegF:h,offsetF:u}}var Di=new WeakMap,ou=new WeakMap;function Ii(t){return ou.get(t)||1}function tu(t){if(t!==Or)throw new Error("invalid wNAF")}var Mr=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
663
- e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>Or;)n&_i&&(r=r.add(o)),o=o.double(),n>>=_i;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Ri(n,this.bits),i=[],
659
+ e*e,this.ORDER)}add(e,n){return W(e+n,this.ORDER)}sub(e,n){return W(e-n,this.ORDER)}mul(e,n){return W(e*n,this.ORDER)}pow(e,n){return wf(this,e,n)}div(e,n){return W(e*Uc(n,this.ORDER),this.ORDER)}sqrN(e){
660
+ return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Uc(e,this.ORDER)}sqrt(e){let n=Wc.get(this);return n||Wc.set(this,n=kf(this.ORDER)),n(this,e)}toBytes(e){return this.
661
+ isLE?zc(e,this.BYTES):Ci(e,this.BYTES)}fromBytes(e,n=false){K(e);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes\
662
+ : expected "+r+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,i?0:u.length-e.length),e=u;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?Fe(e):
663
+ Ti(e);if(a&&(c=W(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Ar(this,e)}cmov(e,n,r){return Ot(r,"condition"),r?n:e}};Object.
664
+ freeze(_r.prototype);function Or(t,e={}){return new _r(t,e)}var Mr=BigInt(0),Oi=BigInt(1);function tu(t,e){let n=e.negate();return t?n:e}function jr(t,e){let n=Ar(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function iu(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
665
+ throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ii(t,e){iu(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=Vc(t),s=BigInt(t);return {windows:n,windowSize:r,mask:i,maxNumber:o,
666
+ shiftBy:s}}function nu(t,e,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(t&o),c=t>>s;a>r&&(a-=i,c+=Oi);let u=e*r,l=u+Math.abs(a)-1,d=a===0,p=a<0,h=e%2!==0;return {nextN:c,offset:l,isZero:d,
667
+ isNeg:p,isNegF:h,offsetF:u}}var _i=new WeakMap,su=new WeakMap;function Ai(t){return su.get(t)||1}function ru(t){if(t!==Mr)throw new Error("invalid wNAF")}var Lr=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
668
+ e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>Mr;)n&Oi&&(r=r.add(o)),o=o.double(),n>>=Oi;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Ii(n,this.bits),i=[],
664
669
  s=e,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let u=1;u<o;u++)a=a.add(s),i.push(a);s=a.double();}return i}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,
665
- s=Ri(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:p,offsetF:h}=eu(r,a,s);r=c,l?i=i.add(Xc(p,n[h])):o=o.add(Xc(d,n[u]));}return tu(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.
666
- ZERO){let i=Ri(e,this.bits);for(let s=0;s<i.windows&&r!==Or;s++){let{nextN:a,offset:c,isZero:u,isNeg:l}=eu(r,s,i);if(r=a,!u){let d=n[c];o=o.add(l?d.negate():d);}}return tu(r),o}getPrecomputes(e,n,r){let o=Di.
667
- get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Di.set(n,o))),o}cached(e,n,r){let o=Ii(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Ii(
668
- e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){ru(n,this.bits),ou.set(e,n),Di.delete(e);}hasCache(e){return Ii(e)!==1}};function nu(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Qc(e),e}else return Ar(t,{isLE:n})}function iu(t,e,n={},r){if(r===void 0&&(r=t==="edwar\
669
- 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>Or))throw new Error(`CURVE.${c} must be positive bigint`)}
670
- let o=nu(e.p,n.Fp,r),i=nu(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.
671
- freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function su(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var tt=BigInt(0),X=BigInt(1),Ai=BigInt(2),vf=BigInt(8);function yf(t,e,n,r){let o=t.sqr(n),i=t.sqr(r),s=t.add(t.mul(e.a,o),i),a=t.add(t.ONE,t.mul(e.d,t.mul(o,i)));return t.eql(s,a)}function au(t,e={}){
672
- let n=e,r=iu("edwards",t,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;mt(n,{},{uvRatio:"function"});let c=Ai<<BigInt(i.BYTES*8)-X,u=g=>o.create(g),l=n.uvRatio===void 0?(g,f)=>{try{return {isValid:!0,value:o.
673
- sqrt(o.div(g,f))}}catch{return {isValid:false,value:tt}}}:n.uvRatio;if(!yf(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(g,f,v=false){let b=v?X:tt;return Ti("coordinate "+g,f,
674
- b,c),f}function p(g){if(!(g instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,X,u(s.Gx*s.Gy));static ZERO=new h(tt,X,X,tt);static Fp=o;static Fn=i;X;Y;Z;T;constructor(f,v,b,y){
670
+ s=Ii(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:p,offsetF:h}=nu(r,a,s);r=c,l?i=i.add(tu(p,n[h])):o=o.add(tu(d,n[u]));}return ru(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.
671
+ ZERO){let i=Ii(e,this.bits);for(let s=0;s<i.windows&&r!==Mr;s++){let{nextN:a,offset:c,isZero:u,isNeg:l}=nu(r,s,i);if(r=a,!u){let d=n[c];o=o.add(l?d.negate():d);}}return ru(r),o}getPrecomputes(e,n,r){let o=_i.
672
+ get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),_i.set(n,o))),o}cached(e,n,r){let o=Ai(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Ai(
673
+ e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){iu(n,this.bits),su.set(e,n),_i.delete(e);}hasCache(e){return Ai(e)!==1}};function ou(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return eu(e),e}else return Or(t,{isLE:n})}function au(t,e,n={},r){if(r===void 0&&(r=t==="edwar\
674
+ 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>Mr))throw new Error(`CURVE.${c} must be positive bigint`)}
675
+ let o=ou(e.p,n.Fp,r),i=ou(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.
676
+ freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function cu(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var nt=BigInt(0),X=BigInt(1),Mi=BigInt(2),Tf=BigInt(8);function Cf(t,e,n,r){let o=t.sqr(n),i=t.sqr(r),s=t.add(t.mul(e.a,o),i),a=t.add(t.ONE,t.mul(e.d,t.mul(o,i)));return t.eql(s,a)}function uu(t,e={}){
677
+ let n=e,r=au("edwards",t,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;ht(n,{},{uvRatio:"function"});let c=Mi<<BigInt(i.BYTES*8)-X,u=g=>o.create(g),l=n.uvRatio===void 0?(g,f)=>{try{return {isValid:!0,value:o.
678
+ sqrt(o.div(g,f))}}catch{return {isValid:false,value:nt}}}:n.uvRatio;if(!Cf(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(g,f,v=false){let b=v?X:nt;return Ei("coordinate "+g,f,
679
+ b,c),f}function p(g){if(!(g instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,X,u(s.Gx*s.Gy));static ZERO=new h(nt,X,X,nt);static Fp=o;static Fn=i;X;Y;Z;T;constructor(f,v,b,y){
675
680
  this.X=d("x",f),this.Y=d("y",v),this.Z=d("z",b,true),this.T=d("t",y),Object.freeze(this);}static CURVE(){return s}static fromAffine(f){if(f instanceof h)throw new Error("extended point not allowed");let{
676
- x:v,y:b}=f||{};return d("x",v),d("y",b),new h(v,b,X,u(v*b))}static fromBytes(f,v=false){let b=o.BYTES,{a:y,d:k}=s;f=yn(K(f,b,"point")),Ot(v,"zip215");let T=yn(f),w=f[b-1];T[b-1]=w&-129;let P=$e(T),x=v?c:
677
- o.ORDER;Ti("point.y",P,tt,x);let S=u(P*P),O=u(S-X),R=u(k*S-y),{isValid:C,value:I}=l(O,R);if(!C)throw new Error("bad point: invalid y coordinate");let D=(I&X)===X,A=(w&128)!==0;if(!v&&I===tt&&A)throw new Error(
678
- "bad point: x=0 and x_0=1");return A!==D&&(I=u(-I)),h.fromAffine({x:I,y:P})}static fromHex(f,v=false){return h.fromBytes(jc(f),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(f=8,v=true){
679
- return m.createCache(this,f),v||this.multiply(Ai),this}assertValidity(){let f=this,{a:v,d:b}=s;if(f.is0())throw new Error("bad point: ZERO");let{X:y,Y:k,Z:T,T:w}=f,P=u(y*y),x=u(k*k),S=u(T*T),O=u(S*S),
680
- R=u(P*v),C=u(S*u(R+x)),I=u(O+u(b*u(P*x)));if(C!==I)throw new Error("bad point: equation left != right (1)");let D=u(y*k),A=u(T*w);if(D!==A)throw new Error("bad point: equation left != right (2)")}equals(f){
681
- p(f);let{X:v,Y:b,Z:y}=this,{X:k,Y:T,Z:w}=f,P=u(v*w),x=u(k*y),S=u(b*w),O=u(T*y);return P===x&&S===O}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){
682
- let{a:f}=s,{X:v,Y:b,Z:y}=this,k=u(v*v),T=u(b*b),w=u(Ai*u(y*y)),P=u(f*k),x=v+b,S=u(u(x*x)-k-T),O=P+T,R=O-w,C=P-T,I=u(S*R),D=u(O*C),A=u(S*C),j=u(R*O);return new h(I,D,j,A)}add(f){p(f);let{a:v,d:b}=s,{X:y,
683
- Y:k,Z:T,T:w}=this,{X:P,Y:x,Z:S,T:O}=f,R=u(y*P),C=u(k*x),I=u(w*b*O),D=u(T*S),A=u((y+k)*(P+x)-R-C),j=D-I,B=D+I,V=u(C-v*R),z=u(A*j),ee=u(B*V),L=u(A*V),se=u(j*B);return new h(z,ee,se,L)}subtract(f){return p(
684
- f),this.add(f.negate())}multiply(f){if(!i.isValidNot0(f))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:b}=m.cached(this,f,y=>Lr(h,y));return Lr(h,[v,b])[0]}multiplyUnsafe(f){
685
- if(!i.isValid(f))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return f===tt?h.ZERO:this.is0()||f===X?this:m.unsafe(this,f,v=>Lr(h,v))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){
686
- return m.unsafe(this,s.n).is0()}toAffine(f){let v=this,b=f,{X:y,Y:k,Z:T}=v,w=v.is0();b==null&&(b=w?vf:o.inv(T));let P=u(y*b),x=u(k*b),S=o.mul(T,b);if(w)return {x:tt,y:X};if(S!==X)throw new Error("invZ \
687
- was invalid");return {x:P,y:x}}clearCofactor(){return a===X?this:this.multiplyUnsafe(a)}toBytes(){let{x:f,y:v}=this.toAffine(),b=o.toBytes(v);return b[b.length-1]|=f&X?128:0,b}toHex(){return xi(this.toBytes())}toString(){
688
- return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=new Mr(h,i.BITS);return i.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var jr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){
689
- this.ep=e;}static fromBytes(e){Ei();}static fromHex(e){Ei();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){
690
- return this.ep.toAffine(e)}toHex(){return xi(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){
681
+ x:v,y:b}=f||{};return d("x",v),d("y",b),new h(v,b,X,u(v*b))}static fromBytes(f,v=false){let b=o.BYTES,{a:y,d:k}=s;f=kn(K(f,b,"point")),Ot(v,"zip215");let T=kn(f),x=f[b-1];T[b-1]=x&-129;let R=Fe(T),D=v?c:
682
+ o.ORDER;Ei("point.y",R,nt,D);let I=u(R*R),E=u(I-X),S=u(k*I-y),{isValid:w,value:C}=l(E,S);if(!w)throw new Error("bad point: invalid y coordinate");let _=(C&X)===X,O=(x&128)!==0;if(!v&&C===nt&&O)throw new Error(
683
+ "bad point: x=0 and x_0=1");return O!==_&&(C=u(-C)),h.fromAffine({x:C,y:R})}static fromHex(f,v=false){return h.fromBytes($c(f),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(f=8,v=true){
684
+ return m.createCache(this,f),v||this.multiply(Mi),this}assertValidity(){let f=this,{a:v,d:b}=s;if(f.is0())throw new Error("bad point: ZERO");let{X:y,Y:k,Z:T,T:x}=f,R=u(y*y),D=u(k*k),I=u(T*T),E=u(I*I),
685
+ S=u(R*v),w=u(I*u(S+D)),C=u(E+u(b*u(R*D)));if(w!==C)throw new Error("bad point: equation left != right (1)");let _=u(y*k),O=u(T*x);if(_!==O)throw new Error("bad point: equation left != right (2)")}equals(f){
686
+ p(f);let{X:v,Y:b,Z:y}=this,{X:k,Y:T,Z:x}=f,R=u(v*x),D=u(k*y),I=u(b*x),E=u(T*y);return R===D&&I===E}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){
687
+ let{a:f}=s,{X:v,Y:b,Z:y}=this,k=u(v*v),T=u(b*b),x=u(Mi*u(y*y)),R=u(f*k),D=v+b,I=u(u(D*D)-k-T),E=R+T,S=E-x,w=R-T,C=u(I*S),_=u(E*w),O=u(I*w),j=u(S*E);return new h(C,_,j,O)}add(f){p(f);let{a:v,d:b}=s,{X:y,
688
+ Y:k,Z:T,T:x}=this,{X:R,Y:D,Z:I,T:E}=f,S=u(y*R),w=u(k*D),C=u(x*b*E),_=u(T*I),O=u((y+k)*(R+D)-S-w),j=_-C,B=_+C,V=u(w-v*S),z=u(O*j),ee=u(B*V),L=u(O*V),se=u(j*B);return new h(z,ee,se,L)}subtract(f){return p(
689
+ f),this.add(f.negate())}multiply(f){if(!i.isValidNot0(f))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:b}=m.cached(this,f,y=>jr(h,y));return jr(h,[v,b])[0]}multiplyUnsafe(f){
690
+ if(!i.isValid(f))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return f===nt?h.ZERO:this.is0()||f===X?this:m.unsafe(this,f,v=>jr(h,v))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){
691
+ return m.unsafe(this,s.n).is0()}toAffine(f){let v=this,b=f,{X:y,Y:k,Z:T}=v,x=v.is0();b==null&&(b=x?Tf:o.inv(T));let R=u(y*b),D=u(k*b),I=o.mul(T,b);if(x)return {x:nt,y:X};if(I!==X)throw new Error("invZ \
692
+ was invalid");return {x:R,y:D}}clearCofactor(){return a===X?this:this.multiplyUnsafe(a)}toBytes(){let{x:f,y:v}=this.toAffine(),b=o.toBytes(v);return b[b.length-1]|=f&X?128:0,b}toHex(){return Si(this.toBytes())}toString(){
693
+ return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=new Lr(h,i.BITS);return i.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var Nr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){
694
+ this.ep=e;}static fromBytes(e){Ri();}static fromHex(e){Ri();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){
695
+ return this.ep.toAffine(e)}toHex(){return Si(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){
691
696
  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.
692
- ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function cu(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is r\
693
- equired');let r=e,o=n;mt(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=t,u=r.
694
- outputLen,l=2*a.BYTES;if(u!==void 0&&(Ne(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let d=o.randomBytes===void 0?Nc:o.randomBytes,p=o.adjustScalarBytes===void 0?
695
- C=>C:o.adjustScalarBytes,h=o.domain===void 0?(C,I,D)=>{if(Ot(D,"phflag"),I.length||D)throw new Error("Contexts/pre-hash are not supported");return C}:o.domain;function m(C){return c.create($e(C))}function g(C){
696
- let I=P.secretKey;K(C,P.secretKey,"secretKey");let D=K(r(C),2*I,"hashedSecretKey"),A=p(D.slice(0,I)),j=D.slice(I,2*I),B=m(A);return {head:A,prefix:j,scalar:B}}function f(C){let{head:I,prefix:D,scalar:A}=g(
697
- C),j=s.multiply(A),B=j.toBytes();return {head:I,prefix:D,scalar:A,point:j,pointBytes:B}}function v(C){return f(C).pointBytes}function b(C=Uint8Array.of(),...I){let D=_e(...I);return m(r(h(D,K(C,void 0,
698
- "context"),!!i)))}function y(C,I,D={}){C=K(C,void 0,"message"),i&&(C=i(C));let{prefix:A,scalar:j,pointBytes:B}=f(I),V=b(D.context,A,C),z=s.multiply(V).toBytes(),ee=b(D.context,z,B,C),L=c.create(V+ee*j);
699
- if(!c.isValid(L))throw new Error("sign failed: invalid s");let se=_e(z,c.toBytes(L));return K(se,P.signature,"result")}let k={zip215:o.zip215};function T(C,I,D,A=k){let{context:j}=A,B=A.zip215===void 0?
700
- !!k.zip215:A.zip215,V=P.signature;C=K(C,V,"signature"),I=K(I,void 0,"message"),D=K(D,P.publicKey,"publicKey"),B!==void 0&&Ot(B,"zip215"),i&&(I=i(I));let z=V/2,ee=C.subarray(0,z),L=$e(C.subarray(z,V)),
701
- se,ae,G;try{se=t.fromBytes(D,B),ae=t.fromBytes(ee,B),G=s.multiplyUnsafe(L);}catch{return false}if(!B&&se.isSmallOrder())return false;let Wt=b(j,ee,D,I);return ae.add(se.multiplyUnsafe(Wt)).subtract(G).clearCofactor().
702
- is0()}let w=a.BYTES,P={secretKey:w,publicKey:w,signature:2*w,seed:w};function x(C){return C=C===void 0?d(P.seed):C,K(C,P.seed,"seed")}function S(C){return Rr(C)&&C.length===P.secretKey}function O(C,I){
703
- try{return !!t.fromBytes(C,I===void 0?k.zip215:I)}catch{return false}}let R={getExtendedPublicKey:f,randomSecretKey:x,isValidSecretKey:S,isValidPublicKey:O,toMontgomery(C){let{y:I}=t.fromBytes(C),D=P.publicKey,
704
- A=D===32;if(!A&&D!==57)throw new Error("only defined for 25519 and 448");let j=A?a.div(X+I,X-I):a.div(I-X,I+X);return a.toBytes(j)},toMontgomerySecret(C){let I=P.secretKey;K(C,I);let D=r(C.subarray(0,
705
- I));return p(D).subarray(0,I)}};return Object.freeze(P),Object.freeze(R),Object.freeze({keygen:su(x,v),getPublicKey:v,sign:y,verify:T,utils:R,Point:t,lengths:P})}var wf=BigInt(0),Fe=BigInt(1),lu=BigInt(2);var Sf=BigInt(5),Tf=BigInt(8),Mt=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ni={p:Mt,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Tf,
697
+ ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function lu(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is r\
698
+ equired');let r=e,o=n;ht(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=t,u=r.
699
+ outputLen,l=2*a.BYTES;if(u!==void 0&&(Be(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let d=o.randomBytes===void 0?Bc:o.randomBytes,p=o.adjustScalarBytes===void 0?
700
+ w=>w:o.adjustScalarBytes,h=o.domain===void 0?(w,C,_)=>{if(Ot(_,"phflag"),C.length||_)throw new Error("Contexts/pre-hash are not supported");return w}:o.domain;function m(w){return c.create(Fe(w))}function g(w){
701
+ let C=R.secretKey;K(w,R.secretKey,"secretKey");let _=K(r(w),2*C,"hashedSecretKey"),O=p(_.slice(0,C)),j=_.slice(C,2*C),B=m(O);return {head:O,prefix:j,scalar:B}}function f(w){let{head:C,prefix:_,scalar:O}=g(
702
+ w),j=s.multiply(O),B=j.toBytes();return {head:C,prefix:_,scalar:O,point:j,pointBytes:B}}function v(w){return f(w).pointBytes}function b(w=Uint8Array.of(),...C){let _=Oe(...C);return m(r(h(_,K(w,void 0,
703
+ "context"),!!i)))}function y(w,C,_={}){w=K(w,void 0,"message"),i&&(w=i(w));let{prefix:O,scalar:j,pointBytes:B}=f(C),V=b(_.context,O,w),z=s.multiply(V).toBytes(),ee=b(_.context,z,B,w),L=c.create(V+ee*j);
704
+ if(!c.isValid(L))throw new Error("sign failed: invalid s");let se=Oe(z,c.toBytes(L));return K(se,R.signature,"result")}let k={zip215:o.zip215};function T(w,C,_,O=k){let{context:j}=O,B=O.zip215===void 0?
705
+ !!k.zip215:O.zip215,V=R.signature;w=K(w,V,"signature"),C=K(C,void 0,"message"),_=K(_,R.publicKey,"publicKey"),B!==void 0&&Ot(B,"zip215"),i&&(C=i(C));let z=V/2,ee=w.subarray(0,z),L=Fe(w.subarray(z,V)),
706
+ se,ae,G;try{se=t.fromBytes(_,B),ae=t.fromBytes(ee,B),G=s.multiplyUnsafe(L);}catch{return false}if(!B&&se.isSmallOrder())return false;let Wt=b(j,ee,_,C);return ae.add(se.multiplyUnsafe(Wt)).subtract(G).clearCofactor().
707
+ is0()}let x=a.BYTES,R={secretKey:x,publicKey:x,signature:2*x,seed:x};function D(w){return w=w===void 0?d(R.seed):w,K(w,R.seed,"seed")}function I(w){return Dr(w)&&w.length===R.secretKey}function E(w,C){
708
+ try{return !!t.fromBytes(w,C===void 0?k.zip215:C)}catch{return false}}let S={getExtendedPublicKey:f,randomSecretKey:D,isValidSecretKey:I,isValidPublicKey:E,toMontgomery(w){let{y:C}=t.fromBytes(w),_=R.publicKey,
709
+ O=_===32;if(!O&&_!==57)throw new Error("only defined for 25519 and 448");let j=O?a.div(X+C,X-C):a.div(C-X,C+X);return a.toBytes(j)},toMontgomerySecret(w){let C=R.secretKey;K(w,C);let _=r(w.subarray(0,
710
+ C));return p(_).subarray(0,C)}};return Object.freeze(R),Object.freeze(S),Object.freeze({keygen:cu(D,v),getPublicKey:v,sign:y,verify:T,utils:S,Point:t,lengths:R})}var Rf=BigInt(0),qe=BigInt(1),pu=BigInt(2);var Df=BigInt(5),If=BigInt(8),Mt=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Bi={p:Mt,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:If,
706
711
  a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
707
- c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Cf(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Mt,a=t*t%
708
- i*t%i,c=Te(a,lu,i)*a%i,u=Te(c,Fe,i)*t%i,l=Te(u,Sf,i)*u%i,d=Te(l,e,i)*l%i,p=Te(d,n,i)*d%i,h=Te(p,r,i)*p%i,m=Te(h,o,i)*h%i,g=Te(m,o,i)*h%i,f=Te(g,e,i)*l%i;return {pow_p_5_8:Te(f,lu,i)*t%i,b2:a}}function Ef(t){
709
- return t[0]&=248,t[31]&=127,t[31]|=64,t}var Mi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function $i(t,e){let n=Mt,r=W(e*e*e,n),o=W(r*r*e,n),i=Cf(t*o).pow_p_5_8,
710
- s=W(t*r*i,n),a=W(e*s*s,n),c=s,u=W(s*Mi,n),l=a===t,d=a===W(-t,n),p=a===W(-t*Mi,n);return l&&(s=c),(d||p)&&(s=u),Be(s,n)&&(s=W(-s,n)),{isValid:l||d,value:s}}var rt=au(Ni,{uvRatio:$i}),nt=rt.Fp,fu=rt.Fn;function Pf(t){return cu(rt,Cr,Object.assign({adjustScalarBytes:Ef,zip215:true},t))}var mu=Pf({});var Li=Mi;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Df=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
711
- "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var du=t=>$i(Fe,t),Af=BigInt("0x7\
712
- fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),ji=t=>nt.create($e(t)&Af);var ot=class t extends jr{static BASE=new t(
713
- rt.BASE);static ZERO=new t(rt.ZERO);static Fp=nt;static Fn=fu;constructor(e){super(e);}static fromAffine(e){return new t(rt.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoP\
714
- oint expected")}init(e){return new t(e)}static fromBytes(e){Se(e,32);let{a:n,d:r}=Ni,o=Mt,i=k=>nt.create(k),s=ji(e);if(!Fc(nt.toBytes(s),e)||Be(s,o))throw new Error("invalid ristretto255 encoding 1");
715
- let a=i(s*s),c=i(Fe+n*a),u=i(Fe-n*a),l=i(c*c),d=i(u*u),p=i(n*r*l-d),{isValid:h,value:m}=du(i(p*d)),g=i(m*u),f=i(m*g*p),v=i((s+s)*g);Be(v,o)&&(v=i(-v));let b=i(c*f),y=i(v*b);if(!h||Be(y,o)||b===wf)throw new Error(
716
- "invalid ristretto255 encoding 2");return new t(new rt(v,b,Fe,y))}static fromHex(e){return t.fromBytes(gn(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,i=Mt,s=f=>nt.create(f),a=s(s(r+n)*s(r-n)),c=s(e*n),
717
- u=s(c*c),{value:l}=du(s(a*u)),d=s(l*a),p=s(l*c),h=s(d*p*o),m;if(Be(o*h,i)){let f=s(n*Li),v=s(e*Li);e=f,n=v,m=s(d*Df);}else m=p;Be(e*h,i)&&(n=s(-n));let g=s((r-n)*m);return Be(g,i)&&(g=s(-g)),nt.toBytes(
718
- g)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:i}=e.ep,s=u=>nt.create(u),a=s(n*i)===s(r*o),c=s(r*i)===s(n*o);return a||c}is0(){return this.equals(t.ZERO)}};Object.freeze(ot.BASE);Object.freeze(
719
- ot.ZERO);Object.freeze(ot.prototype);Object.freeze(ot);var hu=`-----BEGIN PUBLIC KEY-----
712
+ c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function _f(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Mt,a=t*t%
713
+ i*t%i,c=Ee(a,pu,i)*a%i,u=Ee(c,qe,i)*t%i,l=Ee(u,Df,i)*u%i,d=Ee(l,e,i)*l%i,p=Ee(d,n,i)*d%i,h=Ee(p,r,i)*p%i,m=Ee(h,o,i)*h%i,g=Ee(m,o,i)*h%i,f=Ee(g,e,i)*l%i;return {pow_p_5_8:Ee(f,pu,i)*t%i,b2:a}}function Af(t){
714
+ return t[0]&=248,t[31]&=127,t[31]|=64,t}var ji=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Fi(t,e){let n=Mt,r=W(e*e*e,n),o=W(r*r*e,n),i=_f(t*o).pow_p_5_8,
715
+ s=W(t*r*i,n),a=W(e*s*s,n),c=s,u=W(s*ji,n),l=a===t,d=a===W(-t,n),p=a===W(-t*ji,n);return l&&(s=c),(d||p)&&(s=u),ze(s,n)&&(s=W(-s,n)),{isValid:l||d,value:s}}var ot=uu(Bi,{uvRatio:Fi}),rt=ot.Fp,hu=ot.Fn;function Of(t){return lu(ot,Er,Object.assign({adjustScalarBytes:Af,zip215:true},t))}var gu=Of({});var Ni=ji;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Lf=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
716
+ "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var fu=t=>Fi(qe,t),$f=BigInt("0x7\
717
+ fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),$i=t=>rt.create(Fe(t)&$f);var it=class t extends Nr{static BASE=new t(
718
+ ot.BASE);static ZERO=new t(ot.ZERO);static Fp=rt;static Fn=hu;constructor(e){super(e);}static fromAffine(e){return new t(ot.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoP\
719
+ oint expected")}init(e){return new t(e)}static fromBytes(e){Ce(e,32);let{a:n,d:r}=Bi,o=Mt,i=k=>rt.create(k),s=$i(e);if(!qc(rt.toBytes(s),e)||ze(s,o))throw new Error("invalid ristretto255 encoding 1");
720
+ let a=i(s*s),c=i(qe+n*a),u=i(qe-n*a),l=i(c*c),d=i(u*u),p=i(n*r*l-d),{isValid:h,value:m}=fu(i(p*d)),g=i(m*u),f=i(m*g*p),v=i((s+s)*g);ze(v,o)&&(v=i(-v));let b=i(c*f),y=i(v*b);if(!h||ze(y,o)||b===Rf)throw new Error(
721
+ "invalid ristretto255 encoding 2");return new t(new ot(v,b,qe,y))}static fromHex(e){return t.fromBytes(bn(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,i=Mt,s=f=>rt.create(f),a=s(s(r+n)*s(r-n)),c=s(e*n),
722
+ u=s(c*c),{value:l}=fu(s(a*u)),d=s(l*a),p=s(l*c),h=s(d*p*o),m;if(ze(o*h,i)){let f=s(n*Ni),v=s(e*Ni);e=f,n=v,m=s(d*Lf);}else m=p;ze(e*h,i)&&(n=s(-n));let g=s((r-n)*m);return ze(g,i)&&(g=s(-g)),rt.toBytes(
723
+ g)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:i}=e.ep,s=u=>rt.create(u),a=s(n*i)===s(r*o),c=s(r*i)===s(n*o);return a||c}is0(){return this.equals(t.ZERO)}};Object.freeze(it.BASE);Object.freeze(
724
+ it.ZERO);Object.freeze(it.prototype);Object.freeze(it);var bu=`-----BEGIN PUBLIC KEY-----
720
725
  MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
721
- -----END PUBLIC KEY-----`;function gu(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 Bi(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.
722
- length%4?"=".repeat(4-e.length%4):"";return gu(e+n)}function Mf(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=gu(e);return n.subarray(n.length-32)}var Lf=new TextEncoder,bu=new TextDecoder;
723
- function jf(t){return typeof t=="object"&&t!==null&&"keys"in t}function Lt(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 Nf=/^[A-Za-z0-9_-]+$/;
724
- function vu(t){let e=t.split(".");return e.length===3&&e.every(n=>Nf.test(n))}function Fi(t){return t===""?"empty":vu(t)?"token":"malformed"}function zi(t,e){if(!vu(t))return {ok:false,reason:"malformed t\
725
- oken"};let n=t.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(bu.decode(Bi(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(jf(e)){let l=typeof s.kid=="string"?s.kid:e.defaultKid,
726
- 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=Mf(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
727
- return {ok:false,reason:"invalid public key"}}let u=false;try{u=mu.verify(Bi(i),Lf.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return u?{ok:true,header:s,payloadBytes:Bi(o)}:
728
- {ok:false,reason:"bad signature"}}function jt(t,e){let n=zi(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(bu.decode(
729
- n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function qi(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"\
730
- active":e<=r?"grace":"expired"}function jv(t,e,n={}){let r=Lt(t);if(Fi(r)==="empty")return {status:"none",reason:"empty"};let i=jt(r,e);if(!i.signatureValid||!i.payload)return {status:"invalid",...i.reason?
731
- {reason:i.reason}:{}};let s=i.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),c=qi(s,a,n.revoked);return c==="revoked"?{status:c,payload:s,reason:"license revoked"}:{status:c,payload:s}}var yu="BVSALA-REVOC",$f=300,Bf=new TextDecoder;function ku(t,e,n={}){let r=u=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:u}),o=zi(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
732
- if(o.header?.typ!==yu)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${yu})`);let i;try{i=JSON.parse(Bf.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
726
+ -----END PUBLIC KEY-----`;function vu(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 zi(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.
727
+ length%4?"=".repeat(4-e.length%4):"";return vu(e+n)}function Ff(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=vu(e);return n.subarray(n.length-32)}var zf=new TextEncoder,yu=new TextDecoder;
728
+ function qf(t){return typeof t=="object"&&t!==null&&"keys"in t}function Lt(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 Vf=/^[A-Za-z0-9_-]+$/;
729
+ function ku(t){let e=t.split(".");return e.length===3&&e.every(n=>Vf.test(n))}function qi(t){return t===""?"empty":ku(t)?"token":"malformed"}function Vi(t,e){if(!ku(t))return {ok:false,reason:"malformed t\
730
+ oken"};let n=t.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(yu.decode(zi(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(qf(e)){let l=typeof s.kid=="string"?s.kid:e.defaultKid,
731
+ 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=Ff(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
732
+ return {ok:false,reason:"invalid public key"}}let u=false;try{u=gu.verify(zi(i),zf.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return u?{ok:true,header:s,payloadBytes:zi(o)}:
733
+ {ok:false,reason:"bad signature"}}function jt(t,e){let n=Vi(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(yu.decode(
734
+ n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function Ui(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"\
735
+ active":e<=r?"grace":"expired"}function Vv(t,e,n={}){let r=Lt(t);if(qi(r)==="empty")return {status:"none",reason:"empty"};let i=jt(r,e);if(!i.signatureValid||!i.payload)return {status:"invalid",...i.reason?
736
+ {reason:i.reason}:{}};let s=i.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),c=Ui(s,a,n.revoked);return c==="revoked"?{status:c,payload:s,reason:"license revoked"}:{status:c,payload:s}}var xu="BVSALA-REVOC",Uf=300,Hf=new TextDecoder;function wu(t,e,n={}){let r=u=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:u}),o=Vi(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
737
+ if(o.header?.typ!==xu)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${xu})`);let i;try{i=JSON.parse(Hf.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
733
738
  seq!="number"||typeof i.asOf!="number"||!Array.isArray(i.revoked))return r("malformed revocation payload");let s=n.minSeq??0;if(i.seq<s)return r(`stale/rolled-back list (seq ${i.seq} < ${s})`);let a=n.
734
- nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??$f;return i.asOf>a+c?r(`asOf too far in the future (${i.asOf} > ${a+c})`):{ok:true,seq:i.seq,asOf:i.asOf,revoked:new Set(i.revoked)}}var Nt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
739
+ nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??Uf;return i.asOf>a+c?r(`asOf too far in the future (${i.asOf} > ${a+c})`):{ok:true,seq:i.seq,asOf:i.asOf,revoked:new Set(i.revoked)}}var Nt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
735
740
  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.
736
741
  set}apply(e){if(e.seq<this._seq)return false;let n=this.set.size;for(let i of e.revoked)this.set.add(i);let r=this.set.size>n,o=e.seq>this._seq;return e.seq>this._seq&&(this._seq=e.seq),e.asOf>this._asOf&&
737
- (this._asOf=e.asOf),r||o}};function Nr(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=Lt(t),s=Fi(i),a=s==="token"?jt(i,e):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,u=new Set(
738
- c?.features??[]),l=()=>{if(s==="empty")return "none";if(!c)return "invalid";let p=qi(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(p==="active"||p==="grace")){let h=c.expires_at+c.grace_days*
742
+ (this._asOf=e.asOf),r||o}};function $r(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=Lt(t),s=qi(i),a=s==="token"?jt(i,e):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,u=new Set(
743
+ c?.features??[]),l=()=>{if(s==="empty")return "none";if(!c)return "invalid";let p=Ui(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(p==="active"||p==="grace")){let h=c.expires_at+c.grace_days*
739
744
  86400,m=Math.min(o,h),g=Math.max(n.revocation.lastContactAt,m);if(r()-g>n.maxStalenessSeconds)return "stale"}return p},d=()=>{let p=l();return p==="active"||p==="grace"};return {isEntitled:p=>d()&&u.has(
740
- p),isActive:()=>d(),status:l,reason:()=>c?void 0:a.reason,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}function xu(t,e,n){return Nr(t,e,{revocation:new Nt,...n?{now:n}:{}})}var $t={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},wu=3,Ff=12;function zf(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
745
+ p),isActive:()=>d(),status:l,reason:()=>c?void 0:a.reason,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}function Su(t,e,n){return $r(t,e,{revocation:new Nt,...n?{now:n}:{}})}var $t={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Tu=3,Wf=12;function Jf(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
741
746
  0){let o=Math.pow(2,Math.min(t.consecutiveFailures,4));n=Math.min(t.maxIntervalSeconds,t.floorSeconds*o);}else {let o=t.refreshAfter!=null?t.refreshAfter-t.nowSeconds:t.pollIntervalSeconds,i=o<0?t.pollIntervalSeconds:
742
- o;n=Math.min(t.pollIntervalSeconds,Math.max(t.floorSeconds,i));}let r=1+(e()*2-1)*t.jitterRatio;return Math.max(t.floorSeconds,n*r)}var qf=10,$r=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;lastEtag=null;consecutive304=0;now(){
747
+ o;n=Math.min(t.pollIntervalSeconds,Math.max(t.floorSeconds,i));}let r=1+(e()*2-1)*t.jitterRatio;return Math.max(t.floorSeconds,n*r)}var Kf=10,Br=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;lastEtag=null;consecutive304=0;now(){
743
748
  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();
744
749
  if(!e){this.avisar("sin-fetch","[bv-sala] no global fetch available; revocation call-home disabled (offline). License expiry is still enforced from the token."),this.opts.onEvent?.({type:"no-fetch"});
745
750
  return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??$t.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"application/json"};this.lastEtag&&(i["\
746
751
  if-none-match"]=this.lastEtag);try{let s=await e(this.opts.url,{signal:n.signal,headers:i});if(s.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.now()),this.opts.onEvent?.(
747
- {type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=qf&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.ok)throw new Error(`revocat\
748
- ions HTTP ${s.status}`);let a=s.headers.get("etag"),c=await s.json();if(!c.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let u=ku(c.list,this.opts.publicKeyPem,{minSeq:this.
752
+ {type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=Kf&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.ok)throw new Error(`revocat\
753
+ ions HTTP ${s.status}`);let a=s.headers.get("etag"),c=await s.json();if(!c.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let u=wu(c.list,this.opts.publicKeyPem,{minSeq:this.
749
754
  opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??$t.maxSkewSeconds});if(!u.ok){let d=u.reason??"rejected";this.opts.onEvent?.({type:"rejected",reason:d}),this.avisar(`r\
750
755
  echazada:${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. Check ${this.opts.url}.`);
751
756
  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.snapshot().size}:{type:"\
752
757
  unchanged",seq:u.seq});}catch(s){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:s}),this.avisarFalloDeRed(s);}finally{clearTimeout(o),this.controller=null;}}callado(){return !!(this.opts.
753
- silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||ye(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;let n=this.consecutiveFailures;if(n<wu||(n-wu)%
754
- Ff!==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 revocations sti\
758
+ silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||ke(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;let n=this.consecutiveFailures;if(n<Tu||(n-Tu)%
759
+ Wf!==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 revocations sti\
755
760
  ll 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(){if(this.stopped)
756
- return;let e=zf({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??$t.floorSeconds,pollIntervalSeconds:this.
761
+ return;let e=Jf({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??$t.floorSeconds,pollIntervalSeconds:this.
757
762
  opts.pollIntervalSeconds??$t.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??$t.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??$t.jitterRatio,...this.opts.random?{random:this.
758
763
  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.
759
- controller?.abort();}};var xn=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=
764
+ controller?.abort();}};var wn=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=
760
765
  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.
761
766
  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.
762
767
  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??
763
768
  Math.ceil(this.maxBuffer/this.maxBatch)+4,r=0;for(let o=0;o<n&&this.buffer.length>0;o++){let i=this.buffer.length;if(await this.flush(),r=this.buffer.length>=i?r+1:0,r>=2)break}}async flush(){if(this.
764
769
  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.
765
770
  fetch;if(!e)return;let n=this.buffer.splice(0,this.maxBatch);try{let r=n.map(i=>this.toWire(i)),o=await e(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bear\
766
- er ${this.options.serviceAccountKey}`,[Nn]:`${this.options.surface??"sdk"}/${Me}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
767
- `the server responded ${o.status}`)):o.status===401||o.status===403?(ye(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status} at ${this.options.url}. Check 'se\
771
+ er ${this.options.serviceAccountKey}`,[$n]:`${this.options.surface??"sdk"}/${je}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
772
+ `the server responded ${o.status}`)):o.status===401||o.status===403?(ke(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status} at ${this.options.url}. Check 'se\
768
773
  rviceAccountKey' (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?.(
769
774
  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.
770
775
  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||
@@ -776,207 +781,207 @@ tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutput
776
781
  eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.cost.eliminatedInputFloorCost}:
777
782
  {},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}$/.
778
783
  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.
779
- attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function Br(){return globalThis.process}function Vf(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\
780
- ]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function Uf(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??
781
- t.NETLIFY)}async function Hf(){if(Br()?.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 Wf(t,e=Hf){
782
- if(t.KUBERNETES_SERVICE_HOST||Uf(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||Vf(n)))return n}async function Jf(){let t=Br();if(!t||!t.env)return;let e=t.env,n=await Wf(e),r=[t.platform,
783
- 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 Kf=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
784
- ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function Vi(){let t=Br()?.env;if(!t)
785
- return false;for(let e of Kf){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function Gf(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
784
+ attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function Fr(){return globalThis.process}function Gf(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\
785
+ ]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function Zf(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??
786
+ t.NETLIFY)}async function Yf(){if(Fr()?.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 Qf(t,e=Yf){
787
+ if(t.KUBERNETES_SERVICE_HOST||Zf(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||Gf(n)))return n}async function Xf(){let t=Fr();if(!t||!t.env)return;let e=t.env,n=await Qf(e),r=[t.platform,
788
+ 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 em=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
789
+ ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function Hi(){let t=Fr()?.env;if(!t)
790
+ return false;for(let e of em){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function tm(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
786
791
  r.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",s,r.encode(e));return [...new Uint8Array(a)].map(c=>c.toString(16).padStart(2,"0")).join("")}catch{}let o=2166136261,i=`${t}\
787
- |${e}`;for(let s=0;s<i.length;s++)o^=i.charCodeAt(s),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function Ui(t){let n=Br()?.env?.BVSALA_SEAT_ID;if(n&&Zf.test(n))return n;let r=await Jf();
788
- if(!r)return;let o=await Gf(t,r);if(o)return `m-${o.slice(0,32)}`}var Zf=/^[A-Za-z0-9._:/-]{1,128}$/;var Su={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function Tu(t){return {exactCache:t.exactCache??new zn,semanticCache:t.semanticCache,singleflight:t.singleflight??new qn,resolvers:t.resolvers??pa(),router:t.router??new Kn,toolSelector:t.toolSelector??
789
- new Zn,formatSelector:t.formatSelector??new er({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new tr,constraintBackends:t.constraintBackends??[]}}var ke=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\
790
- ted before any provider request was sent"),this.name="StreamAbortedError",this.requestSent=e;}},Fr=class extends Error{job;notSubmitted;constructor(e,n,r,o){super(e,o),this.name="BatchSubmitError",this.
791
- job=n,this.notSubmitted=r;}};var Yf={"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.\
792
+ |${e}`;for(let s=0;s<i.length;s++)o^=i.charCodeAt(s),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function Wi(t){let n=Fr()?.env?.BVSALA_SEAT_ID;if(n&&nm.test(n))return n;let r=await Xf();
793
+ if(!r)return;let o=await tm(t,r);if(o)return `m-${o.slice(0,32)}`}var nm=/^[A-Za-z0-9._:/-]{1,128}$/;var Cu={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function Eu(t){return {exactCache:t.exactCache??new qn,semanticCache:t.semanticCache,singleflight:t.singleflight??new Vn,resolvers:t.resolvers??ma(),router:t.router??new Gn,toolSelector:t.toolSelector??
794
+ new Yn,formatSelector:t.formatSelector??new tr({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new nr,constraintBackends:t.constraintBackends??[]}}var xe=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\
795
+ ted before any provider request was sent"),this.name="StreamAbortedError",this.requestSent=e;}},zr=class extends Error{job;notSubmitted;constructor(e,n,r,o){super(e,o),this.name="BatchSubmitError",this.
796
+ job=n,this.notSubmitted=r;}};var rm={"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.\
792
797
  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\
793
798
  .6-luna":true,"gpt-5.6-sol":true,"gpt-5.6-terra":true,"gpt-6-astra":true,"gpt-6-sol":true,"gpt-6-luna":true,o3:true,"o3-mini":true,"o3-pro":true,"o4-mini":true,"claude-opus-4-5":false,"claude-opus-4-6":false,"claude-opus-4-7":false,
794
799
  "claude-opus-4-8":false,"claude-opus-5":true,"claude-opus-5-5":true,"claude-opus-4":false,"claude-sonnet-4-5":false,"claude-sonnet-4-6":false,"claude-sonnet-5":true,"claude-fable-5":true,"claude-fable-5-1":true,"claude-myt\
795
- hos-5-1":true,"claude-mythos-5":true,"claude-sonnet-4":false,"claude-haiku-4-5":false,"claude-3-5-sonnet":false,"claude-3-5-haiku":false,"claude-3-opus":false,"claude-3-haiku":false,"gemini-3.8-flash":true,"gemini-3.7-flash":true,
796
- "gemini-3.6-flash":true,"gemini-3.1-flash-lite":true,"gemini-3-flash-preview":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini-2.5-pro":true,"gemini-2.5-flash":true},Qf=new Set(
797
- ["claude-opus-4-7","claude-opus-4-8"]),Xf=[/^o\d/,/^gpt-5/,/^gpt-([6-9]|\d{2})/,/^gpt-oss/,/^gemini-(2\.5|[3-9])/,/^claude-[a-z]+-([5-9]|\d{2})/,/^grok-(3-mini|[4-9])/,/reason/,/think/,/(^|[-_.])r\d($|[-_.])/,
798
- /^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Cu(t){let e=t.lastIndexOf("/"),n=(e>=0?t.slice(e+1):t).toLowerCase();if(Xf.some(i=>i.test(n)))return "reasoning-model";let r=Tt(t);if(r===void 0)
799
- return "unclassified-model";let o=Yf[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(Qf.has(r))return "temperature-ignored"}var Hi={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},Eu={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},em=[["claude-fable-5-1",512],["claude-mytho\
800
+ hos-5-1":true,"claude-mythos-5":true,"claude-sonnet-4":false,"claude-haiku-4-5":false,"claude-3-5-sonnet":false,"claude-3-5-haiku":false,"claude-3-opus":false,"gemini-3.8-flash":true,"gemini-3.7-flash":true,"gemini-3.6-flas\
801
+ h":true,"gemini-3.1-flash-lite":true,"gemini-3-flash-preview":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini-2.5-pro":true,"gemini-2.5-flash":true},om=new Set(["claude\
802
+ -opus-4-7","claude-opus-4-8"]),im=[/^o\d/,/^gpt-5/,/^gpt-([6-9]|\d{2})/,/^gpt-oss/,/^gemini-(2\.5|[3-9])/,/^claude-[a-z]+-([5-9]|\d{2})/,/^grok-(3-mini|[4-9])/,/reason/,/think/,/(^|[-_.])r\d($|[-_.])/,
803
+ /^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Pu(t){let e=t.lastIndexOf("/"),n=(e>=0?t.slice(e+1):t).toLowerCase();if(im.some(i=>i.test(n)))return "reasoning-model";let r=Tt(t);if(r===void 0)
804
+ return "unclassified-model";let o=rm[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(om.has(r))return "temperature-ignored"}var Ji={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},Ru={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},sm=[["claude-fable-5-1",512],["claude-mytho\
800
805
  s-5-1",512],["claude-fable-5",512],["claude-mythos-5",512],["claude-opus-5-5",512],["claude-opus-5",512],["claude-opus-4-7",2048],["claude-opus-4-6",4096],["claude-opus-4-5",4096],["claude-haiku-4-5",
801
- 4096],["claude-3-5-haiku",2048]];function Wi(t){for(let[e,n]of em)if(t===e||t.startsWith(`${e}-`))return {...Eu,minimumCacheTokens:n};return Eu}var Ji={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1};var Pu={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function zr(t,e,n,r){let o=r.minimumCacheTokens;if(o==null||t<o)return t;let i=Math.min(e,t),s=t-i,a=Math.min(1,Math.max(0,
802
- n)),c=a*i*r.cacheReadMultiplier+(1-a)*i*r.cacheWriteMultiplier;return s+c}function Ki(t){let e=zr(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=zr(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??
806
+ 4096],["claude-3-5-haiku",2048]];function Ki(t){for(let[e,n]of sm)if(t===e||t.startsWith(`${e}-`))return {...Ru,minimumCacheTokens:n};return Ru}var Gi={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1};var Du={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function qr(t,e,n,r){let o=r.minimumCacheTokens;if(o==null||t<o)return t;let i=Math.min(e,t),s=t-i,a=Math.min(1,Math.max(0,
807
+ n)),c=a*i*r.cacheReadMultiplier+(1-a)*i*r.cacheWriteMultiplier;return s+c}function Zi(t){let e=qr(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=qr(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??
803
808
  0),r=e-n,o=t.tier.minimumCacheTokens,s=o!=null&&t.originalTokens>=o&&t.compressedTokens<o,a;if(r<=0){let c=e<t.originalTokens;a=s?`compressing drops the prompt out of the cacheable tier (${t.compressedTokens}\
804
809
  < ${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*
805
810
  100).toFixed(0)}% hit rate)`:"the saving does not cover the compressor's cost";}else s?a=`pays off even after losing the prefix cache (${(t.prefixHitRate*100).toFixed(0)}% hit rate)`:a="pays off and do\
806
- es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function Ru(t){let e=o=>Ki({...t,prefixHitRate:o}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,
807
- r=1;for(let o=0;o<40;o++){let i=(n+r)/2;e(i)>0?n=i:r=i;}return (n+r)/2}function tm(t){let e=Ru({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(zr(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.
808
- totalTokens?null:1)}var qr=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-
809
- 1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=tm(n),o=this.estados.get(e),i=nm(o);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:r,observada:i}:r==null?
811
+ es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function Iu(t){let e=o=>Zi({...t,prefixHitRate:o}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,
812
+ r=1;for(let o=0;o<40;o++){let i=(n+r)/2;e(i)>0?n=i:r=i;}return (n+r)/2}function am(t){let e=Iu({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(qr(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.
813
+ totalTokens?null:1)}var Vr=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-
814
+ 1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=am(n),o=this.estados.get(e),i=cm(o);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:r,observada:i}:r==null?
810
815
  {marcar:true,razon:"marking cannot lose money at this tier (no write premium)",umbral:r,observada:i}:o?.apagada?{marcar:false,razon:`prefix-cache marking OFF: measured hit rate ${Bt(i)} did not reach the ${Bt(
811
816
  r)} break-even, so marking was costing money`,umbral:r,observada:i}:o==null||o.marcadas<this.exploracion?{marcar:true,razon:`exploring the prefix cache (${o?.marcadas??0}/${this.exploracion}); hit rate \
812
817
  is only observable on requests that were marked`,umbral:r,observada:i}:i!=null&&i>r?{marcar:true,razon:`measured hit rate ${Bt(i)} beats the ${Bt(r)} break-even`,umbral:r,observada:i}:(o.apagada=true,{marcar:false,
813
818
  razon:`prefix-cache marking OFF: measured hit rate ${Bt(i)} did not reach the ${Bt(r)} break-even, so marking was costing money`,umbral:r,observada:i})}registrar(e,n){let r=this.estados.get(e)??{marcadas:0,
814
- 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 nm(t){
815
- if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function Bt(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var Ft={"5m":3e5,"30m":18e5,"1h":36e5},Ce=["5m","30m","1h"],_u=20;function Du(t,e){let n=3735928559^e,r=1103547991^e;for(let o=0;o<t.length;o++){let i=t.charCodeAt(o);n=Math.imul(n^i,2654435761),r=Math.
816
- imul(r^i,1597334677);}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Iu(t){
817
- return Du(t,0).toString(36)+"."+Du(t,2654435769).toString(36)}function rm(t){let e=t.toolCalls?.length?t.toolCalls.map(r=>`${r.id??""}${r.name}${r.arguments}`).join(""):"",n=t.isError===true?"error":
818
- "";return `${t.role}${t.name??""}${t.toolCallId??""}${e}${t.content}${n}`}function Au(t,e){let n=[Iu(`bvsala-prefijo\0${t}`)];for(let r of e)n.push(Iu(`${n[n.length-1]}${rm(r)}`));return n}function ts(t){
819
- let e=0;for(;e<t.length&&t[e].role==="system";)e+=1;return e}function Gi(){return {"5m":0,"30m":0,"1h":0}}function Zi(){return {"5m":{resueltas:0,reutilizadas:0,tardias:0},"30m":{resueltas:0,reutilizadas:0,
820
- tardias:0},"1h":{resueltas:0,reutilizadas:0,tardias:0}}}var Vr=1,Ou=1440*6e4;function ns(t){return `bvsala:cache-breakpoints:v${Vr}:${t}`}var qt=class{clases=new Map;porHuella=new Map;maxPorClase;maxClases;prediccionesMinimas;confirmacionMinima;memoria;constructor(e={}){
819
+ 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 cm(t){
820
+ if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function Bt(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var Ft={"5m":3e5,"30m":18e5,"1h":36e5},Pe=["5m","30m","1h"],Ou=20;function _u(t,e){let n=3735928559^e,r=1103547991^e;for(let o=0;o<t.length;o++){let i=t.charCodeAt(o);n=Math.imul(n^i,2654435761),r=Math.
821
+ imul(r^i,1597334677);}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Au(t){
822
+ return _u(t,0).toString(36)+"."+_u(t,2654435769).toString(36)}function um(t){let e=t.toolCalls?.length?t.toolCalls.map(r=>`${r.id??""}${r.name}${r.arguments}`).join(""):"",n=t.isError===true?"error":
823
+ "";return `${t.role}${t.name??""}${t.toolCallId??""}${e}${t.content}${n}`}function Mu(t,e){let n=[Au(`bvsala-prefijo\0${t}`)];for(let r of e)n.push(Au(`${n[n.length-1]}${um(r)}`));return n}function rs(t){
824
+ let e=0;for(;e<t.length&&t[e].role==="system";)e+=1;return e}function Yi(){return {"5m":0,"30m":0,"1h":0}}function Qi(){return {"5m":{resueltas:0,reutilizadas:0,tardias:0},"30m":{resueltas:0,reutilizadas:0,
825
+ tardias:0},"1h":{resueltas:0,reutilizadas:0,tardias:0}}}var Ur=1,Lu=1440*6e4;function os(t){return `bvsala:cache-breakpoints:v${Ur}:${t}`}var qt=class{clases=new Map;porHuella=new Map;maxPorClase;maxClases;prediccionesMinimas;confirmacionMinima;memoria;constructor(e={}){
821
826
  this.maxPorClase=Math.max(16,e.maxPorClase??2048),this.maxClases=Math.max(1,e.maxClases??256),this.prediccionesMinimas=Math.max(1,e.prediccionesMinimas??8),this.confirmacionMinima=e.confirmacionMinima??
822
827
  .5,this.memoria=Math.max(32,e.memoria??512);}observar(e,n,r){let o=this.estadoDe(e);this.vencer(o,r);let i=null;for(let s=1;s<n.length;s++){let a=this.porHuella.get(n[s]);if(!a||a.descartada||a.clase!==
823
828
  e||a.indice!==s)continue;let c=Math.max(0,r-a.escrita);c>Ft["1h"]||(this.resolverReutilizada(o,a,c),i={tipo:a.tipo,indice:s,huecoMs:c,...a.posicionDelProveedor!==void 0?{posicionDelProveedor:a.posicionDelProveedor}:
824
829
  {},...a.ttl?{ttl:a.ttl}:{},...a.idDelProveedor?{idDelProveedor:a.idDelProveedor}:{}});}return i}registrar(e){let n=this.estadoDe(e.clase);this.vencer(n,e.enviada);let r=e.enviada;for(let o of ["S","H","\
825
830
  T"]){let i=e.tramos[o];if(i===void 0||i<=0||i>=e.huellas.length)continue;if(n.cola.length-n.cabeza>=this.maxPorClase)break;let s=e.huellas[i],a=e.ultimoMarcado===o,c={clase:e.clase,tipo:o,huella:s,indice:i,
826
831
  escrita:r,contadas:0,descartada:false,...a&&e.posicionDelProveedor!=null&&e.posicionDelProveedor>0?{posicionDelProveedor:e.posicionDelProveedor}:{},...a&&e.ttl?{ttl:e.ttl}:{},...a&&e.idDelProveedor?{idDelProveedor:e.
827
- idDelProveedor}:{}},u=this.porHuella.get(s);u&&u.contadas!==7&&this.descartar(u),this.porHuella.set(s,c),n.cola.push(c);for(let l of Ce)n.pendientes[o][l]+=1;}}verificar(e,n,r){if(n.posicionDelProveedor===
832
+ idDelProveedor}:{}},u=this.porHuella.get(s);u&&u.contadas!==7&&this.descartar(u),this.porHuella.set(s,c),n.cola.push(c);for(let l of Pe)n.pendientes[o][l]+=1;}}verificar(e,n,r){if(n.posicionDelProveedor===
828
833
  void 0)return;let o=n.ttl??"5m";if(n.huecoMs>Ft[o])return;let i=this.estadoDe(e);i.predichas+=1,r>=n.posicionDelProveedor*.98&&(i.confirmadas+=1),i.predichas>=this.prediccionesMinimas&&i.confirmadas/i.
829
834
  predichas<this.confirmacionMinima&&(i.apagada=true);}estadistica(e,n){let r=this.estadoDe(e);this.vencer(r,n);let o=(i,s)=>({pendientes5m:s["5m"],pendientes30m:s["30m"],pendientes1h:s["1h"],muestras5m:i["\
830
- 5m"].resueltas,muestras30m:i["30m"].resueltas,muestras1h:i["1h"].resueltas,k5m:i["5m"].reutilizadas,k30m:i["30m"].reutilizadas,k1h:i["1h"].reutilizadas,kTardias:i["1h"].tardias,en5m:Yi(i["5m"]),en30m:Yi(
831
- i["30m"]),en1h:Yi(i["1h"])});return {S:o(r.contadores.S,r.pendientes.S),H:o(r.contadores.H,r.pendientes.H),T:o(r.contadores.T,r.pendientes.T),predichas:r.predichas,confirmadas:r.confirmadas,apagada:r.apagada}}get vivas(){
832
- return this.porHuella.size}exportarClase(e){let r=this.clases.get(e)??this.estadoVacio(),o=r.cabeza,i=c=>Ce.map(u=>{let l=r.contadores[c][u];return [l.resueltas,l.reutilizadas,l.tardias]}),s=c=>Ce.map(
833
- u=>r.pendientes[c][u]),a={v:Vr,clase:e,c:{S:i("S"),H:i("H"),T:i("T")},p:{S:s("S"),H:s("H"),T:s("T")},e:r.cola.slice(o).map(c=>c.descartada?["",c.tipo,c.indice,c.escrita,c.contadas,1,null,null,null]:[c.
834
- huella,c.tipo,c.indice,c.escrita,c.contadas,0,c.posicionDelProveedor??null,c.ttl??null,c.idDelProveedor??null]),cur:Ce.map(c=>Math.max(0,r.cursores[c]-o)),pr:r.predichas,co:r.confirmadas,off:r.apagada};
835
+ 5m"].resueltas,muestras30m:i["30m"].resueltas,muestras1h:i["1h"].resueltas,k5m:i["5m"].reutilizadas,k30m:i["30m"].reutilizadas,k1h:i["1h"].reutilizadas,kTardias:i["1h"].tardias,en5m:Xi(i["5m"]),en30m:Xi(
836
+ i["30m"]),en1h:Xi(i["1h"])});return {S:o(r.contadores.S,r.pendientes.S),H:o(r.contadores.H,r.pendientes.H),T:o(r.contadores.T,r.pendientes.T),predichas:r.predichas,confirmadas:r.confirmadas,apagada:r.apagada}}get vivas(){
837
+ return this.porHuella.size}exportarClase(e){let r=this.clases.get(e)??this.estadoVacio(),o=r.cabeza,i=c=>Pe.map(u=>{let l=r.contadores[c][u];return [l.resueltas,l.reutilizadas,l.tardias]}),s=c=>Pe.map(
838
+ u=>r.pendientes[c][u]),a={v:Ur,clase:e,c:{S:i("S"),H:i("H"),T:i("T")},p:{S:s("S"),H:s("H"),T:s("T")},e:r.cola.slice(o).map(c=>c.descartada?["",c.tipo,c.indice,c.escrita,c.contadas,1,null,null,null]:[c.
839
+ huella,c.tipo,c.indice,c.escrita,c.contadas,0,c.posicionDelProveedor??null,c.ttl??null,c.idDelProveedor??null]),cur:Pe.map(c=>Math.max(0,r.cursores[c]-o)),pr:r.predichas,co:r.confirmadas,off:r.apagada};
835
840
  return JSON.stringify(a)}importarClase(e,n){let r=n;if(typeof n=="string")try{r=JSON.parse(n);}catch{return "invalid"}let o=r;if(o===null||typeof o!="object")return "invalid";if(typeof o.v=="number"&&o.v>
836
- Vr)return "newer";let i=this.leerInstantanea(o,e);if(!i)return "invalid";let s=this.clases.get(e);if(s){for(let a=s.cabeza;a<s.cola.length;a++){let c=s.cola[a];this.porHuella.get(c.huella)===c&&this.porHuella.
837
- delete(c.huella);}this.clases.delete(e);}this.clases.set(e,i);for(let a of i.cola)a.descartada||this.porHuella.set(a.huella,a);return "loaded"}leerInstantanea(e,n){if(e.v!==Vr||e.clase!==n)return null;let r=i=>typeof i==
841
+ Ur)return "newer";let i=this.leerInstantanea(o,e);if(!i)return "invalid";let s=this.clases.get(e);if(s){for(let a=s.cabeza;a<s.cola.length;a++){let c=s.cola[a];this.porHuella.get(c.huella)===c&&this.porHuella.
842
+ delete(c.huella);}this.clases.delete(e);}this.clases.set(e,i);for(let a of i.cola)a.descartada||this.porHuella.set(a.huella,a);return "loaded"}leerInstantanea(e,n){if(e.v!==Ur||e.clase!==n)return null;let r=i=>typeof i==
838
843
  "number"&&Number.isInteger(i)&&i>=0,o=this.estadoVacio();for(let i of ["S","H","T"]){let s=e.c?.[i],a=e.p?.[i];if(!Array.isArray(s)||s.length!==3||!Array.isArray(a)||a.length!==3)return null;for(let c=0;c<
839
- 3;c++){let u=s[c];if(!Array.isArray(u)||u.length!==3||!u.every(r))return null;let[l,d,p]=u;if(d>l||p>d||!r(a[c]))return null;let h=Ce[c];o.contadores[i][h]={resueltas:l,reutilizadas:d,tardias:p},o.pendientes[i][h]=
844
+ 3;c++){let u=s[c];if(!Array.isArray(u)||u.length!==3||!u.every(r))return null;let[l,d,p]=u;if(d>l||p>d||!r(a[c]))return null;let h=Pe[c];o.contadores[i][h]={resueltas:l,reutilizadas:d,tardias:p},o.pendientes[i][h]=
840
845
  a[c];}}if(!Array.isArray(e.e)||e.e.length>this.maxPorClase)return null;for(let i of e.e){if(!Array.isArray(i)||i.length!==9)return null;let[s,a,c,u,l,d,p,h,m]=i;if(typeof s!="string"||d===0&&s===""||a!==
841
846
  "S"&&a!=="H"&&a!=="T"||!r(c)||c===0||typeof u!="number"||!Number.isFinite(u)||!r(l)||l>7||d!==0&&d!==1||p!==null&&!(typeof p=="number"&&Number.isFinite(p)&&p>0)||h!==null&&h!=="5m"&&h!=="1h"||m!==null&&
842
847
  !(typeof m=="string"&&m!==""&&m.length<=256))return null;o.cola.push({clase:n,tipo:a,huella:s,indice:c,escrita:u,contadas:l,descartada:d===1,...p!==null?{posicionDelProveedor:p}:{},...h!==null?{ttl:h}:
843
- {},...m!==null?{idDelProveedor:m}:{}});}if(!Array.isArray(e.cur)||e.cur.length!==3)return null;for(let i=0;i<3;i++){let s=e.cur[i];if(!r(s)||s>o.cola.length)return null;o.cursores[Ce[i]]=s;}return !r(e.pr)||
844
- !r(e.co)||e.co>e.pr||typeof e.off!="boolean"?null:(o.predichas=e.pr,o.confirmadas=e.co,o.apagada=e.off,o)}estadoVacio(){return {contadores:{S:Zi(),H:Zi(),T:Zi()},pendientes:{S:Gi(),H:Gi(),T:Gi()},cola:[],
848
+ {},...m!==null?{idDelProveedor:m}:{}});}if(!Array.isArray(e.cur)||e.cur.length!==3)return null;for(let i=0;i<3;i++){let s=e.cur[i];if(!r(s)||s>o.cola.length)return null;o.cursores[Pe[i]]=s;}return !r(e.pr)||
849
+ !r(e.co)||e.co>e.pr||typeof e.off!="boolean"?null:(o.predichas=e.pr,o.confirmadas=e.co,o.apagada=e.off,o)}estadoVacio(){return {contadores:{S:Qi(),H:Qi(),T:Qi()},pendientes:{S:Yi(),H:Yi(),T:Yi()},cola:[],
845
850
  cabeza:0,cursores:{"5m":0,"30m":0,"1h":0},predichas:0,confirmadas:0,apagada:false}}estadoDe(e){let n=this.clases.get(e);if(n)return this.clases.delete(e),this.clases.set(e,n),n;for(n=this.estadoVacio(),this.
846
851
  clases.set(e,n);this.clases.size>this.maxClases;){let[r,o]=this.clases.entries().next().value;for(let i=o.cabeza;i<o.cola.length;i++){let s=o.cola[i];this.porHuella.get(s.huella)===s&&this.porHuella.delete(
847
- s.huella);}this.clases.delete(r);}return n}descartar(e){let n=this.clases.get(e.clase);Ce.forEach((r,o)=>{e.contadas&1<<o||(n&&(n.pendientes[e.tipo][r]=Math.max(0,n.pendientes[e.tipo][r]-1)),e.contadas|=
848
- 1<<o);}),e.descartada=true;}resolverReutilizada(e,n,r){Ce.forEach((o,i)=>{if(n.contadas&1<<i)return;e.pendientes[n.tipo][o]=Math.max(0,e.pendientes[n.tipo][o]-1);let s=e.contadores[n.tipo][o];s.resueltas+=
849
- 1,r<=Ft[o]&&(s.reutilizadas+=1),o==="1h"&&r<=Ft["1h"]&&r>Ft["5m"]&&(s.tardias+=1),n.contadas|=1<<i;}),this.reducirSiHaceFalta(e.contadores[n.tipo]);}vencer(e,n){for(Ce.forEach((r,o)=>{let i=Math.max(e.cursores[r],
852
+ s.huella);}this.clases.delete(r);}return n}descartar(e){let n=this.clases.get(e.clase);Pe.forEach((r,o)=>{e.contadas&1<<o||(n&&(n.pendientes[e.tipo][r]=Math.max(0,n.pendientes[e.tipo][r]-1)),e.contadas|=
853
+ 1<<o);}),e.descartada=true;}resolverReutilizada(e,n,r){Pe.forEach((o,i)=>{if(n.contadas&1<<i)return;e.pendientes[n.tipo][o]=Math.max(0,e.pendientes[n.tipo][o]-1);let s=e.contadores[n.tipo][o];s.resueltas+=
854
+ 1,r<=Ft[o]&&(s.reutilizadas+=1),o==="1h"&&r<=Ft["1h"]&&r>Ft["5m"]&&(s.tardias+=1),n.contadas|=1<<i;}),this.reducirSiHaceFalta(e.contadores[n.tipo]);}vencer(e,n){for(Pe.forEach((r,o)=>{let i=Math.max(e.cursores[r],
850
855
  e.cabeza);for(;i<e.cola.length&&n-e.cola[i].escrita>Ft[r];){let s=e.cola[i];!s.descartada&&!(s.contadas&1<<o)&&(e.pendientes[s.tipo][r]=Math.max(0,e.pendientes[s.tipo][r]-1),e.contadores[s.tipo][r].resueltas+=
851
856
  1,this.reducirSiHaceFalta(e.contadores[s.tipo])),s.contadas|=1<<o,i+=1;}e.cursores[r]=i;});e.cabeza<e.cursores["1h"];){let r=e.cola[e.cabeza];this.porHuella.get(r.huella)===r&&this.porHuella.delete(r.huella),
852
- e.cabeza+=1;}if(e.cabeza>1024&&e.cabeza*2>e.cola.length){e.cola.splice(0,e.cabeza);for(let r of Ce)e.cursores[r]-=e.cabeza;e.cabeza=0;}}reducirSiHaceFalta(e){for(let n of Ce)e[n].resueltas>=this.memoria&&
853
- (e[n].resueltas=Math.floor(e[n].resueltas/2),e[n].reutilizadas=Math.floor(e[n].reutilizadas/2),e[n].tardias=Math.floor(e[n].tardias/2));}};function Yi(t){return t.resueltas>0?t.reutilizadas/t.resueltas:
854
- 0}function Qi(t,e){let n=t-e;return n>0?Math.max(0,(t-1)/n):1}function Xi(t,e,n=1.96){if(e<=0)return [0,1];let r=t/e,o=n*n,i=(r+o/(2*e))/(1+o/e),s=n*Math.sqrt(r*(1-r)/e+o/(4*e*e))/(1+o/e);return [Math.max(
855
- 0,i-s),Math.min(1,i+s)]}function es(t,e,n,r,o){return e+n>=o&&Xi(t,e+n)[0]>r?true:e>=o&&Xi(t,e)[1]<r?false:null}function Mu(t){let e=t.muestrasMinimas??5,n=t.tramo.cacheReadMultiplier,r=t.tramo.cacheWriteMultiplier,
856
- o=t.primaDeUnaHora!=null&&t.primaDeUnaHora>r?t.primaDeUnaHora:null,i=Qi(r,n),s=o!=null?Qi(o,n):null,a={historial:true,cola:false,ttl:"5m",razon:"",equilibrio:i};if(t.estadistica.apagada)return {...a,razon:`\
857
+ e.cabeza+=1;}if(e.cabeza>1024&&e.cabeza*2>e.cola.length){e.cola.splice(0,e.cabeza);for(let r of Pe)e.cursores[r]-=e.cabeza;e.cabeza=0;}}reducirSiHaceFalta(e){for(let n of Pe)e[n].resueltas>=this.memoria&&
858
+ (e[n].resueltas=Math.floor(e[n].resueltas/2),e[n].reutilizadas=Math.floor(e[n].reutilizadas/2),e[n].tardias=Math.floor(e[n].tardias/2));}};function Xi(t){return t.resueltas>0?t.reutilizadas/t.resueltas:
859
+ 0}function es(t,e){let n=t-e;return n>0?Math.max(0,(t-1)/n):1}function ts(t,e,n=1.96){if(e<=0)return [0,1];let r=t/e,o=n*n,i=(r+o/(2*e))/(1+o/e),s=n*Math.sqrt(r*(1-r)/e+o/(4*e*e))/(1+o/e);return [Math.max(
860
+ 0,i-s),Math.min(1,i+s)]}function ns(t,e,n,r,o){return e+n>=o&&ts(t,e+n)[0]>r?true:e>=o&&ts(t,e)[1]<r?false:null}function ju(t){let e=t.muestrasMinimas??5,n=t.tramo.cacheReadMultiplier,r=t.tramo.cacheWriteMultiplier,
861
+ o=t.primaDeUnaHora!=null&&t.primaDeUnaHora>r?t.primaDeUnaHora:null,i=es(r,n),s=o!=null?es(o,n):null,a={historial:true,cola:false,ttl:"5m",razon:"",equilibrio:i};if(t.estadistica.apagada)return {...a,razon:`\
857
862
  fixed placement: the provider's counter confirmed only ${t.estadistica.confirmadas} of ${t.estadistica.predichas} cache reads the layer predicted for this traffic, so the layer stopped trusting its ow\
858
- n reuse measurement here`};let c=b=>({en5m:es(b.k5m,b.muestras5m,b.pendientes5m,i,e),en1h:s!=null?es(b.k1h,b.muestras1h,b.pendientes1h,s,e):null}),u=[],l=t.estadistica.H,d=t.estadistica.T,p=c(l),h=c(d),
863
+ n reuse measurement here`};let c=b=>({en5m:ns(b.k5m,b.muestras5m,b.pendientes5m,i,e),en1h:s!=null?ns(b.k1h,b.muestras1h,b.pendientes1h,s,e):null}),u=[],l=t.estadistica.H,d=t.estadistica.T,p=c(l),h=c(d),
859
864
  m=b=>`${b.k5m}/${b.muestras5m} in 5 min, ${b.k1h}/${b.muestras1h} in 1 h`,g=true;t.hayHistorial&&(p.en5m===true||p.en1h===true?u.push(`history re-sent (${m(l)}): above break-even, marked`):p.en5m===false?(g=false,
860
865
  u.push(`history re-sent only ${m(l)} (break-even ${zt(i)}): breakpoint moved back to the system header, no write premium on a prefix nobody re-reads`)):u.push(`history: not conclusive yet (${m(l)}), f\
861
866
  ixed placement kept`));let f=h.en5m===true||h.en1h===true;u.push(f?`continued ${m(d)}: above break-even, tail marked so the next turn reads this whole prompt`:h.en5m===false?`continued only ${m(d)} (break-ev\
862
867
  en ${zt(i)}): tail not marked`:`tail: not conclusive yet (${m(d)}), not marked`);let v="5m";if(o!=null){let b=f?"T":g&&t.hayHistorial?"H":"S",y=t.estadistica[b],k=b==="T"?h:b==="H"?p:c(y),T=b==="T"?t.
863
868
  tokens.T:b==="H"?t.tokens.H:t.tokens.S;if(k.en5m!==true&&k.en1h===true)v="1h",u.push(`1h TTL: re-sent ${m(y)} (1 h break-even ${zt(s)}), while 5 min does not pay`);else if(k.en5m===true&&y.muestras1h>=e&&T>
864
- 0){let[w]=Xi(y.kTardias,y.muestras1h+y.pendientes1h),P=Math.max(0,T-t.lecturaPrevista()),x=w*(r-n)*T,S=(o-r)*P;x>S&&(v="1h",u.push(`1h TTL: at least ${zt(w)} of re-sends come after 5 min; re-reading ${T}\
865
- tokens then beats the extra premium on the ${P} written now`));}}return {historial:g,cola:f,ttl:v,razon:u.join("; "),equilibrio:i}}function Lu(t){let e=t.muestrasMinimas??5,n=Qi(t.tramo.cacheWriteMultiplier,
866
- t.tramo.cacheReadMultiplier),r=t.estadistica.T,o=t.estadistica.H,i=(a,c,u)=>es(a,c,u,n,e)===false;if(t.estadistica.apagada)return {explicita:false,historial:true,razon:`provider default kept: the provider's co\
869
+ 0){let[x]=ts(y.kTardias,y.muestras1h+y.pendientes1h),R=Math.max(0,T-t.lecturaPrevista()),D=x*(r-n)*T,I=(o-r)*R;D>I&&(v="1h",u.push(`1h TTL: at least ${zt(x)} of re-sends come after 5 min; re-reading ${T}\
870
+ tokens then beats the extra premium on the ${R} written now`));}}return {historial:g,cola:f,ttl:v,razon:u.join("; "),equilibrio:i}}function Nu(t){let e=t.muestrasMinimas??5,n=es(t.tramo.cacheWriteMultiplier,
871
+ t.tramo.cacheReadMultiplier),r=t.estadistica.T,o=t.estadistica.H,i=(a,c,u)=>ns(a,c,u,n,e)===false;if(t.estadistica.apagada)return {explicita:false,historial:true,razon:`provider default kept: the provider's co\
867
872
  unter confirmed only ${t.estadistica.confirmadas} of ${t.estadistica.predichas} predicted cache reads`,equilibrio:n};if(!i(r.k30m,r.muestras30m,r.pendientes30m))return {explicita:false,historial:true,razon:`\
868
873
  provider default kept: continued ${r.k30m}/${r.muestras30m} within 30 min, not clearly below the ${zt(n)} break-even`,equilibrio:n};let s=!t.hayHistorial||!i(o.k30m,o.muestras30m,o.pendientes30m);return {
869
874
  explicita:true,historial:s,razon:`explicit mode: continued only ${r.k30m}/${r.muestras30m} within 30 min (break-even ${zt(n)}), so the question is not written; breakpoint at the ${s?"end of the stable h\
870
- istory":"system header"}`,equilibrio:n}}function zt(t){return `${(t*100).toFixed(1)}%`}var ju=.5;function om(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function im(t){return 1-t}function sm(t,e=ju){return e-t}function Nu(t,e,n=ju){
871
- if(!t||!e)return null;let r=om(t,e);if(r==null||!Number.isFinite(r))return null;let o=im(r),i=sm(r,n),s=i>0,a=c=>`${(c*100).toFixed(1)}%`;return {r,equilibrio:o,escaladoMaximo:i,viable:s,razon:s?`the c\
875
+ istory":"system header"}`,equilibrio:n}}function zt(t){return `${(t*100).toFixed(1)}%`}var $u=.5;function lm(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function dm(t){return 1-t}function pm(t,e=$u){return e-t}function Bu(t,e,n=$u){
876
+ if(!t||!e)return null;let r=lm(t,e);if(r==null||!Number.isFinite(r))return null;let o=dm(r),i=pm(r,n),s=i>0,a=c=>`${(c*100).toFixed(1)}%`;return {r,equilibrio:o,escaladoMaximo:i,viable:s,razon:s?`the c\
872
877
  heap model costs ${a(r)} of the strong one, so routing pays off while escalations stay under ${a(i)} (it stops saving money at ${a(o)})`:`the cheap model costs ${a(r)} of the strong one: even with zer\
873
- o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var rs={"gpt-4":"gpt-4o","gpt-4-turbo":"gpt-4o-mini","gpt-4o":"gpt-4o-mini","gpt-4.1":"gpt-4.1-mini","cla\
874
- 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 am(t){return Object.keys(t).sort((e,n)=>n.length-e.
875
- length||e.localeCompare(n))}function $u(t,e=rs){if(!t)return null;let n=t.lastIndexOf("/"),r=n>=0?t.slice(0,n+1):"",o=n>=0?t.slice(n+1):t,i=e[t]??e[o]??cm(o,e);return !i||i===o?null:r+i}function cm(t,e){
876
- for(let n of am(e))if(t.startsWith(n)&&t.charAt(n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var Ur=class{exploracion;estados=new Map;constructor(e={}){this.exploracion=Math.max(1,e.exploracion??20);}costeDeExploracion(e){return this.exploracion*Math.max(0,e)}estado(e){return this.estados.get(
877
- e)}decidir(e,n){let r=this.estados.get(e),o=um(r),i=r?.enrutadas??0,s=a=>a==null?"n/a":`${(a*100).toFixed(1)}%`;return r?.apagada?{enrutar:false,razon:`model cascade OFF for this workload: measured escal\
878
+ o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var is={"gpt-4":"gpt-4o","gpt-4-turbo":"gpt-4o-mini","gpt-4o":"gpt-4o-mini","gpt-4.1":"gpt-4.1-mini","cla\
879
+ ude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-5-sonnet":"claude-3-5-haiku"};function fm(t){return Object.keys(t).sort((e,n)=>n.length-e.length||e.localeCompare(n))}function Fu(t,e=is){
880
+ if(!t)return null;let n=t.lastIndexOf("/"),r=n>=0?t.slice(0,n+1):"",o=n>=0?t.slice(n+1):t,i=e[t]??e[o]??mm(o,e);return !i||i===o?null:r+i}function mm(t,e){for(let n of fm(e))if(t.startsWith(n)&&t.charAt(
881
+ n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var Hr=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(
882
+ e)}decidir(e,n){let r=this.estados.get(e),o=hm(r),i=r?.enrutadas??0,s=a=>a==null?"n/a":`${(a*100).toFixed(1)}%`;return r?.apagada?{enrutar:false,razon:`model cascade OFF for this workload: measured escal\
878
883
  ation rate ${s(o)} is at or above the ${s(n.equilibrio)} break-even, so routing was costing money`,observada:o,muestras:i}:i<this.exploracion?{enrutar:true,razon:`measuring this workload (${i}/${this.exploracion}\
879
884
  ); the escalation rate is only observable on requests that were actually routed`,observada:o,muestras:i}:o!=null&&o<n.equilibrio?{enrutar:true,razon:`measured escalation rate ${s(o)} stays under the ${s(
880
885
  n.equilibrio)} break-even (this is a MONEY check, not a quality one)`,observada:o,muestras:i}:(r&&(r.apagada=true),{enrutar:false,razon:`model cascade OFF for this workload: measured escalation rate ${s(o)}\
881
886
  is at or above the ${s(n.equilibrio)} break-even, so routing was costing money`,observada:o,muestras:i})}registrar(e,n){let r=this.estados.get(e)??{enrutadas:0,escaladas:0,apagada:false};r.enrutadas+=1,
882
- n&&(r.escaladas+=1),this.estados.set(e,r);}};function um(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var lm=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function dm(t){return t?os(t)?"value-constrained":"structural":"none"}function os(t,e=0){if(e>12)return false;let n=t;
883
- for(let r of lm)if(n[r]!==void 0)return true;if(t.properties){for(let r of Object.values(t.properties))if(os(r,e+1))return true}return !!(t.items&&os(t.items,e+1))}function Bu(t){let e=dm(t.schema),n=(t.tools??
887
+ n&&(r.escaladas+=1),this.estados.set(e,r);}};function hm(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var gm=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function bm(t){return t?ss(t)?"value-constrained":"structural":"none"}function ss(t,e=0){if(e>12)return false;let n=t;
888
+ for(let r of gm)if(n[r]!==void 0)return true;if(t.properties){for(let r of Object.values(t.properties))if(ss(r,e+1))return true}return !!(t.items&&ss(t.items,e+1))}function zu(t){let e=bm(t.schema),n=(t.tools??
884
889
  []).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\
885
890
  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\
886
891
  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 \
887
- content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function is(t){let e=[];if(e.push("non-empty"),t.texto.trim()==="")return {acepta:false,
892
+ content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function as(t){let e=[];if(e.push("non-empty"),t.texto.trim()==="")return {acepta:false,
888
893
  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 \
889
894
  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\
890
895
  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,
891
- motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=de(n,t.schema);return r.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
892
- acepta:false,motivo:`the cheap model's answer does not satisfy the output contract (${r.errors.slice(0,3).map(i=>`${i.path}: ${i.message}`).join("; ")})`,comprobaciones:e}}function Fu(t,e){let n,r;try{n=
893
- JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=Hr(n),i=Hr(r);return o.length===0&&i.length===0?{divergen:false,motivo:"no comparab\
894
- le facts (free prose only)"}:fm(o,i)?{divergen:false,motivo:"the hard values agree"}:{divergen:true,motivo:"both answers satisfy the contract but disagree on at least one hard value; this is the signature \
895
- of a false valid \u2014 it is a reason to look, never a verdict"}}var pm=40;function Hr(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\
896
- an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=pm&&n.push(`s:${r.toLowerCase()}`);}else if(Array.isArray(t))for(let r of t)Hr(r,e+1,n);else if(t&&typeof t=="objec\
897
- t")for(let r of Object.keys(t).sort())Hr(t[r],e+1,n);return n.sort()}function fm(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 zu="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\
898
- , because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function mm(t){if(t<=0)return "";let e=zu;for(;e.length<t;)e+=zu;return e.slice(
899
- 0,t)}function hm(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 ss(t){if(t.enum&&t.enum.length>0)return {valor:hm(t.enum)};switch(t.type??(t.properties?
900
- "object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:mm(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?
901
- {valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=ss(t.items);return n?{valor:Array.from({length:t.maxItems},()=>n.valor)}:void 0}case "ob\
902
- ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let i=ss(o);if(!i)return;n[r]=i.valor;}return {valor:n}}default:return}}function gm(t){let e=ss(
903
- t);return e?JSON.stringify(e.valor):null}function qu(t,e){let n=gm(t);return n===null?null:e(n)}var Wr=16,Vu=64,bm=8,vm="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 Uu(t,e,n,r={}){
904
- let o=r.minimumSavingsTokens??bm,i;try{if(us(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};i=ds(t,0);}catch(O){return {applied:false,reason:O instanceof
896
+ motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=pe(n,t.schema);return r.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
897
+ acepta:false,motivo:`the cheap model's answer does not satisfy the output contract (${r.errors.slice(0,3).map(i=>`${i.path}: ${i.message}`).join("; ")})`,comprobaciones:e}}function qu(t,e){let n,r;try{n=
898
+ JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=Wr(n),i=Wr(r);return o.length===0&&i.length===0?{divergen:false,motivo:"no comparab\
899
+ le facts (free prose only)"}:ym(o,i)?{divergen:false,motivo:"the hard values agree"}:{divergen:true,motivo:"both answers satisfy the contract but disagree on at least one hard value; this is the signature \
900
+ of a false valid \u2014 it is a reason to look, never a verdict"}}var vm=40;function Wr(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\
901
+ an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=vm&&n.push(`s:${r.toLowerCase()}`);}else if(Array.isArray(t))for(let r of t)Wr(r,e+1,n);else if(t&&typeof t=="objec\
902
+ t")for(let r of Object.keys(t).sort())Wr(t[r],e+1,n);return n.sort()}function ym(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 Vu="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\
903
+ , because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function km(t){if(t<=0)return "";let e=Vu;for(;e.length<t;)e+=Vu;return e.slice(
904
+ 0,t)}function xm(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 cs(t){if(t.enum&&t.enum.length>0)return {valor:xm(t.enum)};switch(t.type??(t.properties?
905
+ "object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:km(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?
906
+ {valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=cs(t.items);return n?{valor:Array.from({length:t.maxItems},()=>n.valor)}:void 0}case "ob\
907
+ ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let i=cs(o);if(!i)return;n[r]=i.valor;}return {valor:n}}default:return}}function wm(t){let e=cs(
908
+ t);return e?JSON.stringify(e.valor):null}function Uu(t,e){let n=wm(t);return n===null?null:e(n)}var Jr=16,Hu=64,Sm=8,Tm="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 Wu(t,e,n,r={}){
909
+ let o=r.minimumSavingsTokens??Sm,i;try{if(ds(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};i=fs(t,0);}catch(E){return {applied:false,reason:E instanceof
905
910
  RangeError?"schema too deep or cyclic":"schema could not be compacted"}}if(i.renamed===0&&i.coded===0)return {applied:false,reason:"nothing to compact (no renameable keys, no codeable enums)"};let s=i.node;
906
- if(!s)return {applied:false,reason:"nothing to compact"};let a=O=>Vt(O,s,true),c=O=>Vt(O,s,false),u=Tm(t),l=ym(t,i.compact,s,u);if(!l.ok)return {applied:false,reason:l.reason};let d=e(JSON.stringify(t)),p=e(JSON.stringify(
907
- i.compact)),h=d-p,m=Number.POSITIVE_INFINITY;for(let O of u){let R=e(JSON.stringify(O))-e(JSON.stringify(a(O)));R<m&&(m=R);}Number.isFinite(m)||(m=0);let g=O=>O/1e3*n.inputPer1k,f=O=>O/1e3*n.outputPer1k,
911
+ if(!s)return {applied:false,reason:"nothing to compact"};let a=E=>Vt(E,s,true),c=E=>Vt(E,s,false),u=Im(t),l=Cm(t,i.compact,s,u);if(!l.ok)return {applied:false,reason:l.reason};let d=e(JSON.stringify(t)),p=e(JSON.stringify(
912
+ i.compact)),h=d-p,m=Number.POSITIVE_INFINITY;for(let E of u){let S=e(JSON.stringify(E))-e(JSON.stringify(a(E)));S<m&&(m=S);}Number.isFinite(m)||(m=0);let g=E=>E/1e3*n.inputPer1k,f=E=>E/1e3*n.outputPer1k,
908
913
  v=g(o),b=n.outputPer1k>0?(o-h)*n.inputPer1k/n.outputPer1k:Number.NEGATIVE_INFINITY,y=Number.isFinite(b)?b.toFixed(1):"any",k=n.inputPer1k>0?`${(n.outputPer1k/n.inputPer1k).toFixed(1)}x`:"more than",T=r.
909
914
  evidencia;if(T==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\
910
- e model, not of the schema: ${vm}. Here the compact contract saves ${h} input tokens and output is billed ${k} input, so it only pays while the output delta stays above ${y} tokens. Measure yours (ben\
911
- chmarks/ab-live.ts) and pass it in`};let w=T.deltaTokens;if(w<0)return {applied:false,reason:`the measured output delta is ${w} tokens: this model writes MORE from a compact contract (${T.procedencia}). T\
912
- he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${k} input, so no schema is big enough to buy it back`};let P=g(h)+f(w),x=n.inputPer1k>0?P*1e3/
913
- n.inputPer1k:h,S=`+${w} tokens (${w>0?"the model wrote LESS":"no measured change"}), ${T.procedencia}`;return P<v?{applied:false,reason:`net saving $${P.toFixed(9)}/request is below the floor of ${o} inp\
914
- ut tokens ($${v.toFixed(9)}): the compact contract saves ${h} input tokens and the measured output delta is ${S}; break-even at ${y}`}:{applied:true,reason:`net saving $${P.toFixed(9)}/request (${x.toFixed(
915
- 1)} input tokens equivalent): the compact contract saves ${h} input tokens and the measured output delta is ${S}; break-even at ${y}`,plan:{compactSchema:i.compact,expand:c,compact:a,renamedKeys:i.renamed,
916
- codedEnumValues:i.coded,schemaTokensOriginal:d,schemaTokensCompact:p,modelledShapeSavingTokens:m,measuredOutputDeltaTokens:w,outputDeltaProvenance:T.procedencia,breakEvenOutputDeltaTokens:b,netSavingUsd:P}}}
917
- function ym(t,e,n,r){for(let o of r){if(!de(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let i=Vt(o,n,true);if(!de(i,e).valid)return {
918
- ok:false,reason:"compact witness does not validate against the compact schema"};if(!ls(Vt(i,n,false),o))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function Hu(t){return t.type==="ob\
919
- ject"||t.type==null&&t.properties!=null}function Wu(t){return t.type==="array"||t.type==null&&t.items!=null}function km(t){let e=t.enum;return !e||e.length===0||e.length>Vu||!e.every(n=>typeof n=="stri\
920
- ng")?null:e}function ds(t,e){if(e>Wr)throw new RangeError("schema too deep");let n=km(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=Ju(n,true);if(!r)return {compact:t,renamed:0,
915
+ e model, not of the schema: ${Tm}. Here the compact contract saves ${h} input tokens and output is billed ${k} input, so it only pays while the output delta stays above ${y} tokens. Measure yours (ben\
916
+ chmarks/ab-live.ts) and pass it in`};let x=T.deltaTokens;if(x<0)return {applied:false,reason:`the measured output delta is ${x} tokens: this model writes MORE from a compact contract (${T.procedencia}). T\
917
+ he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${k} input, so no schema is big enough to buy it back`};let R=g(h)+f(x),D=n.inputPer1k>0?R*1e3/
918
+ n.inputPer1k:h,I=`+${x} tokens (${x>0?"the model wrote LESS":"no measured change"}), ${T.procedencia}`;return R<v?{applied:false,reason:`net saving $${R.toFixed(9)}/request is below the floor of ${o} inp\
919
+ ut tokens ($${v.toFixed(9)}): the compact contract saves ${h} input tokens and the measured output delta is ${I}; break-even at ${y}`}:{applied:true,reason:`net saving $${R.toFixed(9)}/request (${D.toFixed(
920
+ 1)} input tokens equivalent): the compact contract saves ${h} input tokens and the measured output delta is ${I}; break-even at ${y}`,plan:{compactSchema:i.compact,expand:c,compact:a,renamedKeys:i.renamed,
921
+ codedEnumValues:i.coded,schemaTokensOriginal:d,schemaTokensCompact:p,modelledShapeSavingTokens:m,measuredOutputDeltaTokens:x,outputDeltaProvenance:T.procedencia,breakEvenOutputDeltaTokens:b,netSavingUsd:R}}}
922
+ function Cm(t,e,n,r){for(let o of r){if(!pe(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let i=Vt(o,n,true);if(!pe(i,e).valid)return {
923
+ ok:false,reason:"compact witness does not validate against the compact schema"};if(!ps(Vt(i,n,false),o))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function Ju(t){return t.type==="ob\
924
+ ject"||t.type==null&&t.properties!=null}function Ku(t){return t.type==="array"||t.type==null&&t.items!=null}function Em(t){let e=t.enum;return !e||e.length===0||e.length>Hu||!e.every(n=>typeof n=="stri\
925
+ ng")?null:e}function fs(t,e){if(e>Jr)throw new RangeError("schema too deep");let n=Em(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=Gu(n,true);if(!r)return {compact:t,renamed:0,
921
926
  coded:0};let o=[...r].filter(([s,a])=>s!==a).length;if(o===0)return {compact:t,renamed:0,coded:0};let i=new Map;for(let[s,a]of r)i.set(a,s);return {compact:{...t,enum:n.map(s=>r.get(s))},node:{enumFwd:r,
922
- enumBack:i},renamed:0,coded:o}}return Hu(t)?xm(t,e):Wu(t)?wm(t,e):{compact:t,renamed:0,coded:0}}function xm(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};
923
- let r=0,o=0,i=new Map,s=new Map;for(let[p,h]of n){let m=ds(h,e+1);s.set(p,m.compact),m.node&&i.set(p,m.node),r+=m.renamed,o+=m.coded;}let a=null;t.additionalProperties===false&&(a=Ju(n.map(([p])=>p),false));
927
+ enumBack:i},renamed:0,coded:o}}return Ju(t)?Pm(t,e):Ku(t)?Rm(t,e):{compact:t,renamed:0,coded:0}}function Pm(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};
928
+ let r=0,o=0,i=new Map,s=new Map;for(let[p,h]of n){let m=fs(h,e+1);s.set(p,m.compact),m.node&&i.set(p,m.node),r+=m.renamed,o+=m.coded;}let a=null;t.additionalProperties===false&&(a=Gu(n.map(([p])=>p),false));
924
929
  let c={};for(let[p]of n)c[a?.get(p)??p]=s.get(p);let u={...t,properties:c};t.required&&(u.required=t.required.map(p=>a?.get(p)??p));let l={};if(a){let p=new Map;for(let[m,g]of a)p.set(g,m);let h=false;for(let[
925
- m,g]of a)m!==g&&(h=true);if(h){l.keysFwd=a,l.keysBack=p;for(let[m,g]of a)m!==g&&(r+=1);}}i.size>0&&(l.props=i);let d=!l.keysFwd&&!l.props;return {compact:u,...d?{}:{node:l},renamed:r,coded:o}}function wm(t,e){
926
- if(!t.items)return {compact:t,renamed:0,coded:0};let n=ds(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function Ju(t,e){let n=[
930
+ m,g]of a)m!==g&&(h=true);if(h){l.keysFwd=a,l.keysBack=p;for(let[m,g]of a)m!==g&&(r+=1);}}i.size>0&&(l.props=i);let d=!l.keysFwd&&!l.props;return {compact:u,...d?{}:{node:l},renamed:r,coded:o}}function Rm(t,e){
931
+ if(!t.items)return {compact:t,renamed:0,coded:0};let n=fs(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function Gu(t,e){let n=[
927
932
  ...t].sort(),r=new Set,o=new Map;n.forEach((s,a)=>{let c=e?s.toUpperCase():s,u=s;for(let l=1;l<s.length;l++){let d=c.slice(0,l);if(!r.has(d)){u=d;break}}if(u===s){let l=a.toString(36);l.length<s.length&&
928
933
  !r.has(l)&&(u=l);}r.add(u),o.set(s,u);});let i=new Set(t);for(let[s,a]of o)if(a!==s&&i.has(a))return null;return o}function Vt(t,e,n){let r=n?e.enumFwd:e.enumBack;if(r&&typeof t=="string")return r.get(t)??
929
- t;if(e.items&&Array.isArray(t))return t.map(i=>Vt(i,e.items,n));let o=n?e.keysFwd:e.keysBack;if((o||e.props)&&Sm(t)){let i={};for(let[s,a]of Object.entries(t)){let c=o?.get(s)??s,u=n?s:c,l=e.props?.get(
930
- u);i[c]=l?Vt(a,l,n):a;}return i}return t}function Sm(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Tm(t){let e=Math.min(Vu,Math.max(1,as(t,0))),n=[];for(let r=0;r<e;r++)n.push(cs(t,
931
- r,0));return n}function as(t,e){if(e>Wr)return 0;let n=t.enum?.length??0;for(let r of Object.values(t.properties??{}))n=Math.max(n,as(r,e+1));return t.items&&(n=Math.max(n,as(t.items,e+1))),n}function cs(t,e,n){
932
- if(n>Wr)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(Hu(t)){let r={};for(let[o,i]of Object.entries(t.properties??{}))r[o]=cs(i,e,n+1);return r}if(Wu(t)){if(t.maxItems===
933
- 0)return [];let r=Math.max(1,t.minItems??1),o=t.maxItems!=null?Math.min(r,t.maxItems):r,i=t.items;return Array.from({length:o},()=>i?cs(i,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";
934
+ t;if(e.items&&Array.isArray(t))return t.map(i=>Vt(i,e.items,n));let o=n?e.keysFwd:e.keysBack;if((o||e.props)&&Dm(t)){let i={};for(let[s,a]of Object.entries(t)){let c=o?.get(s)??s,u=n?s:c,l=e.props?.get(
935
+ u);i[c]=l?Vt(a,l,n):a;}return i}return t}function Dm(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Im(t){let e=Math.min(Hu,Math.max(1,us(t,0))),n=[];for(let r=0;r<e;r++)n.push(ls(t,
936
+ r,0));return n}function us(t,e){if(e>Jr)return 0;let n=t.enum?.length??0;for(let r of Object.values(t.properties??{}))n=Math.max(n,us(r,e+1));return t.items&&(n=Math.max(n,us(t.items,e+1))),n}function ls(t,e,n){
937
+ if(n>Jr)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(Ju(t)){let r={};for(let[o,i]of Object.entries(t.properties??{}))r[o]=ls(i,e,n+1);return r}if(Ku(t)){if(t.maxItems===
938
+ 0)return [];let r=Math.max(1,t.minItems??1),o=t.maxItems!=null?Math.min(r,t.maxItems):r,i=t.items;return Array.from({length:o},()=>i?ls(i,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";
934
939
  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===
935
- "integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function us(t,e){if(e>Wr)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.
936
- values(t.properties??{}))if(us(n,e+1))return true;return !!(t.items&&us(t.items,e+1))}function ls(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.
937
- isArray(t),r=Array.isArray(e);if(n||r){if(!n||!r||t.length!==e.length)return false;for(let s=0;s<t.length;s++)if(!ls(t[s],e[s]))return false;return true}let o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)
938
- return false;for(let s of o)if(!Object.prototype.hasOwnProperty.call(e,s)||!ls(t[s],e[s]))return false;return true}var Cm="2026-08-14",Ku={"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 \
939
- enums)",pares:8}},Em=yo(Ku);function Pm(t){return vo(Ku,Em,t)}var Jr=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&&
940
+ "integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function ds(t,e){if(e>Jr)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.
941
+ values(t.properties??{}))if(ds(n,e+1))return true;return !!(t.items&&ds(t.items,e+1))}function ps(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.
942
+ isArray(t),r=Array.isArray(e);if(n||r){if(!n||!r||t.length!==e.length)return false;for(let s=0;s<t.length;s++)if(!ps(t[s],e[s]))return false;return true}let o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)
943
+ return false;for(let s of o)if(!Object.prototype.hasOwnProperty.call(e,s)||!ps(t[s],e[s]))return false;return true}var _m="2026-08-14",Zu={"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 \
944
+ enums)",pares:8}},Am=ko(Zu);function Om(t){return yo(Zu,Am,t)}var Kr=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&&
940
945
  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,
941
- origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let i=Pm(e);return i?{deltaTokens:i.deltaTokens,origen:"catalogue",procedencia:`measured by Bi\
942
- Velio on ${e} (${Cm}, ${i.pares} paired reps, ${i.contrato}, ${i.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};var fs="[BiVelio Savings: an older tool result was trimmed here to lower the cost; the most recent results travel in full.]",Rm=new TextEncoder;function Dm(t){return Rm.encode(t).length}function Im(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;
943
- r=ps(o);}catch{r=n;}return `${t} ${r}`}function ps(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(ps).join(",")}]`:`{${Object.keys(t).sort().map(n=>`${JSON.stringify(
944
- n)}:${ps(t[n])}`).join(",")}}`}function Gu(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=[],
945
- 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,p=l.toolCallId?e.get(l.toolCallId):void 0,h=Im(d,p);h!==null&&
946
+ origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let i=Om(e);return i?{deltaTokens:i.deltaTokens,origen:"catalogue",procedencia:`measured by Bi\
947
+ Velio on ${e} (${_m}, ${i.pares} paired reps, ${i.contrato}, ${i.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};var hs="[BiVelio Savings: an older tool result was trimmed here to lower the cost; the most recent results travel in full.]",Mm=new TextEncoder;function Lm(t){return Mm.encode(t).length}function jm(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;
948
+ r=ms(o);}catch{r=n;}return `${t} ${r}`}function ms(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(ms).join(",")}]`:`{${Object.keys(t).sort().map(n=>`${JSON.stringify(
949
+ n)}:${ms(t[n])}`).join(",")}}`}function Yu(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=[],
950
+ 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,p=l.toolCallId?e.get(l.toolCallId):void 0,h=jm(d,p);h!==null&&
946
951
  o.set(u,h);}let i=r.length?r[r.length-1]:-1,s=new Map;for(let u of r){let l=o.get(u);if(l===void 0)continue;let d=s.get(l);(d===void 0||u>d)&&s.set(l,u);}let a=[],c=0;for(let u of r){if(u===i)continue;let l=o.
947
- get(u);if(l===void 0||s.get(l)===u)continue;let d=Dm(t[u].content);d<1024||(a.push(u),c+=d);}return {indices:a,bytesOriginales:c}}function Zu(t,e){if(e.length===0)return t;let n=new Set(e);return t.map(
948
- (r,o)=>n.has(o)?{...r,content:fs}:r)}function Kr(t,e){if(e?.cacheTier)return e.cacheTier;let n=t.toLowerCase(),r=n.indexOf("/"),o=r>0?n.slice(0,r):"",i=r>=0?n.slice(r+1):n;return o==="openai"||o==="azure-openai"?Hi:o==="anthropic"?Wi(i):
949
- o==="google"||o==="google-vertex"?Ji:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(i)?Hi:i.startsWith("claude")?Wi(i):i.startsWith("gemini")?Ji:Pu}function Yu(t){let e=t.prefix!=null,n=Ki({originalTokens:t.originalTokens,
952
+ get(u);if(l===void 0||s.get(l)===u)continue;let d=Lm(t[u].content);d<1024||(a.push(u),c+=d);}return {indices:a,bytesOriginales:c}}function Qu(t,e){if(e.length===0)return t;let n=new Set(e);return t.map(
953
+ (r,o)=>n.has(o)?{...r,content:hs}:r)}function Gr(t,e){if(e?.cacheTier)return e.cacheTier;let n=t.toLowerCase(),r=n.indexOf("/"),o=r>0?n.slice(0,r):"",i=r>=0?n.slice(r+1):n;return o==="openai"||o==="azure-openai"?Ji:o==="anthropic"?Ki(i):
954
+ o==="google"||o==="google-vertex"?Gi:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(i)?Ji:i.startsWith("claude")?Ki(i):i.startsWith("gemini")?Gi:Du}function Xu(t){let e=t.prefix!=null,n=Zi({originalTokens:t.originalTokens,
950
955
  compressedTokens:t.compressedTokens,stablePrefixTokens:t.prefix?.stableTokens??0,prefixHitRate:t.prefix?.hitRate??0,tier:t.tier,...t.compressorCostTokens!=null?{compressorCostTokens:t.compressorCostTokens}:
951
956
  {}});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.
952
- 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 Xu(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),
957
+ 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 tl(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),
953
958
  i=r+e(t.promptTokens+t.esquemasDeLaSegunda)+n(t.salidaFinal),s=o-i,a=r,c=s>0&&s>=a,u;return s<=0?u=`discovery costs more than it saves: the prompt (${t.promptTokens} tokens) is paid twice and the sche\
954
959
  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\
955
960
  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,
956
- costeDeDosLlamadas:i,ganancia:s,perdidaSiDegrada:a,razon:u}}function el(t){let n=(t.description??(Array.isArray(t.intents)?t.intents.join("; "):"")).trim().split(/\r?\n/,1)[0]??"",r=n.length>Qu?n.slice(
957
- 0,Qu-1).trimEnd()+"\u2026":n;return {id:t.id,intents:t.intents,risk:t.risk,...r?{description:r}:{}}}var Qu=200;function tl(t,e,n){let r=new Map(e.map(c=>[c.id,c])),o=[],i=[],s=new Set;for(let c of t){let u=r.
958
- get(c);if(!u){i.push(c);continue}o.includes(u.id)||(o.push(u.id),u.risk==="read"&&s.size<Math.max(0,n)&&s.add(u.id));}return {tools:e.filter(c=>c.risk!=="read"||s.has(c.id)),reconocidos:o,ignorados:i}}function nl(t,e){
959
- let n=0,r=[];for(let o of t)o.risk==="read"?r.push(o.tokens):n+=o.tokens;r.sort((o,i)=>i-o);for(let o of r.slice(0,Math.max(0,e)))n+=o;return n}var Am=2;function ms(t){return Y(he({messages:t.messages,structuredData:t.structuredData??null,tools:t.tools??[],schema:t.response?.schema??null}))}function rl(t){return t.temperature===0}var it=t=>typeof t==
960
- "number"&&Number.isInteger(t)&&t>=0;function Om(t,e){if(it(t.reasoningTokens)){if(!e)return t.reasoningTokens;if(it(e.reasoningTokens))return t.reasoningTokens+e.reasoningTokens}}function ol(t){if(t.contadorSimulado)
961
- return "simulated-provider";if(t.origen==="no-oficial")return "unofficial-origin";let e=t.usoPrimario;if(!e||e.complete===false||!it(e.inputTokens)||e.inputTokens<=0||!it(e.outputTokens))return "no-usage";let n=t.
962
- usoReparacion;if(n&&(n.complete===false||!it(n.outputTokens)))return "no-usage";if(t.eliminatedInput!==0||t.compressedInput!==0||t.elididoLocal!==0||Math.abs(t.sentLocalSinSondeo-t.baselineInput)>Am)return "\
961
+ costeDeDosLlamadas:i,ganancia:s,perdidaSiDegrada:a,razon:u}}function nl(t){let n=(t.description??(Array.isArray(t.intents)?t.intents.join("; "):"")).trim().split(/\r?\n/,1)[0]??"",r=n.length>el?n.slice(
962
+ 0,el-1).trimEnd()+"\u2026":n;return {id:t.id,intents:t.intents,risk:t.risk,...r?{description:r}:{}}}var el=200;function rl(t,e,n){let r=new Map(e.map(c=>[c.id,c])),o=[],i=[],s=new Set;for(let c of t){let u=r.
963
+ get(c);if(!u){i.push(c);continue}o.includes(u.id)||(o.push(u.id),u.risk==="read"&&s.size<Math.max(0,n)&&s.add(u.id));}return {tools:e.filter(c=>c.risk!=="read"||s.has(c.id)),reconocidos:o,ignorados:i}}function ol(t,e){
964
+ let n=0,r=[];for(let o of t)o.risk==="read"?r.push(o.tokens):n+=o.tokens;r.sort((o,i)=>i-o);for(let o of r.slice(0,Math.max(0,e)))n+=o;return n}var $m=2;function gs(t){return Y(ge({messages:t.messages,structuredData:t.structuredData??null,tools:t.tools??[],schema:t.response?.schema??null}))}function il(t){return t.temperature===0}var st=t=>typeof t==
965
+ "number"&&Number.isInteger(t)&&t>=0;function Bm(t,e){if(st(t.reasoningTokens)){if(!e)return t.reasoningTokens;if(st(e.reasoningTokens))return t.reasoningTokens+e.reasoningTokens}}function sl(t){if(t.contadorSimulado)
966
+ return "simulated-provider";if(t.origen==="no-oficial")return "unofficial-origin";let e=t.usoPrimario;if(!e||e.complete===false||!st(e.inputTokens)||e.inputTokens<=0||!st(e.outputTokens))return "no-usage";let n=t.
967
+ usoReparacion;if(n&&(n.complete===false||!st(n.outputTokens)))return "no-usage";if(t.eliminatedInput!==0||t.compressedInput!==0||t.elididoLocal!==0||Math.abs(t.sentLocalSinSondeo-t.baselineInput)>$m)return "\
963
968
  layer-changed-request";if(t.codebookAplicado)return "codebook";if(t.tokensDelSondeo!==0||t.sondeoAplicado)return "tool-discovery";if(t.busquedaNativa===true)return "native-tool-search";if(t.hayEsquema&&(!t.
964
969
  esquemaNativo||t.esquemaPorPrompt))return "schema-in-prompt";if(t.hayEsquema&&!t.esquemaEnFormatoNativo)return "schema-not-verbatim";if(t.hayEsquema&&!t.esquemaEstricto)return "schema-not-strict";if(t.modeloServido!==
965
- t.modeloPedido)return "cheaper-model-served";if(!t.cacheable)return "not-cacheable";let r=ei(t.tierServido),o=r?.conDescuento&&r.factor!=null&&r.factor>0&&r.factor<1?r.factor:void 0,i=Om(e,n);return {v:2,
970
+ t.modeloPedido)return "cheaper-model-served";if(!t.cacheable)return "not-cacheable";let r=ti(t.tierServido),o=r?.conDescuento&&r.factor!=null&&r.factor>0&&r.factor<1?r.factor:void 0,i=Bm(e,n);return {v:2,
966
971
  requestId:t.requestId,at:t.at,model:t.modeloPedido,inputTokens:e.inputTokens,outputTokens:n?Math.min(e.outputTokens,n.outputTokens):e.outputTokens,...o!==void 0?{tierFactor:o}:{},layerInsertions:Math.
967
- max(0,t.mensajesDeLaCapa)+Math.max(0,t.piezasDelAdaptador)+(t.hayEsquema?1:0),...i!==void 0?{reasoningTokens:i}:{},requestFingerprint:t.huella(),textSha256:Y(t.textoServido)}}var Gr=t=>typeof t=="stri\
968
- ng"&&t.length>0;function il(t){if(t==null||typeof t!="object")return "absent";let e=t.reference;if(e==null)return "absent";if(typeof e!="object"||Array.isArray(e))return "malformed";let n=e,r=n.tierFactor,
969
- o=n.reasoningTokens;return n.v===2&&typeof n.inputTokens=="number"&&Number.isInteger(n.inputTokens)&&n.inputTokens>0&&it(n.outputTokens)&&typeof n.at=="number"&&Number.isFinite(n.at)&&(r===void 0||typeof r==
970
- "number"&&r>0&&r<1)&&it(n.layerInsertions)&&(o===void 0||it(o))&&Gr(n.requestId)&&Gr(n.model)&&Gr(n.requestFingerprint)&&Gr(n.textSha256)?{v:2,requestId:n.requestId,at:n.at,model:n.model,inputTokens:n.
972
+ max(0,t.mensajesDeLaCapa)+Math.max(0,t.piezasDelAdaptador)+(t.hayEsquema?1:0),...i!==void 0?{reasoningTokens:i}:{},requestFingerprint:t.huella(),textSha256:Y(t.textoServido)}}var Zr=t=>typeof t=="stri\
973
+ ng"&&t.length>0;function al(t){if(t==null||typeof t!="object")return "absent";let e=t.reference;if(e==null)return "absent";if(typeof e!="object"||Array.isArray(e))return "malformed";let n=e,r=n.tierFactor,
974
+ o=n.reasoningTokens;return n.v===2&&typeof n.inputTokens=="number"&&Number.isInteger(n.inputTokens)&&n.inputTokens>0&&st(n.outputTokens)&&typeof n.at=="number"&&Number.isFinite(n.at)&&(r===void 0||typeof r==
975
+ "number"&&r>0&&r<1)&&st(n.layerInsertions)&&(o===void 0||st(o))&&Zr(n.requestId)&&Zr(n.model)&&Zr(n.requestFingerprint)&&Zr(n.textSha256)?{v:2,requestId:n.requestId,at:n.at,model:n.model,inputTokens:n.
971
976
  inputTokens,outputTokens:n.outputTokens,...r!==void 0?{tierFactor:r}:{},layerInsertions:n.layerInsertions,...o!==void 0?{reasoningTokens:o}:{},requestFingerprint:n.requestFingerprint,textSha256:n.textSha256,
972
- ...typeof n.cacheKey=="string"?{cacheKey:n.cacheKey}:{}}:"malformed"}function Mm(t,e){if(!e.determinista)return "sampled";if(e.salidaDelModelo!==void 0)return e.salidaDelModelo;if(t.reasoningTokens===void 0)
973
- return "reasoning-not-reported";if(t.reasoningTokens!==0)return "reasoning-reported"}function sl(t,e){if(e.textoServidoSha256!==t.textSha256)return {ok:false,reason:"witness"};if(e.claveLeida!==void 0&&t.cacheKey!==
977
+ ...typeof n.cacheKey=="string"?{cacheKey:n.cacheKey}:{}}:"malformed"}function Fm(t,e){if(!e.determinista)return "sampled";if(e.salidaDelModelo!==void 0)return e.salidaDelModelo;if(t.reasoningTokens===void 0)
978
+ return "reasoning-not-reported";if(t.reasoningTokens!==0)return "reasoning-reported"}function cl(t,e){if(e.textoServidoSha256!==t.textSha256)return {ok:false,reason:"witness"};if(e.claveLeida!==void 0&&t.cacheKey!==
974
979
  e.claveLeida)return {ok:false,reason:"witness"};if(t.model!==e.modeloPedido||e.modeloServido!==e.modeloPedido)return {ok:false,reason:"model-mismatch"};let n=e.ahoraMs-t.at;if(!(n>=-3e5&&n<=2592e6))return {ok:false,
975
980
  reason:"expired"};if(e.huella!==t.requestFingerprint)return {ok:false,reason:"different-request"};if(!e.calidadOk)return {ok:false,reason:"quality"};let r=e.precio,o=r?.cachedInputPer1k;if(!r||typeof o!="numb\
976
981
  er"||!Number.isFinite(o)||!(o>0)||!Number.isFinite(r.inputPer1k)||o>r.inputPer1k||typeof r.outputPer1k!="number"||!Number.isFinite(r.outputPer1k)||r.outputPer1k<0)return {ok:false,reason:"no-cached-price"};
977
982
  let i=t.inputTokens-8*t.layerInsertions;if(!(i>0))return {ok:false,reason:"no-credit"};let s=typeof e.topeDeSalida=="number"&&Number.isFinite(e.topeDeSalida)?Math.max(0,e.topeDeSalida):Number.POSITIVE_INFINITY,
978
- a=Mm(t,e),c=a===void 0?Math.floor(.95*Math.min(t.outputTokens,s)):0,u=Math.min(1,t.tierFactor??1,e.diferible?za:1);return {ok:true,...a!==void 0?{outputNotCredited:a}:{},credit:{requestId:t.requestId,at:t.
979
- at,inputTokens:t.inputTokens,outputTokens:t.outputTokens,creditedInputTokens:i,creditedOutputTokens:c,cachedInputPer1k:o,outputPer1k:r.outputPer1k,tierFactor:u}}}var wn={done:true,value:void 0},Sn=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){
983
+ a=Fm(t,e),c=a===void 0?Math.floor(.95*Math.min(t.outputTokens,s)):0,u=Math.min(1,t.tierFactor??1,e.diferible?Va:1);return {ok:true,...a!==void 0?{outputNotCredited:a}:{},credit:{requestId:t.requestId,at:t.
984
+ at,inputTokens:t.inputTokens,outputTokens:t.outputTokens,creditedInputTokens:i,creditedOutputTokens:c,cachedInputPer1k:o,outputPer1k:r.outputPer1k,tierFactor:u}}}var Sn={done:true,value:void 0},Tn=class{handle;sumidero;now;inicio;controlador=new AbortController;resolver;rechazar;cola=[];esperas=[];cerrada=false;errorPendiente=null;consumidorSalio=false;iterado=false;_abortado=false;vivo=false;proveedorTerminado=false;terminado=false;primerEventoAt;quitarEscucha;constructor(e,n){
980
985
  this.now=e,this.inicio=e();let r,o,i=new Promise((a,c)=>{r=a,o=c;});i.catch(()=>{}),this.resolver=r,this.rechazar=o;let s=this;if(this.sumidero={senal:this.controlador.signal,texto(a){s.recibirTexto(a);},
981
986
  proveedorTermino(){s.proveedorTerminado=true;},sirvioEnVivo:false},this.handle={result:i,abort:a=>this.abort(a),[Symbol.asyncIterator]:()=>this.iterador()},n)if(n.aborted)this.abort(n.reason);else {let a=()=>this.
982
987
  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.
@@ -985,54 +990,54 @@ terminado)return;let r=e.toolCalls?.length??0,o=this.primerEventoAt??(n.vivo&&r>
985
990
  encolar({type:"tool_call",call:a});this.encolar({type:"done",result:s});}this.cerrar(),this.acabar();}fallar(e){this.terminado||(this.rechazar(e),this._abortado?this.cerrar():this.fallarCola(e),this.acabar());}acabar(){
986
991
  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.
987
992
  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)
988
- 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(wn);}fallarCola(e){this.cerrada=true;let[n,...r]=this.
989
- esperas.splice(0);if(n){n.reject(e);for(let o of r)o.resolve(wn);}else this.errorPendiente={valor:e};}siguiente(){if(this.consumidorSalio)return Promise.resolve(wn);let e=this.cola.shift();if(e)return Promise.
990
- 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(wn):new Promise((n,r)=>{this.esperas.
993
+ 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(Sn);}fallarCola(e){this.cerrada=true;let[n,...r]=this.
994
+ esperas.splice(0);if(n){n.reject(e);for(let o of r)o.resolve(Sn);}else this.errorPendiente={valor:e};}siguiente(){if(this.consumidorSalio)return Promise.resolve(Sn);let e=this.cola.shift();if(e)return Promise.
995
+ 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(Sn):new Promise((n,r)=>{this.esperas.
991
996
  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(),
992
- this.consumidorSalio=true,this.cola.length=0,Promise.resolve(wn))}}};function Lm(t,e){switch(t){case "deterministic":return "deterministic";case "exact":return "exact_cache";case "semantic":return "semantic_cache";case "singleflight":return "coalesced";default:return e?.origen===
993
- "fail_open"?"fail_open":"provider"}}function jm(t){if(!t||t.mode!=="shadow"&&t.mode!=="on")return;if(t.mode==="shadow")return {mode:"shadow",gate:t.verifier,outcome:"not_applied",...t.divergedOnSample!==
994
- void 0?{sampleDiverged:t.divergedOnSample}:{}};let e=t.servedModel!==t.requestedModel?"accepted":t.escalated===true?"escalated":"not_routed";return {mode:"on",gate:t.verifier,outcome:e}}function al(t){let e=t.
995
- hechos,n=Lm(t.cacheResult,e),r={source:n};if(t.hayEsquema)if(t.structurallyValid===null)r.schema={outcome:"not_applicable",decodeTimeConstraint:t.backend!=="none",errorCount:0};else {let i=e?.validacion,
997
+ this.consumidorSalio=true,this.cola.length=0,Promise.resolve(Sn))}}};function zm(t,e){switch(t){case "deterministic":return "deterministic";case "exact":return "exact_cache";case "semantic":return "semantic_cache";case "singleflight":return "coalesced";default:return e?.origen===
998
+ "fail_open"?"fail_open":"provider"}}function qm(t){if(!t||t.mode!=="shadow"&&t.mode!=="on")return;if(t.mode==="shadow")return {mode:"shadow",gate:t.verifier,outcome:"not_applied",...t.divergedOnSample!==
999
+ void 0?{sampleDiverged:t.divergedOnSample}:{}};let e=t.servedModel!==t.requestedModel?"accepted":t.escalated===true?"escalated":"not_routed";return {mode:"on",gate:t.verifier,outcome:e}}function ul(t){let e=t.
1000
+ hechos,n=zm(t.cacheResult,e),r={source:n};if(t.hayEsquema)if(t.structurallyValid===null)r.schema={outcome:"not_applicable",decodeTimeConstraint:t.backend!=="none",errorCount:0};else {let i=e?.validacion,
996
1001
  s=i?.errores??(t.structurallyValid?0:1);r.schema={outcome:t.structurallyValid?"passed":"failed",decodeTimeConstraint:t.backend!=="none",errorCount:s,...i?.desenvuelto?{unwrapped:true}:{}};}if(n==="provid\
997
1002
  er"&&e?.reparacion&&(r.repair={...e.reparacion}),n==="provider"||n==="fail_open"){let i=e?.final,s=i?.topeDelLlamante;r.truncation={truncated:i?.finishReason==="length",...i?.finishReason!==void 0?{finishReason:i.
998
1003
  finishReason}:{},capSetByCaller:s!=null,...s!=null?{outputLimit:s}:{}};}if(n==="exact_cache")r.cacheMatch={kind:"exact",...t.ageMs!==void 0?{ageMs:t.ageMs}:{}};else if(n==="semantic_cache"&&e?.semantico){
999
1004
  let i=e.semantico;r.cacheMatch={kind:"semantic",ageMs:i.ageMs,similarity:i.similarity,similarityFloor:i.similarityFloor,acceptFloor:i.acceptFloor,...i.verifierRan?{verifierScore:i.verifierScore}:{},embedder:i.
1000
- embedder,factGuard:"passed",...i.calibration?{calibration:{...i.calibration}}:{}};}let o=jm(t.cascada);return o&&(r.cascade=o),r}function cl(t){return {source:"coalesced",sharedFrom:t==null?"provider":t.
1005
+ embedder,factGuard:"passed",...i.calibration?{calibration:{...i.calibration}}:{}};}let o=qm(t.cascada);return o&&(r.cascade=o),r}function ll(t){return {source:"coalesced",sharedFrom:t==null?"provider":t.
1001
1006
  source==="coalesced"?t.sharedFrom??"provider":t.source,...t?.schema?{schema:{...t.schema}}:{},...t?.repair?{repair:{...t.repair}}:{},...t?.truncation?{truncation:{...t.truncation}}:{},...t?.cacheMatch?
1002
- {cacheMatch:Nm(t.cacheMatch)}:{},...t?.cascade?{cascade:{...t.cascade}}:{}}}function Nm(t){return t.kind==="semantic"&&t.calibration?{...t,calibration:{...t.calibration}}:{...t}}function Zr(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,
1007
+ {cacheMatch:Vm(t.cacheMatch)}:{},...t?.cascade?{cascade:{...t.cascade}}:{}}}function Vm(t){return t.kind==="semantic"&&t.calibration?{...t,calibration:{...t.calibration}}:{...t}}function Yr(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,
1003
1008
  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==
1004
- "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 $m(t){let e=t*100,
1005
- n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function ul(t){let e=$m(t);return `[bvsala] Verification sampling is ON \
1009
+ "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 Um(t){let e=t*100,
1010
+ n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function dl(t){let e=Um(t);return `[bvsala] Verification sampling is ON \
1006
1011
  (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\
1007
1012
  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\
1008
- your statement or any commission.`}function ll(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\
1009
- \` must be a number from 0 to 1 and \`verification.maxCheckCostUsd\`, when set, a positive number (got sampleRate ${e}); verification sampling is OFF.`}var dl="[bvsala] Verification sampling is set, b\
1013
+ your statement or any commission.`}function pl(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\
1014
+ \` must be a number from 0 to 1 and \`verification.maxCheckCostUsd\`, when set, a positive number (got sampleRate ${e}); verification sampling is OFF.`}var fl="[bvsala] Verification sampling is set, b\
1010
1015
  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\
1011
- g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",pl="[bvsala] verification sampling hit an internal error and skipped a request; your\
1012
- request was not affected.";function fl(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?
1016
+ g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",ml="[bvsala] verification sampling hit an internal error and skipped a request; your\
1017
+ request was not affected.";function hl(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?
1013
1018
  {tools:[...t.tools]}:{},...t.response?.schema?{schema:t.response.schema}:{},...t.response?.maxOutputTokens!=null?{maxOutputTokens:t.response.maxOutputTokens}:{},...t.temperature!==void 0?{temperature:t.
1014
- temperature}:{},...t.seed!==void 0?{seed:t.seed}:{}}}function ml(t){let{request:e,result:n,via:r}=t,o=n.report;if(r==="fail-open")return {excluida:"fail_open"};if(e.savings?.verification===false)return {excluida:"opted_out"};let i=n.finishReason;return i==="\
1019
+ temperature}:{},...t.seed!==void 0?{seed:t.seed}:{}}}function gl(t){let{request:e,result:n,via:r}=t,o=n.report;if(r==="fail-open")return {excluida:"fail_open"};if(e.savings?.verification===false)return {excluida:"opted_out"};let i=n.finishReason;return i==="\
1015
1020
  length"?{excluida:"truncated"}:i!==void 0&&i!=="stop"&&i!=="tool_calls"?{excluida:"incomplete"}:o.constraints.structurallyValid===false||o.qualityStatus==="rejected"?{excluida:"contract_failed"}:o.cost.basis===
1016
1021
  "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>
1017
1022
  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?
1018
- {estrato:"tokens_compressed"}:{estrato:"unchanged"}}function hl(t,e){if(!(e>0))return false;if(e>=1)return true;let n=Y(`${t}:verification-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function gl(t,e){let n=t.inputTokens,r=Math.min(t.cachedInputTokens??0,n),o=e.cachedInputPer1k??e.inputPer1k,i=Math.max(0,n-r)/1e3*e.inputPer1k+r/1e3*o+t.outputTokens/1e3*e.outputPer1k;return Math.round(
1019
- i*1e10)/1e10}var Bm=32,Fm=6e5;function zm(t){return new Date(t).toISOString().slice(0,10)}var Yr=class{tasa;tope;onCheck;waitUntil;provider;precio;contrato;now;sumidero;avisar;enVuelo=new Set;cerrado=false;constructor(e){
1023
+ {estrato:"tokens_compressed"}:{estrato:"unchanged"}}function bl(t,e){if(!(e>0))return false;if(e>=1)return true;let n=Y(`${t}:verification-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function vl(t,e){let n=t.inputTokens,r=Math.min(t.cachedInputTokens??0,n),o=e.cachedInputPer1k??e.inputPer1k,i=Math.max(0,n-r)/1e3*e.inputPer1k+r/1e3*o+t.outputTokens/1e3*e.outputPer1k;return Math.round(
1024
+ i*1e10)/1e10}var Hm=32,Wm=6e5;function Jm(t){return new Date(t).toISOString().slice(0,10)}var Qr=class{tasa;tope;onCheck;waitUntil;provider;precio;contrato;now;sumidero;avisar;enVuelo=new Set;cerrado=false;constructor(e){
1020
1025
  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,
1021
- this.sumidero=e.sumidero,this.avisar=e.avisar;}get copiasEnVuelo(){return this.enVuelo.size}decidir(e,n,r){if(this.cerrado)return n;try{let o=n.report,i=hl(o.requestId,this.tasa),s=ml({request:e,result:n,
1022
- via:r,precio:this.precio,...this.tope!==void 0?{tope:this.tope}:{}}),a;if(i&&"estrato"in s){let l=this.precio(e.model);if(!l)throw new Error("price vanished between classification and launch");a={peticion:fl(
1023
- e),precios:l,estrato:s.estrato};}let c=this.now();this.sumidero.contar?.(zm(c),"estrato"in s?s.estrato:s.excluida),a&&this.lanzar(e,n,c,a);let u="estrato"in s?{sampled:i,stratum:s.estrato}:{sampled:i,excluded:s.
1024
- excluida};return {...n,report:{...o,verification:u}}}catch{return this.avisar("verificacion-fallo-interno",pl),n}}cerrar(){this.cerrado=true;let e=[...this.enVuelo];this.enVuelo.clear();for(let n of e)if(!n.
1026
+ this.sumidero=e.sumidero,this.avisar=e.avisar;}get copiasEnVuelo(){return this.enVuelo.size}decidir(e,n,r){if(this.cerrado)return n;try{let o=n.report,i=bl(o.requestId,this.tasa),s=gl({request:e,result:n,
1027
+ via:r,precio:this.precio,...this.tope!==void 0?{tope:this.tope}:{}}),a;if(i&&"estrato"in s){let l=this.precio(e.model);if(!l)throw new Error("price vanished between classification and launch");a={peticion:hl(
1028
+ e),precios:l,estrato:s.estrato};}let c=this.now();this.sumidero.contar?.(Jm(c),"estrato"in s?s.estrato:s.excluida),a&&this.lanzar(e,n,c,a);let u="estrato"in s?{sampled:i,stratum:s.estrato}:{sampled:i,excluded:s.
1029
+ excluida};return {...n,report:{...o,verification:u}}}catch{return this.avisar("verificacion-fallo-interno",ml),n}}cerrar(){this.cerrado=true;let e=[...this.enVuelo];this.enVuelo.clear();for(let n of e)if(!n.
1025
1030
  decidido){n.decidido=true,n.reloj&&clearTimeout(n.reloj);try{n.abortar.abort();}catch{}this.registrar({...n.base,outcome:"abandoned"}),n.terminar();}}lanzar(e,n,r,o){let i=n.report,s=o.precios,a={requestId:i.
1026
1031
  requestId,at:r,stratum:o.estrato,requestedModel:e.model,servedModel:i.model,cacheResult:i.cache.result,optimized:{cost:i.cost.actual,inputTokens:i.tokens.actualInput,cachedInputTokens:i.tokens.providerCachedInput??
1027
- 0,outputTokens:i.tokens.actualOutput},prices:{inputPer1k:s.inputPer1k,...s.cachedInputPer1k!==void 0?{cachedInputPer1k:s.cachedInputPer1k}:{},outputPer1k:s.outputPer1k}};if(this.enVuelo.size>=Bm){this.
1032
+ 0,outputTokens:i.tokens.actualOutput},prices:{inputPer1k:s.inputPer1k,...s.cachedInputPer1k!==void 0?{cachedInputPer1k:s.cachedInputPer1k}:{},outputPer1k:s.outputPer1k}};if(this.enVuelo.size>=Hm){this.
1028
1033
  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(()=>{
1029
- try{l.abortar.abort();}catch{}this.resolverVuelo(l,{...a,outcome:"check_failed"});},Fm),l.reloj.unref?.(),setTimeout(()=>{if(l.decidido)return;let d;try{d=Promise.resolve(this.provider.generate(o.peticion,
1034
+ try{l.abortar.abort();}catch{}this.resolverVuelo(l,{...a,outcome:"check_failed"});},Wm),l.reloj.unref?.(),setTimeout(()=>{if(l.decidido)return;let d;try{d=Promise.resolve(this.provider.generate(o.peticion,
1030
1035
  {signal:l.abortar.signal}));}catch(p){d=Promise.reject(p);}d.then(p=>{let h;try{h=this.checkDeLaRespuesta(a,o.peticion,p,s);}catch{h={...a,outcome:"check_failed"};}this.resolverVuelo(l,h);},()=>{this.resolverVuelo(
1031
1036
  l,{...a,outcome:"check_failed"});});},0),this.waitUntil)try{this.waitUntil(u.catch(()=>{}));}catch{}}checkDeLaRespuesta(e,n,r,o){let i=r?.usage,s=i?.inputTokens,a=i?.outputTokens,c=i?.cachedInputTokens??
1032
1037
  0,u=h=>typeof h=="number"&&Number.isSafeInteger(h)&&h>=0;if(!i||i.complete===false||!u(s)||!u(a)||!u(c)||s===0&&a===0)return {...e,outcome:"check_unmeasured"};let l=Math.min(c,s),d=r.finishReason,p=typeof d==
1033
- "string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost:gl({inputTokens:s,outputTokens:a,cachedInputTokens:l},o),inputTokens:s,cachedInputTokens:l,outputTokens:a,...p!==
1038
+ "string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost:vl({inputTokens:s,outputTokens:a,cachedInputTokens:l},o),inputTokens:s,cachedInputTokens:l,outputTokens:a,...p!==
1034
1039
  void 0?{finishReason:p}:{},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.
1035
- 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 hs=true,Tl=new WeakSet;function qm(t){typeof t=="object"&&t!==null&&Tl.add(t);}function yl(t){return typeof t=="object"&&t!==null&&Tl.has(t)}function kl(t,e){switch(t){case "none":return Vm();case "inv\
1040
+ 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 bs=true,El=new WeakSet;function Km(t){typeof t=="object"&&t!==null&&El.add(t);}function xl(t){return typeof t=="object"&&t!==null&&El.has(t)}function wl(t,e){switch(t){case "none":return Gm();case "inv\
1036
1041
  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\
1037
1042
  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 \
1038
1043
  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\
@@ -1040,71 +1045,71 @@ status: invalid)":"BiVelio license key is not valid (it does not verify). Check
1040
1045
  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\
1041
1046
  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\
1042
1047
  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\
1043
- license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function Vm(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 t\
1048
+ license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function Gm(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 t\
1044
1049
  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\
1045
- cense status: none)"}function Um(){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 \
1046
- path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var Xr=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new qr;espejoDeCache=new qt;verjaDeCascada;memoriaDelCodebook=new Jr;referenciasDeLider=new WeakMap;noReproducibles=new WeakSet;comprobador;constructor(e,n={}){
1047
- this.config=e,e.silenceWarnings===true&&rc(e.provider),this.deps=Tu(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>Qt()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.
1048
- verjaDeCascada=new Ur(e.modelCascade?.exploration!=null?{exploracion:e.modelCascade.exploration}:{});let r=Zr(e.verification);this.comprobador=r.activo&&n.verificacion?new Yr({ajustes:r,provider:e.provider,
1049
- precio:o=>this.precioConocido(o),contrato:(o,i)=>Hm(o,i),now:this.now,sumidero:n.verificacion,avisar:(o,i)=>this.avisar(o,i)}):void 0;}conVerificacion(e,n,r){return this.comprobador?this.comprobador.decidir(
1050
+ cense status: none)"}function Zm(){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 \
1051
+ path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var eo=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new Vr;espejoDeCache=new qt;verjaDeCascada;memoriaDelCodebook=new Kr;referenciasDeLider=new WeakMap;noReproducibles=new WeakSet;negativasSinCobro=new WeakSet;comprobador;constructor(e,n={}){
1052
+ this.config=e,e.silenceWarnings===true&&ic(e.provider),this.deps=Eu(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>Xt()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.
1053
+ verjaDeCascada=new Hr(e.modelCascade?.exploration!=null?{exploracion:e.modelCascade.exploration}:{});let r=Yr(e.verification);this.comprobador=r.activo&&n.verificacion?new Qr({ajustes:r,provider:e.provider,
1054
+ precio:o=>this.precioConocido(o),contrato:(o,i)=>Ym(o,i),now:this.now,sumidero:n.verificacion,avisar:(o,i)=>this.avisar(o,i)}):void 0;}conVerificacion(e,n,r){return this.comprobador?this.comprobador.decidir(
1050
1055
  e,n,r):n}cerrarVerificacion(){this.comprobador?.cerrar();}async generate(e){this.assertLicensed(),e=this.conPalancasPorDefecto(e);let n={llamadas:0,falloDelProveedor:false,sinContador:0},r;try{r=await this.
1051
- generateOptimized(e,n);}catch(o){if(o instanceof Qe||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||yl(o))throw o;return this.conVerificacion(e,await this.failOpenDirect(e,o),"fail-open")}
1052
- return this.conVerificacion(e,r,"optimizado")}generateStream(e,n={},r){let o;try{o=new Sn(this.now,n?.signal);}catch(i){let s=new Sn(this.now);return s.fallar(i),s.handle}return this.ejecutarStream(e,o,
1053
- r),o.handle}async ejecutarStream(e,n,r){try{if(r&&await r,n.abortado)throw new ke(!1);e=this.conPalancasPorDefecto(e);let o=this.motivoDeEntregaEntera(e);if(o){let a=await this.generate(e);n.completar(
1054
- a,{vivo:!1,motivo:o});return}this.assertLicensed(),n.entrarEnVivo();let i={llamadas:0,falloDelProveedor:!1,sinContador:0},s;try{s=await this.generateOptimized(e,i,n.sumidero);}catch(a){if(a instanceof Qe||
1055
- a instanceof ke)throw a;if(n.sumidero.senal.aborted)throw new ke(i.llamadas>0);if(this.config.failOpen===!1||i.falloDelProveedor||i.llamadas>0||yl(a))throw a;let c=this.conVerificacion(e,await this.failOpenDirect(
1056
+ generateOptimized(e,n);}catch(o){if(o instanceof Xe||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||xl(o))throw o;return this.conVerificacion(e,await this.failOpenDirect(e,o),"fail-open")}
1057
+ return this.conVerificacion(e,r,"optimizado")}generateStream(e,n={},r){let o;try{o=new Tn(this.now,n?.signal);}catch(i){let s=new Tn(this.now);return s.fallar(i),s.handle}return this.ejecutarStream(e,o,
1058
+ r),o.handle}async ejecutarStream(e,n,r){try{if(r&&await r,n.abortado)throw new xe(!1);e=this.conPalancasPorDefecto(e);let o=this.motivoDeEntregaEntera(e);if(o){let a=await this.generate(e);n.completar(
1059
+ a,{vivo:!1,motivo:o});return}this.assertLicensed(),n.entrarEnVivo();let i={llamadas:0,falloDelProveedor:!1,sinContador:0},s;try{s=await this.generateOptimized(e,i,n.sumidero);}catch(a){if(a instanceof Xe||
1060
+ a instanceof xe)throw a;if(n.sumidero.senal.aborted)throw new xe(i.llamadas>0);if(this.config.failOpen===!1||i.falloDelProveedor||i.llamadas>0||xl(a))throw a;let c=this.conVerificacion(e,await this.failOpenDirect(
1056
1061
  e,a),"fail-open");n.completar(c,{vivo:!1,motivo:"fail-open"});return}s=this.conVerificacion(e,s,"optimizado"),n.completar(s,n.sumidero.sirvioEnVivo?{vivo:!0}:{vivo:!1,motivo:"shortcut"});}catch(o){n.fallar(
1057
1062
  o);}}conPalancasPorDefecto(e){let n=this.config.priceLevers;if(!n)return e;let r=e.savings,o=n.deferrable===true&&r?.deferrable===void 0,i=n.standalone===true&&r?.standalone===void 0;return !o&&!i?e:{...e,savings:{
1058
1063
  ...r??{},...o?{deferrable:true}:{},...i?{standalone:true}:{}}}}motivoDeEntregaEntera(e){return e.response?.schema!=null?"output-contract":e.savings?.deferrable===true?"deferrable":typeof this.config.provider.
1059
1064
  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=true,o}return r.
1060
- usage.complete===false&&(n.sinContador+=1),r}async llamarProveedorEnStream(e,n,r){if(r.senal.aborted)throw new ke(n.llamadas>0);n.llamadas+=1;let o="",i;try{for await(let s of this.config.provider.generateStream(
1061
- e,{signal:r.senal})){if(r.senal.aborted)break;if(s.type==="text")s.delta!==""&&(o+=s.delta,r.texto(s.delta));else if(s.type==="done"){i=s.response;break}}}catch(s){throw r.senal.aborted?new ke(true):(n.
1062
- falloDelProveedor=true,s)}if(!i)throw r.senal.aborted?new ke(true):(n.falloDelProveedor=true,new Error(`provider "${this.config.provider.id}" stream ended without a final response`));return r.proveedorTermino(),
1065
+ usage.complete===false&&(n.sinContador+=1),r}async llamarProveedorEnStream(e,n,r){if(r.senal.aborted)throw new xe(n.llamadas>0);n.llamadas+=1;let o="",i;try{for await(let s of this.config.provider.generateStream(
1066
+ e,{signal:r.senal})){if(r.senal.aborted)break;if(s.type==="text")s.delta!==""&&(o+=s.delta,r.texto(s.delta));else if(s.type==="done"){i=s.response;break}}}catch(s){throw r.senal.aborted?new xe(true):(n.
1067
+ falloDelProveedor=true,s)}if(!i)throw r.senal.aborted?new xe(true):(n.falloDelProveedor=true,new Error(`provider "${this.config.provider.id}" stream ended without a final response`));return r.proveedorTermino(),
1063
1068
  i.usage.complete===false&&(n.sinContador+=1),i.text!==o&&(this.avisar(`stream-texto-distinto:${this.config.provider.id}`,`[bvsala] provider "${this.config.provider.id}" streamed text that differs from it\
1064
- s 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 concatenated deltas.`),i=Xa(
1065
- i,{...i,text:o})),r.sirvioEnVivo=true,i}decidirMarcadoDeCache(e,n,r,o,i,s,a,c=null){let u=e.savings?.standalone===true&&lt(n,dt(this.config.provider))?ni(n):null,l=u!==null,d={marcar:false,huella:"",claveDeVerja:"",
1066
- mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:l,explicitaPorColocador:false,colocacion:null},p=gs(n,this.config.compressionEconomics);if(!p)return a.record("prefix-cache","skipped",{reason:`no cac\
1069
+ s 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 concatenated deltas.`),i=tc(
1070
+ i,{...i,text:o})),r.sirvioEnVivo=true,i}decidirMarcadoDeCache(e,n,r,o,i,s,a,c=null){let u=e.savings?.standalone===true&&dt(n,pt(this.config.provider))?ri(n):null,l=u!==null,d={marcar:false,huella:"",claveDeVerja:"",
1071
+ mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:l,explicitaPorColocador:false,colocacion:null},p=vs(n,this.config.compressionEconomics);if(!p)return a.record("prefix-cache","skipped",{reason:`no cac\
1067
1072
  he read discount for model "${n}" (unrecognised provider, or a declared tier that does not discount reads): not claiming a cacheable prefix`}),d;if(!o.setIsStable)return a.record("prefix-cache","skipp\
1068
1073
  ed",{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 want fixed."}),d;if(i)return a.record("\
1069
1074
  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 \u2014 varies across requests that would \
1070
1075
  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."}),d;let h=null;if(this.config.cacheBreakpoints===
1071
1076
  "auto"&&!l){let k=this.colocarConEspejo(e,n,r,o,s,p,a,c);if("marcado"in k)return k.marcado;h=k.observacion;}if(s<=0)return {...d,colocacion:h};let m=r.slice(0,s),g=this.tokensFor(this.assemblePromptText(
1072
- m,o.tools),e),f=this.tokensFor(this.assemblePromptText(r,o.tools),e),v=Y(he({model:n,tools:(o.tools??[]).map(k=>k.id),prefijo:m.map(k=>`${k.role}:${k.content}`)})),b=l?`${v}|explicit`:v,y=this.verjaDeCache.
1077
+ m,o.tools),e),f=this.tokensFor(this.assemblePromptText(r,o.tools),e),v=Y(ge({model:n,tools:(o.tools??[]).map(k=>k.id),prefijo:m.map(k=>`${k.role}:${k.content}`)})),b=l?`${v}|explicit`:v,y=this.verjaDeCache.
1073
1078
  decidir(b,{totalTokens:f,stablePrefixTokens:g,tier:u??p});return a.record("prefix-cache",y.marcar?"marked":"skipped",{reason:y.razon,stablePrefixTokens:g,breakEvenHitRate:y.umbral,observedHitRate:y.observada,
1074
1079
  ...l?{mode:"explicit"}:{}}),y.marcar?{marcar:true,huella:v,claveDeVerja:b,mensajesDePrefijo:s,cacheWriteMultiplier:p.cacheWriteMultiplier,explicita:l,explicitaPorColocador:false,colocacion:h}:{...d,colocacion:h}}colocarConEspejo(e,n,r,o,i,s,a,c=null){
1075
- let{tramoOpenAI:u,conPrima:l}=this.primasDelColocador(e,n,s);if(!l&&!u)return {observacion:null};let d=ts(r),p=Math.max(d,Math.min(i,r.length)),h=r.length,m=c?.huellas??this.huellasDelColocador(e,n,r,o.
1076
- tools),g=m[d],f=c?.clase===g?c:null,v=f?.espejo??this.espejoDeCache,b=this.now(),y=v.observar(g,m,b),k=v.estadistica(g,b),T=f?{mirrorStore:f.estado}:{},w={S:d,...p>d?{H:p}:{},T:h},P=z=>this.tokensFor(
1077
- this.assemblePromptText(r.slice(0,z),o.tools),e),x={clase:g,huellas:m,tramos:w,coincidencia:y,enviada:b,...f?{conAlmacen:true}:{}};if(u){let z=Lu({estadistica:k,tramo:u,hayHistorial:p>d});a.record("pref\
1078
- ix-cache-placement",z.explicita?"explicit":"provider-default",{reason:z.razon,breakEvenReuseRate:z.equilibrio,continuedWithin30m:k.T.en30m,samples:k.T.muestras30m,...T});let ee={...x,cola:!z.explicita,
1080
+ let{tramoOpenAI:u,conPrima:l}=this.primasDelColocador(e,n,s);if(!l&&!u)return {observacion:null};let d=rs(r),p=Math.max(d,Math.min(i,r.length)),h=r.length,m=c?.huellas??this.huellasDelColocador(e,n,r,o.
1081
+ tools),g=m[d],f=c?.clase===g?c:null,v=f?.espejo??this.espejoDeCache,b=this.now(),y=v.observar(g,m,b),k=v.estadistica(g,b),T=f?{mirrorStore:f.estado}:{},x={S:d,...p>d?{H:p}:{},T:h},R=z=>this.tokensFor(
1082
+ this.assemblePromptText(r.slice(0,z),o.tools),e),D={clase:g,huellas:m,tramos:x,coincidencia:y,enviada:b,...f?{conAlmacen:true}:{}};if(u){let z=Nu({estadistica:k,tramo:u,hayHistorial:p>d});a.record("pref\
1083
+ ix-cache-placement",z.explicita?"explicit":"provider-default",{reason:z.razon,breakEvenReuseRate:z.equilibrio,continuedWithin30m:k.T.en30m,samples:k.T.muestras30m,...T});let ee={...D,cola:!z.explicita,
1079
1084
  ttl:"5m",ultimo:z.explicita?null:"T",indiceDelUltimo:z.explicita?null:h};if(!z.explicita)return {observacion:ee};let L=z.historial?p:d;if(L<=0)return {marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,
1080
- cacheWriteMultiplier:1,explicita:true,explicitaPorColocador:true,colocacion:{...ee,ultimo:null,indiceDelUltimo:null}}};let se=L===d?"S":"H",ae=`${g}|explicit|${se}`,G=this.verjaDeCache.decidir(ae,{totalTokens:P(
1081
- h),stablePrefixTokens:P(L),tier:u});return a.record("prefix-cache",G.marcar?"marked":"skipped",{reason:G.razon,breakEvenHitRate:G.umbral,observedHitRate:G.observada,mode:"explicit"}),{marcado:{marcar:G.
1085
+ cacheWriteMultiplier:1,explicita:true,explicitaPorColocador:true,colocacion:{...ee,ultimo:null,indiceDelUltimo:null}}};let se=L===d?"S":"H",ae=`${g}|explicit|${se}`,G=this.verjaDeCache.decidir(ae,{totalTokens:R(
1086
+ h),stablePrefixTokens:R(L),tier:u});return a.record("prefix-cache",G.marcar?"marked":"skipped",{reason:G.razon,breakEvenHitRate:G.umbral,observedHitRate:G.observada,mode:"explicit"}),{marcado:{marcar:G.
1082
1087
  marcar,huella:G.marcar?this.huellaDelPrefijo(n,o.tools,r,L):"",claveDeVerja:G.marcar?ae:"",mensajesDePrefijo:G.marcar?L:0,cacheWriteMultiplier:1,explicita:true,explicitaPorColocador:true,colocacion:{...ee,
1083
- ultimo:G.marcar?se:null,indiceDelUltimo:G.marcar?L:null}}}}let S={S:d>0?P(d):0,H:p>d?P(p):0,T:P(h)},O=Qo(n),R=Mu({estadistica:k,tramo:s,primaDeUnaHora:O>s.cacheWriteMultiplier?O:null,tokens:S,hayHistorial:p>
1084
- d,lecturaPrevista:()=>y?P(y.indice):0}),C=R.historial&&p>d?p:d,I=R.cola?"T":C>0?C===p&&p>d?"H":"S":null,D=R.cola?h:C>0?C:null;a.record("prefix-cache-placement",I??"none",{reason:R.razon||"fixed placem\
1085
- ent",boundary:C===0?"none":C===d?"system":"history",tail:R.cola,ttl:R.ttl,breakEvenReuseRate:R.equilibrio,historyReusedWithin5m:k.H.en5m,continuedWithin5m:k.T.en5m,samples:k.T.muestras5m,providerConfirmedReads:`${k.
1086
- confirmadas}/${k.predichas}`,...T});let A={...x,cola:R.cola,ttl:R.ttl,ultimo:null,indiceDelUltimo:null};if(I==null||D==null)return {marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,
1087
- explicita:false,explicitaPorColocador:false,colocacion:A}};let j=R.ttl==="1h"?{...s,cacheWriteMultiplier:O}:s,B=`${g}|${C===0?"-":C===d?"S":"H"}${R.cola?"+T":""}@${R.ttl}`,V=this.verjaDeCache.decidir(B,{totalTokens:S.
1088
- T,stablePrefixTokens:R.cola?S.T:C===d?S.S:S.H,tier:j});return a.record("prefix-cache",V.marcar?"marked":"skipped",{reason:V.razon,stablePrefixTokens:R.cola?S.T:C===d?S.S:S.H,breakEvenHitRate:V.umbral,
1089
- observedHitRate:V.observada}),V.marcar?{marcado:{marcar:true,huella:this.huellaDelPrefijo(n,o.tools,r,C),claveDeVerja:B,mensajesDePrefijo:C,cacheWriteMultiplier:s.cacheWriteMultiplier,explicita:false,explicitaPorColocador:false,
1090
- colocacion:{...A,ultimo:I,indiceDelUltimo:D}}}:{marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:false,explicitaPorColocador:false,colocacion:A}}}apuntarEnElEspejo(e,n,r,o=this.
1088
+ ultimo:G.marcar?se:null,indiceDelUltimo:G.marcar?L:null}}}}let I={S:d>0?R(d):0,H:p>d?R(p):0,T:R(h)},E=Xo(n),S=ju({estadistica:k,tramo:s,primaDeUnaHora:E>s.cacheWriteMultiplier?E:null,tokens:I,hayHistorial:p>
1089
+ d,lecturaPrevista:()=>y?R(y.indice):0}),w=S.historial&&p>d?p:d,C=S.cola?"T":w>0?w===p&&p>d?"H":"S":null,_=S.cola?h:w>0?w:null;a.record("prefix-cache-placement",C??"none",{reason:S.razon||"fixed placem\
1090
+ ent",boundary:w===0?"none":w===d?"system":"history",tail:S.cola,ttl:S.ttl,breakEvenReuseRate:S.equilibrio,historyReusedWithin5m:k.H.en5m,continuedWithin5m:k.T.en5m,samples:k.T.muestras5m,providerConfirmedReads:`${k.
1091
+ confirmadas}/${k.predichas}`,...T});let O={...D,cola:S.cola,ttl:S.ttl,ultimo:null,indiceDelUltimo:null};if(C==null||_==null)return {marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,
1092
+ explicita:false,explicitaPorColocador:false,colocacion:O}};let j=S.ttl==="1h"?{...s,cacheWriteMultiplier:E}:s,B=`${g}|${w===0?"-":w===d?"S":"H"}${S.cola?"+T":""}@${S.ttl}`,V=this.verjaDeCache.decidir(B,{totalTokens:I.
1093
+ T,stablePrefixTokens:S.cola?I.T:w===d?I.S:I.H,tier:j});return a.record("prefix-cache",V.marcar?"marked":"skipped",{reason:V.razon,stablePrefixTokens:S.cola?I.T:w===d?I.S:I.H,breakEvenHitRate:V.umbral,
1094
+ observedHitRate:V.observada}),V.marcar?{marcado:{marcar:true,huella:this.huellaDelPrefijo(n,o.tools,r,w),claveDeVerja:B,mensajesDePrefijo:w,cacheWriteMultiplier:s.cacheWriteMultiplier,explicita:false,explicitaPorColocador:false,
1095
+ colocacion:{...O,ultimo:C,indiceDelUltimo:_}}}:{marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:false,explicitaPorColocador:false,colocacion:O}}}apuntarEnElEspejo(e,n,r,o=this.
1091
1096
  espejoDeCache,i={}){let s=e.colocacion,a=n.complete!==false,c=Math.max(0,n.cachedInputTokens??0),u=Math.max(0,n.cacheWriteInputTokens??0),l=s.ultimo!=null&&s.indiceDelUltimo!=null,d=s.coincidencia?.indice;
1092
- if(a&&l&&s.coincidencia&&d!==void 0&&s.indiceDelUltimo>=d&&s.indiceDelUltimo-d<_u){let p=o.estadistica(s.clase,s.enviada);o.verificar(s.clase,s.coincidencia,c);let h=o.estadistica(s.clase,s.enviada);if(h.
1097
+ if(a&&l&&s.coincidencia&&d!==void 0&&s.indiceDelUltimo>=d&&s.indiceDelUltimo-d<Ou){let p=o.estadistica(s.clase,s.enviada);o.verificar(s.clase,s.coincidencia,c);let h=o.estadistica(s.clase,s.enviada);if(h.
1093
1098
  predichas>p.predichas){let m=h.confirmadas>p.confirmadas,g=i.diagnostico;r.record("prefix-cache-placement","verified",{predictedRead:s.coincidencia.posicionDelProveedor,providerCacheRead:c,confirmed:m,
1094
1099
  ...!m&&g?{cacheMissReason:g.missReason,...g.missedInputTokens!==void 0?{cacheMissedInputTokensEstimate:g.missedInputTokens}:{}}:{},...h.apagada&&!p.apagada?{reason:`the provider's counter confirmed on\
1095
1100
  ly ${h.confirmadas} of ${h.predichas} predicted cache reads: this traffic goes back to the fixed placement`}:{}});}}o.registrar({clase:s.clase,huellas:s.huellas,tramos:s.tramos,enviada:s.enviada,ultimoMarcado:l?
1096
1101
  s.ultimo:null,posicionDelProveedor:a&&l?c+u:null,ttl:s.ttl,idDelProveedor:this.config.cacheMissDiagnostics===true&&l?i.id??null:null});}async apuntarEnElAlmacen(e,n,r,o){let i=this.config.cacheBreakpointStore,
1097
- s=e.colocacion,a=ns(s.clase),c;try{c=await i.get(a);}catch(l){r.record("prefix-cache-placement","store-error",{reason:`could not read the placement store (${Sl(l)}), so this request was not recorded`});
1102
+ s=e.colocacion,a=os(s.clase),c;try{c=await i.get(a);}catch(l){r.record("prefix-cache-placement","store-error",{reason:`could not read the placement store (${Cl(l)}), so this request was not recorded`});
1098
1103
  return}let u=new qt;if(c!=null&&u.importarClase(s.clase,c)==="newer"){r.record("prefix-cache-placement","store-error",{reason:"the placement store holds a state written by a newer SDK version; left un\
1099
- touched"});return}u.observar(s.clase,s.huellas,s.enviada),this.apuntarEnElEspejo(e,n,r,u,o);try{await i.set(a,u.exportarClase(s.clase),Ou);}catch(l){r.record("prefix-cache-placement","store-error",{reason:`\
1100
- could not write the placement store (${Sl(l)})`});}}async cargarEspejo(e,n,r,o,i){if(this.config.cacheBreakpoints!=="auto"||!o.setIsStable||i)return null;let s=dt(this.config.provider);if(e.savings?.standalone===
1101
- true&&lt(n,s))return null;let a=gs(n,this.config.compressionEconomics);if(!a)return null;let{tramoOpenAI:c,conPrima:u}=this.primasDelColocador(e,n,a);if(!u&&!c)return null;let l=this.huellasDelColocador(
1102
- e,n,r,o.tools),d=l[ts(r)],p=new qt,h;try{let m=await this.config.cacheBreakpointStore.get(ns(d));h=m==null?"empty":p.importarClase(d,m)==="loaded"?"loaded":"unreadable";}catch{h="unavailable";}return {clase:d,
1103
- huellas:l,espejo:p,estado:h}}primasDelColocador(e,n,r){let o=dt(this.config.provider),i=e.savings?.standalone===void 0&&lt(n,o);return {tramoOpenAI:i?ni(n):null,conPrima:r.cacheWriteMultiplier>1&&!i}}huellasDelColocador(e,n,r,o){
1104
- let i=he({model:n,tools:(o??[]).map(s=>s.id),schema:e.response?.schema??null});return Au(i,r)}huellaDelPrefijo(e,n,r,o){return Y(he({model:e,tools:(n??[]).map(i=>i.id),prefijo:r.slice(0,o).map(i=>`${i.
1104
+ touched"});return}u.observar(s.clase,s.huellas,s.enviada),this.apuntarEnElEspejo(e,n,r,u,o);try{await i.set(a,u.exportarClase(s.clase),Lu);}catch(l){r.record("prefix-cache-placement","store-error",{reason:`\
1105
+ could not write the placement store (${Cl(l)})`});}}async cargarEspejo(e,n,r,o,i){if(this.config.cacheBreakpoints!=="auto"||!o.setIsStable||i)return null;let s=pt(this.config.provider);if(e.savings?.standalone===
1106
+ true&&dt(n,s))return null;let a=vs(n,this.config.compressionEconomics);if(!a)return null;let{tramoOpenAI:c,conPrima:u}=this.primasDelColocador(e,n,a);if(!u&&!c)return null;let l=this.huellasDelColocador(
1107
+ e,n,r,o.tools),d=l[rs(r)],p=new qt,h;try{let m=await this.config.cacheBreakpointStore.get(os(d));h=m==null?"empty":p.importarClase(d,m)==="loaded"?"loaded":"unreadable";}catch{h="unavailable";}return {clase:d,
1108
+ huellas:l,espejo:p,estado:h}}primasDelColocador(e,n,r){let o=pt(this.config.provider),i=e.savings?.standalone===void 0&&dt(n,o);return {tramoOpenAI:i?ri(n):null,conPrima:r.cacheWriteMultiplier>1&&!i}}huellasDelColocador(e,n,r,o){
1109
+ let i=ge({model:n,tools:(o??[]).map(s=>s.id),schema:e.response?.schema??null});return Mu(i,r)}huellaDelPrefijo(e,n,r,o){return Y(ge({model:e,tools:(n??[]).map(i=>i.id),prefijo:r.slice(0,o).map(i=>`${i.
1105
1110
  role}:${i.content}`)}))}decidirCascada(e,n,r,o,i=this.now()){let s=r.modelCascade??"off",a={modo:"off",modeloPedido:e.model,modeloServido:e.model,candidato:null,enruta:false,elegible:false,razon:"the model \
1106
- cascade is off",fuerza:"none",bucket:"",economia:null,observada:null,muestras:0,precioBarato:null,tasaDeMuestreo:0};if(s==="off")return a;let c=Bu({schema:e.response?.schema,tools:e.tools}),u=$u(e.model,
1107
- this.config.modelCascade?.pairs??rs),l=this.precioConocido(e.model,i),d=u?this.precioConocido(u,i):void 0,p=Nu(d,l),h=Y(he({tenant:n.tenantId,scope:n.authorizationScope,contract:n.contractId,schema:n.
1111
+ cascade is off",fuerza:"none",bucket:"",economia:null,observada:null,muestras:0,precioBarato:null,tasaDeMuestreo:0};if(s==="off")return a;let c=zu({schema:e.response?.schema,tools:e.tools}),u=Fu(e.model,
1112
+ this.config.modelCascade?.pairs??is),l=this.precioConocido(e.model,i),d=u?this.precioConocido(u,i):void 0,p=Bu(d,l),h=Y(ge({tenant:n.tenantId,scope:n.authorizationScope,contract:n.contractId,schema:n.
1108
1113
  schemaVersion,fuerte:e.model,barato:u,tools:n.toolsetHash})),m=this.verjaDeCascada.estado(h),g={modo:s,modeloPedido:e.model,modeloServido:e.model,candidato:u,enruta:false,elegible:false,razon:c.razon,fuerza:c.
1109
1114
  fuerza,bucket:h,economia:p,observada:m&&m.enrutadas>0?m.escaladas/m.enrutadas:null,muestras:m?.enrutadas??0,precioBarato:d??null,tasaDeMuestreo:0},f=y=>(o.record("model-cascade",s==="on"?"not routed":
1110
1115
  "not eligible",{reason:y}),{...g,razon:y});if(!c.elegible)return f(c.razon);if(!u)return f(`no cheaper model is paired with "${e.model}"; declare one in createSavingsLayer({ modelCascade: { pairs } })\
@@ -1118,8 +1123,8 @@ er its meaning, so a well-formed answer with wrong content is served and counted
1118
1123
  o.record("model-cascade","routed",{candidateModel:u,costRatio:p.r,breakEvenEscalationRate:p.equilibrio,observedEscalationRate:b.observada,verifier:c.fuerza,workload:h,reason:b.razon}),{...g,modeloServido:u,
1119
1124
  enruta:true,elegible:true,razon:b.razon,observada:b.observada,muestras:b.muestras,tasaDeMuestreo:0}):(o.record("model-cascade","off (gate)",{reason:b.razon,observedEscalationRate:b.observada,breakEvenEscalationRate:p.
1120
1125
  equilibrio}),{...g,elegible:true,razon:b.razon,observada:b.observada,muestras:b.muestras})}devOpen(){return false}exigirLicencia(){this.assertLicensed();}assertLicensed(){if(this.devOpen())return;let e=this.
1121
- config.licenseGate;if(e&&typeof e.isActive=="function"){if(e.isActive())return;let n=typeof e.status=="function"?e.status():void 0,r=typeof e.reason=="function"?e.reason():void 0;throw new Qe(kl(n,r),
1122
- n)}throw e?new Qe(Um(),"invalid"):new Qe(kl("none"),"none")}avisar(e,n){this.config.silenceWarnings||ye(e,n);}avisarDeTruncado(e,n,r,o,i){let s=e.response?.maxOutputTokens,a=Pn(e)||"(no contractId)",c=i?
1126
+ config.licenseGate;if(e&&typeof e.isActive=="function"){if(e.isActive())return;let n=typeof e.status=="function"?e.status():void 0,r=typeof e.reason=="function"?e.reason():void 0;throw new Xe(wl(n,r),
1127
+ n)}throw e?new Xe(Zm(),"invalid"):new Xe(wl("none"),"none")}avisar(e,n){this.config.silenceWarnings||ke(e,n);}avisarDeTruncado(e,n,r,o,i){let s=e.response?.maxOutputTokens,a=Rn(e)||"(no contractId)",c=i?
1123
1128
  " The layer has NOTED it: the next requests for this contract will carry their value limits written into the prompt, which is the only thing that can fix it without touching your cap. If it still gets\
1124
1129
  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 response (no `maxLength`/`maxItems`), so there is no way to kno\
1125
1130
  w in advance how much it needs: bound it and the cap stops being a guess.":s==null?` The contract allows ~${o} tokens and this request declares no cap, so the cut came from a PROVIDER cap (the Anthrop\
@@ -1135,479 +1140,486 @@ uld decide to pay for: plug it in with `createSavingsLayer({ compressor })`, any
1135
1140
  The rest of the layer keeps saving as usual."),e.semanticCache&&!this.deps.semanticCache&&this.avisar("palanca-sin-cache-semantica",'[bv-sala] `savings.semanticCache` was requested but this layer has\
1136
1141
  no semantic cache, so every rephrased question will come out `cache: "miss"` and be paid to the provider again. It is not on by default because it needs an embedder, which is your own cost and provid\
1137
1142
  er: plug it in with `createSavingsLayer({ semanticCache: new InMemorySemanticCache({ embed }) })`. The exact cache and the rest of the layer keep working.'));}async generateOptimized(e,n={llamadas:0,falloDelProveedor:false,
1138
- sinContador:0},r=null){this.assertLicensed();let o=new mn(this.now),i=new Et,s=Ro(e),a=Fn(s),c=e.savings??{};this.avisarDePalancasSinConfigurar(c),c.semanticCache&&c.semanticCache!=="include-agentic"&&
1139
- this.deps.semanticCache&&xl(s,a)&&this.avisar("semantica-agentica-apagada",'[bv-sala] `savings.semanticCache` is on, but this request is agentic (it declares tools, carries tool calls or results, or h\
1143
+ sinContador:0},r=null){this.assertLicensed();let o=new hn(this.now),i=new Et,s=Do(e),a=zn(s),c=e.savings??{};this.avisarDePalancasSinConfigurar(c),c.semanticCache&&c.semanticCache!=="include-agentic"&&
1144
+ this.deps.semanticCache&&Sl(s,a)&&this.avisar("semantica-agentica-apagada",'[bv-sala] `savings.semanticCache` is on, but this request is agentic (it declares tools, carries tool calls or results, or h\
1140
1145
  olds more than one user turn), so the semantic cache was neither consulted nor written for it. That is the default: two runs of an agent loop can differ only in what a tool returned, and the guard und\
1141
1146
  er the similarity score cannot see that. The exact cache is unaffected. To include agentic requests, set `savings.semanticCache: "include-agentic"` after measuring it on your own traffic.');let u=this.
1142
1147
  now(),l=this.decidirCascada(e,s,c,o,u),d=this.costModelFor(l.modeloServido,u);o.record("canonicalize","done",{tenant:s.tenantId,contract:s.contractId}),o.record("policy",a.reasons.join("; ")||"no rest\
1143
- rictions",{allowExactCache:a.allowExactCache,allowSemanticCache:a.allowSemanticCache});let p=this.tokensFor(this.assembleBaselinePrompt(e),e),h=e.response?.maxOutputTokens??256,m,g=()=>m??=ms(e);if(i.
1148
+ rictions",{allowExactCache:a.allowExactCache,allowSemanticCache:a.allowSemanticCache});let p=this.tokensFor(this.assembleBaselinePrompt(e),e),h=e.response?.maxOutputTokens??256,m,g=()=>m??=gs(e);if(i.
1144
1149
  baselineInput=p,i.baselineOutput=h,i.baselineTools=e.tools?.length??0,c.deterministicResolvers!==false){let y=this.deps.resolvers.try(s);if(y)return i.avoidCall(p,this.tokensFor(y.text,e)),o.record("reso\
1145
- lver",y.resolver,{avoided:true}),this.finish(e,s,{text:y.text,data:y.data,storedAtMs:this.now()},"deterministic",i,d,o,Cn(),En(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(l,{servedModel:e.
1146
- model}))}let f=Do(s,{servedModel:l.modeloServido});if(a.allowExactCache&&c.exactCache!==false){let y=await this.deps.exactCache.get(f);if(y){let k=this.creditoPorReferencia(il(y.meta),{request:e,cascada:l,
1147
- toggles:c,huella:g,texto:y.text,claveLeida:f,calidad:()=>{let T=e.response?.schema;return !T||de(y.data,T).valid}});return k.ok?i.avoidCallByReference(k.credit):(i.avoidCall(p,this.tokensFor(y.text,e)),
1150
+ lver",y.resolver,{avoided:true}),this.finish(e,s,{text:y.text,data:y.data,storedAtMs:this.now()},"deterministic",i,d,o,En(),Pn(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(l,{servedModel:e.
1151
+ model}))}let f=Io(s,{servedModel:l.modeloServido});if(a.allowExactCache&&c.exactCache!==false){let y=await this.deps.exactCache.get(f);if(y){let k=this.creditoPorReferencia(al(y.meta),{request:e,cascada:l,
1152
+ toggles:c,huella:g,texto:y.text,claveLeida:f,calidad:()=>{let T=e.response?.schema;return !T||pe(y.data,T).valid}});return k.ok?i.avoidCallByReference(k.credit):(i.avoidCall(p,this.tokensFor(y.text,e)),
1148
1153
  i.referenceRejected=k.reason),o.record("exact-cache","hit",{ageMs:this.now()-y.storedAtMs,basis:k.ok?"reference":"estimated",...k.ok?{}:{referenceRejected:k.reason},...k.ok&&k.outputNotCredited?{outputNotCredited:k.
1149
- outputNotCredited}:{}}),this.finish(e,s,y,"exact",i,d,o,Cn(),En(),this.now()-y.storedAtMs,void 0,void 0,void 0,void 0,this.informeDeCascada(l))}o.record("exact-cache","miss");}let v=Qs(s,{servedModel:l.
1154
+ outputNotCredited}:{}}),this.finish(e,s,y,"exact",i,d,o,En(),Pn(),this.now()-y.storedAtMs,void 0,void 0,void 0,void 0,this.informeDeCascada(l))}o.record("exact-cache","miss");}let v=ea(s,{servedModel:l.
1150
1155
  modeloServido,deferrable:c.deferrable===true,toolDiscovery:c.toolDiscovery===true,...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{}}),b=async()=>{try{return await this.expensivePath(
1151
- n,e,s,a,c,i,d,o,f,p,l,r,u)}catch(y){throw (n.falloDelProveedor||n.llamadas>0)&&qm(y),y}};if(a.allowSingleflight&&c.singleflight!==false){if(r){let T=this.deps.singleflight,w=typeof T.join=="function"?T.join(
1152
- v):void 0;if(w){let P=await w;return this.noReproducibles.has(P)?(o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),b()):(o.record("singleflight","coalesced",{key:v}),this.
1153
- asCoalescedFollower(P,p,this.tokensFor(P.text??"",e),d,e))}return o.record("singleflight","skipped (streaming: a streamed request never leads)"),b()}let{value:y,coalesced:k}=await this.deps.singleflight.
1156
+ n,e,s,a,c,i,d,o,f,p,l,r,u)}catch(y){throw (n.falloDelProveedor||n.llamadas>0)&&Km(y),y}};if(a.allowSingleflight&&c.singleflight!==false){if(r){let T=this.deps.singleflight,x=typeof T.join=="function"?T.join(
1157
+ v):void 0;if(x){let R=await x;return this.noReproducibles.has(R)?(o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),b()):(o.record("singleflight","coalesced",{key:v}),this.
1158
+ asCoalescedFollower(R,p,this.tokensFor(R.text??"",e),d,e))}return o.record("singleflight","skipped (streaming: a streamed request never leads)"),b()}let{value:y,coalesced:k}=await this.deps.singleflight.
1154
1159
  run(v,b);if(k&&this.noReproducibles.has(y))return o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),b();if(k){o.record("singleflight","coalesced",{key:v});let T=this.creditoPorReferencia(
1155
1160
  this.referenciasDeLider.get(y)??"absent",{request:e,cascada:l,toggles:c,huella:g,texto:y.text??"",claveLeida:void 0,calidad:()=>y.report.constraints.structurallyValid!==false&&y.report.qualityStatus!=="r\
1156
1161
  ejected"});return this.asCoalescedFollower(y,p,this.tokensFor(y.text??"",e),d,e,T)}return y}return b()}async expensivePath(e,n,r,o,i,s,a,c,u,l,d,p,h){let m=this.entitled("semantic_cache"),g=null;if(i.
1157
- semanticCache&&i.semanticCache!=="include-agentic"&&this.deps.semanticCache&&xl(r,o)&&c.record("semantic-cache",'skipped: agentic traffic (default); set savings.semanticCache: "include-agentic" to inc\
1162
+ semanticCache&&i.semanticCache!=="include-agentic"&&this.deps.semanticCache&&Sl(r,o)&&c.record("semantic-cache",'skipped: agentic traffic (default); set savings.semanticCache: "include-agentic" to inc\
1158
1163
  lude it'),o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache&&!m&&c.record("semantic-cache","degraded: feature not included in this license"),o.allowSemanticCache&&i.semanticCache&&this.deps.
1159
- semanticCache&&m){let E=this.deps.semanticCache,M=E.calibrated?await E.lookup(r,{agentic:o.isAgentic}):{hit:await E.find(r),probe:null},N=M.hit;if(g=M.probe,N)return s.avoidCall(l,this.tokensFor(N.record.
1160
- answer.text,n)),c.record("semantic-cache","hit",{confidence:N.confidence,similarity:N.similarity}),this.finish(n,r,N.record.answer,"semantic",s,a,c,Cn(),En(),N.ageMs,N.confidence,void 0,void 0,void 0,
1161
- this.informeDeCascada(d,{servedModel:n.model}),void 0,void 0,void 0,{semantico:N});c.record("semantic-cache","miss",g?{calibration:g.reason,score:g.score}:void 0);}let f=i.router===false,v=f?Cn():this.deps.
1164
+ semanticCache&&m){let P=this.deps.semanticCache,M=P.calibrated?await P.lookup(r,{agentic:o.isAgentic}):{hit:await P.find(r),probe:null},N=M.hit;if(g=M.probe,N)return s.avoidCall(l,this.tokensFor(N.record.
1165
+ answer.text,n)),c.record("semantic-cache","hit",{confidence:N.confidence,similarity:N.similarity}),this.finish(n,r,N.record.answer,"semantic",s,a,c,En(),Pn(),N.ageMs,N.confidence,void 0,void 0,void 0,
1166
+ this.informeDeCascada(d,{servedModel:n.model}),void 0,void 0,void 0,{semantico:N});c.record("semantic-cache","miss",g?{calibration:g.reason,score:g.score}:void 0);}let f=i.router===false,v=f?En():this.deps.
1162
1167
  router.classify(r);c.record("router",v.executionClass,{confidence:v.confidence,reason:v.reason});let b=this.planearBusquedaNativa(n,i,v.executionClass,f,d,a,c),y=b?b.seleccion:f?this.deps.toolSelector.
1163
- passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,v.executionClass,r.toolsetHash);if(!b&&Bo(i.toolSearch).modo==="off"&&this.avisarDeCatalogoRecortado(n,y,d.modeloServido),s.
1164
- actualTools=y.tools.length,y.droppedIds.length){let E=new Set(y.droppedIds),M=(n.tools??[]).filter(N=>E.has(N.id)).reduce((N,U)=>N+this.tokensFor(Qr(U),n),0);s.eliminate(M),c.record("tool-selector",y.
1165
- reason,{dropped:y.droppedIds,eliminatedTokens:M});}s.baselineRetrieval=this.config.retriever?v.rounds:0;let k=await ka({execution:v.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.maxRounds??
1168
+ passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,v.executionClass,r.toolsetHash);if(!b&&Fo(i.toolSearch).modo==="off"&&this.avisarDeCatalogoRecortado(n,y,d.modeloServido),s.
1169
+ actualTools=y.tools.length,y.droppedIds.length){let P=new Set(y.droppedIds),M=(n.tools??[]).filter(N=>P.has(N.id)).reduce((N,U)=>N+this.tokensFor(Xr(U),n),0);s.eliminate(M),c.record("tool-selector",y.
1170
+ reason,{dropped:y.droppedIds,eliminatedTokens:M});}s.baselineRetrieval=this.config.retriever?v.rounds:0;let k=await wa({execution:v.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.maxRounds??
1166
1171
  v.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});s.actualRetrieval=k.rounds,
1167
- k.retrievedCount>0&&c.record("retrieval",`kept ${k.keptCount}/${k.retrievedCount}`,{rounds:k.rounds});let T=En(),w=[...n.messages],P=vs(n.messages),x=false,S=k.docs.length>0?{role:"system",content:`Retri\
1172
+ k.retrievedCount>0&&c.record("retrieval",`kept ${k.keptCount}/${k.retrievedCount}`,{rounds:k.rounds});let T=Pn(),x=[...n.messages],R=ks(n.messages),D=false,I=k.docs.length>0?{role:"system",content:`Retri\
1168
1173
  eved context \u2014 answer using only this evidence and cite sources by [id]:
1169
1174
 
1170
- `+k.docs.map((E,M)=>`[${E.source??E.id??`doc${M+1}`}]
1171
- ${E.text}`).join(`
1175
+ `+k.docs.map((P,M)=>`[${P.source??P.id??`doc${M+1}`}]
1176
+ ${P.text}`).join(`
1172
1177
 
1173
- `)}:null,O=Pn(n),R=n.response?.maxOutputTokens!=null?Math.floor(n.response.maxOutputTokens*3.2):null,C=this.contratosQueIncumplen.has(O)?bs(n.response?.schema,"",R):"";if(C&&Rn(w,{role:"system",content:`\
1174
- JSON limits (not API-enforced): ${C}`}),n.structuredData!==void 0){let E=JSON.stringify(n.structuredData),M=this.tokensFor(E,n);if(i.serialization!==false){T=this.deps.formatSelector.choose(n.structuredData,
1175
- {model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let N=this.tokensFor(T.encoded+T.instruction,n);s.compress(M,N),Rn(w,{role:"system",content:(T.instruction?T.instruction+`
1176
- `:"")+T.encoded}),c.record("serialization",T.chosen,{reason:T.reason,jsonTokens:M,chosenTokens:N});}else Rn(w,{role:"system",content:E}),c.record("serialization","json-compact",{reason:"format selector\
1177
- disabled; sent compact JSON"});}if(S&&Rn(w,S),(i.compression===true||i.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let E=this.config.compressionEconomics??
1178
- {},M=Kr(n.model,E),N={compressorCostTokens:E.compressorCostTokens??0,...E.minimumContextTokens!=null?{minimumContextTokens:E.minimumContextTokens}:{},...E.minimumNetTokens!=null?{minimumNetTokens:E.minimumNetTokens}:
1179
- {}},U=0,Z=0;for(let ue of w)ue.role==="system"?U+=1:Z+=this.tokensFor(ue.content,n);let Ue=this.tokensFor(this.assemblePromptText(w,y.tools),n),ce=Jo({...N,contextTokens:Z,projectedEliminable:Z}),ie=0,
1180
- H=0,Pe=false,xe=ce.reason;if(ce.compress){let ue=[];for(let J of w){if(J.role==="system"){ue.push(J);continue}let Gt=this.tokensFor(J.content,n),Zt=await this.config.compressor.compress({text:J.content}),
1181
- zs=!Zt.skipped&&Zt.fidelityPassed&&_a(J.content,Zt.compressed),qs=zs?this.tokensFor(Zt.compressed,n):Gt;zs&&qs<Gt?(ue.push({...J,content:Zt.compressed}),ie+=Gt,H+=qs):ue.push(J);}let He=this.tokensFor(
1182
- this.assemblePromptText(ue,y.tools),n),ve=Jo({...N,contextTokens:Z,projectedEliminable:ie-H}),Ln=Yu({originalTokens:Ue,compressedTokens:He,tier:M,...E.prefix?{prefix:E.prefix}:{},compressorCostTokens:N.
1183
- compressorCostTokens});H>=ie?xe="no fidelity-passed net reduction":ve.compress?Ln.comprimir?(Pe=true,xe=Ln.razon,x=ue.slice(0,P).some((J,Gt)=>J.content!==w[Gt]?.content),w=ue,s.compress(ie,H)):xe=Ln.razon:
1184
- xe=ve.reason;}Pe||(ie=0,H=0),c.record("compression",Pe?"applied":"skipped",{reason:xe,before:ie,after:H,contextTokens:Z,promptTokens:Ue,cacheTierMinimum:M.minimumCacheTokens,protectedSystemMessages:U,prefixRewritten:x}),
1185
- s.compressionReport={originalTokens:ie,compressedTokens:H,protectedSpans:U,fidelityPassed:true};}if(i.elision!==false&&o.allowElision&&this.entitled("tool_result_elision")){let E=Gu(w);if(E.indices.length>0){
1186
- let M=this.tokensFor(fs,n),N=0;for(let U of E.indices){let Z=this.tokensFor(w[U].content,n);N+=Math.max(0,Z-M);}(E.indices.some(U=>U<P)&&(x=true),w=Zu(w,E.indices),s.eliminate(N),s.elididoLocal+=N),c.
1187
- record("elision","applied",{elided:E.indices.length,eliminatedTokens:N,grossBytes:E.bytesOriginales,live:hs});}else c.record("elision","skipped",{reason:"no old/large tool_result over the a\
1188
- ge\xD7size threshold"});}let I=eh(this.config.toolOutputCompaction,i.toolOutputCompaction);if(I&&!this.entitled("long_context_compression")&&c.record("tool-output-compaction","degraded: feature not inc\
1189
- luded in this license"),I&&o.allowCompression&&this.entitled("long_context_compression")){let E=ja(w,I),M=0,N=0,U=0,Z=0,Ue={};if(E.compactados.length>0){let ie=w.slice();for(let H of E.compactados){let Pe=w[H.
1190
- indice],xe=this.tokensFor(Pe.content,n),ue=this.tokensFor(H.texto,n);ie[H.indice]={...Pe,content:H.texto},M+=xe,N+=ue,H.enLaCola?U+=Math.max(0,xe-ue):Z+=Math.max(0,xe-ue);for(let He of H.aplicadas)Ue[He]=
1191
- (Ue[He]??0)+1;}w=ie,s.compress(M,N),s.compactedLocal+=Math.max(0,M-N);}let ce=Kr(n.model,this.config.compressionEconomics);c.record("tool-output-compaction",E.compactados.length>0?"applied":"skipped",{compacted:E.
1192
- compactados.length,before:M,after:N,tailSavedTokens:U,replayedSavedTokens:Z,transforms:Ue,fileViewsKeptVerbatim:E.vistasDeFichero,exceptedTools:E.exceptuados,cacheWriteMultiplier:ce.cacheWriteMultiplier,
1178
+ `)}:null,E=Rn(n),S=n.response?.maxOutputTokens!=null?Math.floor(n.response.maxOutputTokens*3.2):null,w=this.contratosQueIncumplen.has(E)?ys(n.response?.schema,"",S):"";if(w&&Dn(x,{role:"system",content:`\
1179
+ JSON limits (not API-enforced): ${w}`}),n.structuredData!==void 0){let P=JSON.stringify(n.structuredData),M=this.tokensFor(P,n);if(i.serialization!==false){T=this.deps.formatSelector.choose(n.structuredData,
1180
+ {model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let N=this.tokensFor(T.encoded+T.instruction,n);s.compress(M,N),Dn(x,{role:"system",content:(T.instruction?T.instruction+`
1181
+ `:"")+T.encoded}),c.record("serialization",T.chosen,{reason:T.reason,jsonTokens:M,chosenTokens:N});}else Dn(x,{role:"system",content:P}),c.record("serialization","json-compact",{reason:"format selector\
1182
+ disabled; sent compact JSON"});}if(I&&Dn(x,I),(i.compression===true||i.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let P=this.config.compressionEconomics??
1183
+ {},M=Gr(n.model,P),N={compressorCostTokens:P.compressorCostTokens??0,...P.minimumContextTokens!=null?{minimumContextTokens:P.minimumContextTokens}:{},...P.minimumNetTokens!=null?{minimumNetTokens:P.minimumNetTokens}:
1184
+ {}},U=0,Z=0;for(let ue of x)ue.role==="system"?U+=1:Z+=this.tokensFor(ue.content,n);let He=this.tokensFor(this.assemblePromptText(x,y.tools),n),ce=Ko({...N,contextTokens:Z,projectedEliminable:Z}),ie=0,
1185
+ H=0,De=false,Se=ce.reason;if(ce.compress){let ue=[];for(let J of x){if(J.role==="system"){ue.push(J);continue}let Zt=this.tokensFor(J.content,n),Yt=await this.config.compressor.compress({text:J.content}),
1186
+ Vs=!Yt.skipped&&Yt.fidelityPassed&&Oa(J.content,Yt.compressed),Us=Vs?this.tokensFor(Yt.compressed,n):Zt;Vs&&Us<Zt?(ue.push({...J,content:Yt.compressed}),ie+=Zt,H+=Us):ue.push(J);}let We=this.tokensFor(
1187
+ this.assemblePromptText(ue,y.tools),n),ye=Ko({...N,contextTokens:Z,projectedEliminable:ie-H}),jn=Xu({originalTokens:He,compressedTokens:We,tier:M,...P.prefix?{prefix:P.prefix}:{},compressorCostTokens:N.
1188
+ compressorCostTokens});H>=ie?Se="no fidelity-passed net reduction":ye.compress?jn.comprimir?(De=true,Se=jn.razon,D=ue.slice(0,R).some((J,Zt)=>J.content!==x[Zt]?.content),x=ue,s.compress(ie,H)):Se=jn.razon:
1189
+ Se=ye.reason;}De||(ie=0,H=0),c.record("compression",De?"applied":"skipped",{reason:Se,before:ie,after:H,contextTokens:Z,promptTokens:He,cacheTierMinimum:M.minimumCacheTokens,protectedSystemMessages:U,prefixRewritten:D}),
1190
+ s.compressionReport={originalTokens:ie,compressedTokens:H,protectedSpans:U,fidelityPassed:true};}if(i.elision!==false&&o.allowElision&&this.entitled("tool_result_elision")){let P=Yu(x);if(P.indices.length>0){
1191
+ let M=this.tokensFor(hs,n),N=0;for(let U of P.indices){let Z=this.tokensFor(x[U].content,n);N+=Math.max(0,Z-M);}(P.indices.some(U=>U<R)&&(D=true),x=Qu(x,P.indices),s.eliminate(N),s.elididoLocal+=N),c.
1192
+ record("elision","applied",{elided:P.indices.length,eliminatedTokens:N,grossBytes:P.bytesOriginales,live:bs});}else c.record("elision","skipped",{reason:"no old/large tool_result over the a\
1193
+ ge\xD7size threshold"});}let C=sh(this.config.toolOutputCompaction,i.toolOutputCompaction);if(C&&!this.entitled("long_context_compression")&&c.record("tool-output-compaction","degraded: feature not inc\
1194
+ luded in this license"),C&&o.allowCompression&&this.entitled("long_context_compression")){let P=$a(x,C),M=0,N=0,U=0,Z=0,He={};if(P.compactados.length>0){let ie=x.slice();for(let H of P.compactados){let De=x[H.
1195
+ indice],Se=this.tokensFor(De.content,n),ue=this.tokensFor(H.texto,n);ie[H.indice]={...De,content:H.texto},M+=Se,N+=ue,H.enLaCola?U+=Math.max(0,Se-ue):Z+=Math.max(0,Se-ue);for(let We of H.aplicadas)He[We]=
1196
+ (He[We]??0)+1;}x=ie,s.compress(M,N),s.compactedLocal+=Math.max(0,M-N);}let ce=Gr(n.model,this.config.compressionEconomics);c.record("tool-output-compaction",P.compactados.length>0?"applied":"skipped",{compacted:P.
1197
+ compactados.length,before:M,after:N,tailSavedTokens:U,replayedSavedTokens:Z,transforms:He,fileViewsKeptVerbatim:P.vistasDeFichero,exceptedTools:P.exceptuados,cacheWriteMultiplier:ce.cacheWriteMultiplier,
1193
1198
  cacheReadMultiplier:ce.cacheReadMultiplier,note:"counted in tokens.compressedInput only; never priced into savings or commission. each tail token saved is one token fewer written now and re-read on ev\
1194
- ery later turn"});}let D=n.response?.schema,A=D&&i.outputCodebook===true?Uu(D,E=>this.tokensFor(E,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,Pn(n),i.outputCodebookMeasuredOutputDeltaTokens)}):
1195
- null;A&&c.record("output-codebook",A.applied?"applied":"skipped",{reason:A.reason,...A.applied?{renamedKeys:A.plan.renamedKeys,codedEnumValues:A.plan.codedEnumValues,schemaTokensOriginal:A.plan.schemaTokensOriginal,
1196
- schemaTokensCompact:A.plan.schemaTokensCompact,modelledShapeSavingTokens:A.plan.modelledShapeSavingTokens,measuredOutputDeltaTokens:A.plan.measuredOutputDeltaTokens,outputDeltaProvenance:A.plan.outputDeltaProvenance,
1197
- breakEvenOutputDeltaTokens:A.plan.breakEvenOutputDeltaTokens,netSavingUsd:A.plan.netSavingUsd,pricedForModel:d.modeloServido}:{}});let j=A?.applied?A.plan.compactSchema:D,B=j?Ia(d.modeloServido,j,this.
1199
+ ery later turn"});}let _=n.response?.schema,O=_&&i.outputCodebook===true?Wu(_,P=>this.tokensFor(P,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,Rn(n),i.outputCodebookMeasuredOutputDeltaTokens)}):
1200
+ null;O&&c.record("output-codebook",O.applied?"applied":"skipped",{reason:O.reason,...O.applied?{renamedKeys:O.plan.renamedKeys,codedEnumValues:O.plan.codedEnumValues,schemaTokensOriginal:O.plan.schemaTokensOriginal,
1201
+ schemaTokensCompact:O.plan.schemaTokensCompact,modelledShapeSavingTokens:O.plan.modelledShapeSavingTokens,measuredOutputDeltaTokens:O.plan.measuredOutputDeltaTokens,outputDeltaProvenance:O.plan.outputDeltaProvenance,
1202
+ breakEvenOutputDeltaTokens:O.plan.breakEvenOutputDeltaTokens,netSavingUsd:O.plan.netSavingUsd,pricedForModel:d.modeloServido}:{}});let j=O?.applied?O.plan.compactSchema:_,B=j?Aa(d.modeloServido,j,this.
1198
1203
  deps.constraintBackends):{backend:"none",reason:"no output contract"};c.record("constraints",B.backend,{reason:B.reason});let V=b?{tools:b.prefijo,setIsStable:y.setIsStable}:y,z=i.toolDiscovery===true&&
1199
- !b,ee=this.config.cacheBreakpointStore?await this.cargarEspejo(n,d.modeloServido,w,V,z):null,L=this.decidirMarcadoDeCache(n,d.modeloServido,w,V,z,x?vs(w,true):P,c,ee),se=this.now();if(p?.senal.aborted)throw new ke(
1200
- e.llamadas>0);let ae=b?this.sinDescubrimientoPorBusquedaNativa(i,y.tools,c):await this.descubrirHerramientas(e,n,i,y.tools,w,s,a,c),G=ae.tools;s.actualTools=G.length;let Wt={messages:w,...G.length?{tools:G}:
1204
+ !b,ee=this.config.cacheBreakpointStore?await this.cargarEspejo(n,d.modeloServido,x,V,z):null,L=this.decidirMarcadoDeCache(n,d.modeloServido,x,V,z,D?ks(x,true):R,c,ee),se=this.now();if(p?.senal.aborted)throw new xe(
1205
+ e.llamadas>0);let ae=b?this.sinDescubrimientoPorBusquedaNativa(i,y.tools,c):await this.descubrirHerramientas(e,n,i,y.tools,x,s,a,c),G=ae.tools;s.actualTools=G.length;let Wt={messages:x,...G.length?{tools:G}:
1201
1206
  {},...j?{schema:j}:{},...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{},...i.deferrable?
1202
- {deferrable:true}:{},...L.explicita?{explicitCacheWrites:true}:{},...b?{toolSearch:b.plan}:{},constraintBackend:B.backend},An={model:d.modeloServido,...Wt,...L.marcar?{stablePrefixMessages:L.mensajesDePrefijo,
1207
+ {deferrable:true}:{},...L.explicita?{explicitCacheWrites:true}:{},...b?{toolSearch:b.plan}:{},constraintBackend:B.backend},On={model:d.modeloServido,...Wt,...L.marcar?{stablePrefixMessages:L.mensajesDePrefijo,
1203
1208
  promptCacheKey:L.huella,...L.colocacion&&!L.explicita&&(L.colocacion.cola||L.colocacion.ttl!=="5m")?{cachePlacement:{tail:L.colocacion.cola,ttl:L.colocacion.ttl}}:{},...this.config.cacheMissDiagnostics===
1204
- true&&L.colocacion?{cacheDiagnostics:{previousMessageId:L.colocacion.coincidencia?.idDelProveedor??null}}:{}}:{}},_,Os=false,Jl={...e};try{_=p?await this.llamarProveedorEnStream(An,e,p):await this.llamarProveedor(
1205
- An,e);}catch(E){if(!this.respaldaFaltaDeCapacidad(i,E,p))throw E;Object.assign(e,Jl),Os=true,c.record("deferred-tier","capacity-fallback",{error:E instanceof Error?E.message.slice(0,200):String(E),reason:'\
1206
- the cheaper tier had no capacity; repeated once at the standard tier and price, as configured with priceLevers.onCapacityError: "standard"'});let{deferrable:M,...N}=An;_=await this.llamarProveedor(N,e);}
1207
- let Kl=ur(_),Gl=_.servedServiceTier;b&&c.record("tool-search","provider",{searches:_.toolSearch?.searches??null,loaded:_.toolSearch?.loaded??[],errors:_.toolSearch?.errors??0,resentResults:_.toolSearch?.
1208
- resent?.results??0,resentTools:_.toolSearch?.resent?.tools??[],reason:_.toolSearch?"what the provider's tool search did in this call; its cost is in the provider's counter and credited to no ledger":"\
1209
- the adapter did not report what the search did"}),s.actualLlm+=1;let mo=E=>{if(!A?.applied)return E;let M=ze(E);return M.ok?JSON.stringify(A.plan.expand(M.value)):E},pe=mo(_.text),Ae=_.usage,Ms={..._.
1210
- providerMessageId?{id:_.providerMessageId}:{},..._.cacheDiagnostics?{diagnostico:_.cacheDiagnostics}:{}},ct=false;if(d.enruta){let E=is({texto:pe,schema:D,finishReason:_.finishReason,pidioHerramientas:(_.
1211
- toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!E.acepta),c.record("model-cascade",E.acepta?"accepted":"escalating",{servedModel:d.modeloServido,reason:E.motivo,checks:E.comprobaciones}),
1212
- E.acepta||(ct=true,s.cascadeAttempt(_.usage,d.precioBarato??a,L.marcar&&L.cacheWriteMultiplier>1?1:un(d.modeloServido)),s.actualLlm+=1,_=await this.llamarProveedor({model:n.model,...Wt},e),pe=mo(_.text));}
1213
- let Ee=ct?n.model:d.modeloServido,Jt=ct?this.costModelFor(n.model,h):a;s.actualInput+=_.usage.inputTokens,s.actualOutput+=_.usage.outputTokens;let Zl=_.usage,Yl=_.servedServiceTier,Ql=_.structuredNatively===
1214
- true,On=ur(_),Xl=Qa(this.config.provider),Ls;A?.applied&&c.record("output-codebook",ze(_.text).ok?"expanded":"not-expanded (response was not JSON)",ze(_.text).ok?{localOutputTokensCompact:this.tokensFor(
1215
- _.text,n),localOutputTokensExpanded:this.tokensFor(pe,n),creditedLedger:"none",note:"local count of the served answer in both shapes; not credited to any ledger"}:{}),D&&B.backend==="provider-native"&&
1216
- _.structuredNatively===false&&(B={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","n\
1217
- one",{downgradedFrom:"provider-native",reason:B.reason})),s.sentInputLocal=this.tokensFor(this.assemblePromptText(w,G),n),s.removedInputLocal=Math.max(0,l-s.sentInputLocal-s.elididoLocal-s.compactedLocal);
1218
- let ed=s.sentInputLocal;s.sentInputLocal+=ae.tokensLocalesDelSondeo,s.estimatorExact=this.estimatorEsExacto(n),_.usage.cachedInputTokens&&s.providerCached(_.usage.cachedInputTokens);let js=un(Ee),td=!ct&&
1219
- L.marcar&&L.cacheWriteMultiplier>1;if(js>1&&!td&&(_.usage.cacheWriteInputTokens??0)>0&&s.providerCacheWritePremium(_.usage.cacheWriteInputTokens??0,js,Jt),L.marcar&&Ae.complete===false)c.record("prefix-c\
1220
- ache","not measured: the provider reported no usage for this call");else if(L.marcar){let E=Math.max(0,Ae.cacheWriteInputTokens??0),M=Math.min(E,Math.max(0,Ae.cacheWrite1hInputTokens??(L.colocacion?.ttl===
1221
- "1h"?E:0)));s.cacheWritePremium(E-M,L.cacheWriteMultiplier,d.precioBarato??a),M>0&&s.cacheWritePremium(M,Qo(d.modeloServido),d.precioBarato??a),this.verjaDeCache.registrar(L.claveDeVerja,Ae),c.record(
1222
- "prefix-cache","measured",{cacheRead:Ae.cachedInputTokens??0,cacheWritePremiumTokens:Ae.cacheWriteInputTokens??0,...M>0?{cacheWrite1hTokens:M}:{}});}L.colocacion?.conAlmacen?await this.apuntarEnElAlmacen(
1223
- L,Ae,c,Ms):L.colocacion&&this.apuntarEnElEspejo(L,Ae,c,this.espejoDeCache,Ms);let yt=null;if(d.modo==="shadow"&&d.elegible&&d.candidato&&d.precioBarato&&Qm(u,d.tasaDeMuestreo))try{let E=await this.llamarProveedor(
1224
- {model:d.candidato,...Wt},e);s.actualLlm+=1;let M=s.extraCostUsd;s.cascadeAttempt(E.usage,d.precioBarato,un(d.candidato));let N=mo(E.text),U=is({texto:N,schema:D,finishReason:E.finishReason,pidioHerramientas:(E.
1225
- toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!U.acepta);let Z=U.acepta?Fu(N,pe):null;yt={coste:s.extraCostUsd-M,divergio:Z?Z.divergen:null},c.record("model-cascade",U.acepta?"sampl\
1226
- e accepted":"sample escalated",{candidateModel:d.candidato,reason:U.motivo,sampleCost:yt.coste,...Z?{diverged:Z.divergen,divergence:Z.motivo}:{},note:"measurement only: this answer was NEVER served. T\
1227
- he escalation rate it feeds is a money figure, not a quality one"});}catch(E){c.record("model-cascade","sample failed (measurement only; the answer is unaffected)",{error:E instanceof Error?E.message:String(
1228
- E)});}let Mn=pe,kt=true,Oe={},Kt=(_.toolCalls?.length??0)>0;if(Kt&&(kt=null,D&&c.record("validation","n/a: model requested tool calls (the output contract applies to the final answer)")),D&&!Kt){let E=ze(
1229
- pe),M=E.ok?de(E.value,D):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},N=false;E.ok&&E.rescatado!=null&&M.valid&&(pe=E.rescatado,N=true,c.record("validation","rescued-locally",{reason:"the model \
1230
- wrapped valid JSON in prose or a markdown fence; it was extracted locally instead of paying a repair call"})),!M.valid&&Xm(M.errors)&&this.contratosQueIncumplen.add(Pn(n));let U=_.finishReason==="leng\
1231
- th",Z=wl(_),Ue=!M.valid&&M.errors.some(ce=>/not a valid regular expression/.test(ce.message));if(!M.valid&&Ue)c.record("validation","repair-skipped",{reason:"schema defect (uncompilable pattern); no o\
1232
- utput can satisfy it, a retry is a wasted call",errors:M.errors}),this.avisar("esquema-roto","[bvsala] The response contract has a `pattern` that is not a valid regex, so no response can satisfy it. N\
1233
- OT retried (it would be a paid call for the same failure). Fix the schema's `pattern`."),Oe.reparacion={outcome:"skipped",skipReason:"schema_defect"};else if(!M.valid&&Z)c.record("validation","repair-\
1234
- skipped",{reason:(_.refusal!==void 0?"the provider refused the request (a refusal message instead of an answer)":"the provider refused the request (finish reason content_filter)")+"; a repair on the s\
1235
- ame model would be refused, and may be billed, again",model:Ee}),Oe.reparacion={outcome:"skipped",skipReason:"provider_refusal"};else if(!M.valid&&U){let ce=qu(D,Pe=>this.tokensFor(Pe,n)),ie=n.response?.
1236
- maxOutputTokens??null,H=ce!==null&&ie!=null&&ce<=ie;H&&this.contratosQueIncumplen.add(Pn(n)),c.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same \
1237
- cap would truncate again",maxOutputTokens:n.response?.maxOutputTokens??null,outputTokens:_.usage.outputTokens,model:Ee,...ce!==null?{schemaAllowsTokens:ce}:{},learnedValueLimits:H}),this.avisarDeTruncado(
1238
- n,Ee,_.usage.outputTokens,ce,H),Oe.reparacion={outcome:"skipped",skipReason:"output_truncated"};}else if(!M.valid&&B.backend==="none"){let ce=M.errors.slice(0,5).map(J=>`- ${J.path}: ${J.message}`).join(
1239
- `
1209
+ true&&L.colocacion?{cacheDiagnostics:{previousMessageId:L.colocacion.coincidencia?.idDelProveedor??null}}:{}}:{}},A,Ls=false,Gl={...e};try{A=p?await this.llamarProveedorEnStream(On,e,p):await this.llamarProveedor(
1210
+ On,e);}catch(P){if(!this.respaldaFaltaDeCapacidad(i,P,p))throw P;Object.assign(e,Gl),Ls=true,c.record("deferred-tier","capacity-fallback",{error:P instanceof Error?P.message.slice(0,200):String(P),reason:'\
1211
+ the cheaper tier had no capacity; repeated once at the standard tier and price, as configured with priceLevers.onCapacityError: "standard"'});let{deferrable:M,...N}=On;A=await this.llamarProveedor(N,e);}
1212
+ let Zl=lr(A),Yl=A.servedServiceTier;b&&c.record("tool-search","provider",{searches:A.toolSearch?.searches??null,loaded:A.toolSearch?.loaded??[],errors:A.toolSearch?.errors??0,resentResults:A.toolSearch?.
1213
+ resent?.results??0,resentTools:A.toolSearch?.resent?.tools??[],reason:A.toolSearch?"what the provider's tool search did in this call; its cost is in the provider's counter and credited to no ledger":"\
1214
+ the adapter did not report what the search did"}),s.actualLlm+=1;let ho=P=>{if(!O?.applied)return P;let M=Ve(P);return M.ok?JSON.stringify(O.plan.expand(M.value)):P},fe=ho(A.text),Me=A.usage,Ql=A.unbilledRefusal===
1215
+ true,js={...A.providerMessageId?{id:A.providerMessageId}:{},...A.cacheDiagnostics?{diagnostico:A.cacheDiagnostics}:{}},ut=false;if(d.enruta){let P=as({texto:fe,schema:_,finishReason:A.finishReason,pidioHerramientas:(A.
1216
+ toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!P.acepta),c.record("model-cascade",P.acepta?"accepted":"escalating",{servedModel:d.modeloServido,reason:P.motivo,checks:P.comprobaciones}),
1217
+ P.acepta||(ut=true,s.cascadeAttempt(A.usage,A.unbilledRefusal===true?{inputPer1k:0,outputPer1k:0,cachedInputPer1k:0}:d.precioBarato??a,L.marcar&&L.cacheWriteMultiplier>1?1:ln(d.modeloServido)),s.actualLlm+=
1218
+ 1,A=await this.llamarProveedor({model:n.model,...Wt},e),fe=ho(A.text));}let Re=ut?n.model:d.modeloServido,Jt=ut?this.costModelFor(n.model,h):a;s.actualInput+=A.usage.inputTokens,s.actualOutput+=A.usage.
1219
+ outputTokens,A.unbilledRefusal===true&&s.unbilledCall(A.usage);let Xl=A.usage,ed=A.servedServiceTier,td=A.structuredNatively===true,Mn=lr(A),nd=ec(this.config.provider),Ns;O?.applied&&c.record("output-cod\
1220
+ ebook",Ve(A.text).ok?"expanded":"not-expanded (response was not JSON)",Ve(A.text).ok?{localOutputTokensCompact:this.tokensFor(A.text,n),localOutputTokensExpanded:this.tokensFor(fe,n),creditedLedger:"n\
1221
+ one",note:"local count of the served answer in both shapes; not credited to any ledger"}:{}),_&&B.backend==="provider-native"&&A.structuredNatively===false&&(B={backend:"none",reason:"provider did not en\
1222
+ force the contract natively; the schema travelled in the prompt and the layer is the only validator"},c.record("constraints","none",{downgradedFrom:"provider-native",reason:B.reason})),s.sentInputLocal=
1223
+ this.tokensFor(this.assemblePromptText(x,G),n),s.removedInputLocal=Math.max(0,l-s.sentInputLocal-s.elididoLocal-s.compactedLocal);let rd=s.sentInputLocal;s.sentInputLocal+=ae.tokensLocalesDelSondeo,s.
1224
+ estimatorExact=this.estimatorEsExacto(n),A.usage.cachedInputTokens&&s.providerCached(A.usage.cachedInputTokens);let $s=ln(Re),od=!ut&&L.marcar&&L.cacheWriteMultiplier>1;if($s>1&&!od&&A.unbilledRefusal!==
1225
+ true&&(A.usage.cacheWriteInputTokens??0)>0&&s.providerCacheWritePremium(A.usage.cacheWriteInputTokens??0,$s,Jt),L.marcar&&Me.complete===false)c.record("prefix-cache","not measured: the provider reported no\
1226
+ usage for this call");else if(L.marcar&&Ql)c.record("prefix-cache","not measured: the marked call was a refusal the provider does not bill");else if(L.marcar){let P=Math.max(0,Me.cacheWriteInputTokens??
1227
+ 0),M=Math.min(P,Math.max(0,Me.cacheWrite1hInputTokens??(L.colocacion?.ttl==="1h"?P:0)));s.cacheWritePremium(P-M,L.cacheWriteMultiplier,d.precioBarato??a),M>0&&s.cacheWritePremium(M,Xo(d.modeloServido),
1228
+ d.precioBarato??a),this.verjaDeCache.registrar(L.claveDeVerja,Me),c.record("prefix-cache","measured",{cacheRead:Me.cachedInputTokens??0,cacheWritePremiumTokens:Me.cacheWriteInputTokens??0,...M>0?{cacheWrite1hTokens:M}:
1229
+ {}});}L.colocacion?.conAlmacen?await this.apuntarEnElAlmacen(L,Me,c,js):L.colocacion&&this.apuntarEnElEspejo(L,Me,c,this.espejoDeCache,js);let kt=null;if(d.modo==="shadow"&&d.elegible&&d.candidato&&d.precioBarato&&
1230
+ oh(u,d.tasaDeMuestreo))try{let P=await this.llamarProveedor({model:d.candidato,...Wt},e);s.actualLlm+=1;let M=s.extraCostUsd;s.cascadeAttempt(P.usage,d.precioBarato,ln(d.candidato));let N=ho(P.text),U=as(
1231
+ {texto:N,schema:_,finishReason:P.finishReason,pidioHerramientas:(P.toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!U.acepta);let Z=U.acepta?qu(N,fe):null;kt={coste:s.extraCostUsd-M,divergio:Z?
1232
+ Z.divergen:null},c.record("model-cascade",U.acepta?"sample accepted":"sample escalated",{candidateModel:d.candidato,reason:U.motivo,sampleCost:kt.coste,...Z?{diverged:Z.divergen,divergence:Z.motivo}:{},
1233
+ note:"measurement only: this answer was NEVER served. The escalation rate it feeds is a money figure, not a quality one"});}catch(P){c.record("model-cascade","sample failed (measurement only; the answe\
1234
+ r is unaffected)",{error:P instanceof Error?P.message:String(P)});}let Ln=fe,xt=true,Le={},Kt=(A.toolCalls?.length??0)>0;if(Kt&&(xt=null,_&&c.record("validation","n/a: model requested tool calls (the out\
1235
+ put contract applies to the final answer)")),_&&!Kt){let P=Ve(fe),M=P.ok?pe(P.value,_):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},N=false;P.ok&&P.rescatado!=null&&M.valid&&(fe=P.rescatado,N=
1236
+ true,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"})),!M.valid&&ih(M.errors)&&this.
1237
+ contratosQueIncumplen.add(Rn(n));let U=A.finishReason==="length",Z=Tl(A),He=!M.valid&&M.errors.some(ce=>/not a valid regular expression/.test(ce.message));if(!M.valid&&He)c.record("validation","repair\
1238
+ -skipped",{reason:"schema defect (uncompilable pattern); no output can satisfy it, a retry is a wasted call",errors:M.errors}),this.avisar("esquema-roto","[bvsala] The response contract has a `pattern\
1239
+ ` that is not a valid regex, so no response can satisfy it. NOT retried (it would be a paid call for the same failure). Fix the schema's `pattern`."),Le.reparacion={outcome:"skipped",skipReason:"schem\
1240
+ a_defect"};else if(!M.valid&&Z)c.record("validation","repair-skipped",{reason:(A.refusal!==void 0?"the provider refused the request (a refusal message instead of an answer)":"the provider refused the \
1241
+ request (finish reason content_filter)")+"; a repair on the same model would be refused, and may be billed, again",model:Re}),Le.reparacion={outcome:"skipped",skipReason:"provider_refusal"};else if(!M.
1242
+ valid&&U){let ce=Uu(_,De=>this.tokensFor(De,n)),ie=n.response?.maxOutputTokens??null,H=ce!==null&&ie!=null&&ce<=ie;H&&this.contratosQueIncumplen.add(Rn(n)),c.record("validation","repair-skipped",{reason:"\
1243
+ output truncated by maxOutputTokens; a retry with the same cap would truncate again",maxOutputTokens:n.response?.maxOutputTokens??null,outputTokens:A.usage.outputTokens,model:Re,...ce!==null?{schemaAllowsTokens:ce}:
1244
+ {},learnedValueLimits:H}),this.avisarDeTruncado(n,Re,A.usage.outputTokens,ce,H),Le.reparacion={outcome:"skipped",skipReason:"output_truncated"};}else if(!M.valid&&B.backend==="none"){let ce=M.errors.slice(
1245
+ 0,5).map(J=>`- ${J.path}: ${J.message}`).join(`
1240
1246
  `),ie=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
1241
1247
 
1242
1248
  Previous reply:
1243
- ${pe}
1249
+ ${fe}
1244
1250
 
1245
1251
  Problems found:
1246
1252
  ${ce}
1247
1253
 
1248
- Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],H=this.tokensFor(this.assemblePromptText(ie),n),Pe=s.sentInputLocal>0?s.actualInput/s.sentInputLocal:1,xe=Math.
1249
- round(Pe*H),ue=Math.min(_.usage.outputTokens,n.response?.maxOutputTokens??Number.POSITIVE_INFINITY),He=xe/1e3*Jt.inputPer1k+ue/1e3*Jt.outputPer1k,ve=this.config.skipRepairAboveBaseline?s.estimateCost(
1250
- Jt):void 0;if(ve!=null&&ve.baselineEstimate>0&&ve.actual+He>ve.baselineEstimate&&ve!=null)c.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the\
1251
- invalid answer is served as-is and reported as invalid",errors:M.errors,baselineUsd:ve.baselineEstimate,actualUsd:ve.actual,repairEstimateUsd:He}),this.avisar("reparacion-mas-cara-que-el-baseline",`[\
1252
- bvsala] The answer did not satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${ve.baselineEstimate}, already spent ~$${ve.
1253
- actual}, 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 req\
1254
- uest carrying both tools and an output contract; see the adapter warning for the cheaper shapes.`),Oe.reparacion={outcome:"skipped",skipReason:"would_cost_more_than_no_layer"};else {s.retries=1,c.record(
1255
- "validation","repair-attempt",{errors:M.errors}),_=await this.llamarProveedor({model:Ee,messages:ie,schema:D,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),Ls=
1256
- _.usage,s.actualLlm+=1,s.actualInput+=_.usage.inputTokens,s.actualOutput+=_.usage.outputTokens,s.repairOutput+=_.usage.outputTokens,s.repairInput+=_.usage.inputTokens,s.sentInputLocal+=H,pe=_.text;let J=ze(
1257
- pe);M=J.ok?de(J.value,D):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},J.ok&&(Mn=J.value,J.rescatado!=null&&M.valid&&(pe=J.rescatado)),Oe.reparacion={outcome:M.valid?"repaired":"still_invali\
1258
- d"};}}else E.ok&&(Mn=E.value);kt=M.valid,!M.valid&&Oe.reparacion===void 0&&(Oe.reparacion={outcome:"skipped",skipReason:"decode_time_constraint"}),Oe.validacion={resultado:M.valid?"passed":"failed",errores:M.
1259
- errors.length,desenvuelto:N},c.record("validation",kt?"valid":"invalid");}let nd=this.now()-se,rd=Km(Mn),xt={text:pe,data:Mn,rendered:rd,storedAtMs:this.now()},Ve=this.informeDeDiferido(i,_,Ee,Os),ut=this.
1260
- informeDeEscrituras(i,Kl,Ae,Gl,d.modeloServido,L.marcar,L.explicitaPorColocador);ut&&c.record("cache-writes",ut.mode,{breakpoints:ut.breakpoints,...ut.avoidedWritePremium?{avoidedWritePremium:ut.avoidedWritePremium.
1261
- amount,basis:"estimated"}:{},creditedLedger:"none",reason:ut.reason}),Ve&&c.record("deferred-tier",Ve.credited?"credited":"not-credited",{...Ve.requestedTier?{requestedTier:Ve.requestedTier}:{},...Ve.
1262
- servedTier?{servedTier:Ve.servedTier}:{},creditedLedger:"none",reason:Ve.reason});let od=ae.aplicado,Ns=_.finishReason==="length",ho=_.replayable===false,$s=wl(_),wt=kt!==false&&!Kt&&!od&&!Ns&&!ho&&!$s,Bs=this.
1263
- generateId(),fe;try{fe=ol({contadorSimulado:Go(this.config.provider),origen:Xl,usoPrimario:Zl,usoReparacion:Ls,tierServido:Yl,eliminatedInput:s.eliminatedInput,compressedInput:s.compressedInput,elididoLocal:s.
1264
- elididoLocal,sentLocalSinSondeo:ed,baselineInput:l,codebookAplicado:A?.applied===!0,tokensDelSondeo:ae.tokensLocalesDelSondeo,sondeoAplicado:ae.aplicado,busquedaNativa:b!==null,hayEsquema:D!=null,esquemaNativo:Ql,
1265
- esquemaEnFormatoNativo:On?.esquemaEnFormatoNativo===!0&&j===D,esquemaEstricto:On?.esquemaEstricto===!0,esquemaPorPrompt:On?.esquemaPorPrompt===!0,piezasDelAdaptador:On?.piezasDelAdaptador??0,modeloPedido:n.
1266
- model,modeloServido:Ee,cacheable:wt,mensajesDeLaCapa:w.length-n.messages.length,requestId:Bs,at:this.now(),textoServido:pe,huella:()=>ms(n)});}catch{fe="fingerprint-failed";}let Fs=wt&&o.allowExactCache&&
1267
- i.exactCache!==false;typeof fe=="object"?c.record("reference","written",{inputTokens:fe.inputTokens,outputTokens:fe.outputTokens,layerInsertions:fe.layerInsertions,...fe.reasoningTokens!==void 0?{reasoningTokens:fe.
1268
- reasoningTokens}:{},exactCache:Fs}):c.record("reference","not-written",{reason:fe});try{wt||c.record("cache-write",Kt?"skipped: tool-call turn (an action request must not be replayed from cache)":kt===
1269
- !1?"skipped: response fails its output contract":Ns?'skipped: answer cut off by the output cap (finish_reason "length"); replaying half an answer would bill it as a 100% avoided call':ho?"skipped: the\
1270
- provider answer carries content this layer cannot replay":$s?'skipped: the provider refused (stop_reason "refusal" / finish_reason "content_filter" / a refusal message); a refusal is not an answer, a\
1271
- nd replaying it would credit an avoided call the provider may not have billed':"skipped: answered with a reduced tool view (tool discovery), so it must not be replayed");let E=ct?Do(r,{servedModel:Ee}):
1272
- u;if(Fs){let N=this.config.exactCacheTtlMs??864e5,U=o.maxCacheAgeMs==null?N:Math.min(N,o.maxCacheAgeMs);await this.deps.exactCache.set(E,typeof fe=="object"?{...xt,meta:{...xt.meta??{},reference:{...fe,
1273
- cacheKey:E}}}:xt,U);}let M=Ee!==n.model;wt&&!M&&o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache?await this.deps.semanticCache.store(r,xt):wt&&M&&i.semanticCache&&c.record("cache-write","\
1274
- semantic write skipped: a cheaper model answered, and this cache keys on the model the caller asked for"),g&&this.deps.semanticCache&&(wt&&!M&&o.allowSemanticCache&&i.semanticCache?(c.record("semantic\
1275
- -calibration","label requested",{reason:g.reason,score:g.score}),this.deps.semanticCache.observe(g,xt)):c.record("semantic-calibration","no label: the cache would not store this answer"));}catch(E){c.record(
1276
- "cache-write","failed (non-fatal; answer already served)",{error:E instanceof Error?E.message:String(E)});}s.callsWithoutUsage=e.sinContador;let St=this.finish(n,r,xt,"miss",s,Jt,c,v,T,void 0,void 0,kt,
1277
- B.backend,nd,this.informeDeCascada(d,{servedModel:Ee,...d.enruta?{escalated:ct}:{},...d.elegible&&d.precioBarato?{estimatedSwapSaving:Ym(s,ct,d.precioBarato,this.costModelFor(n.model,h))}:{},...yt?{sampled:true,
1278
- sampleCost:gt(yt.coste),...yt.divergio!==null?{divergedOnSample:yt.divergio}:{}}:{},...s.cascadeInput>0||s.cascadeOutput>0?{cascadeInputTokens:s.cascadeInput,cascadeOutputTokens:s.cascadeOutput}:{}}),
1279
- Ve,Bs,ut,{...Oe,final:{..._.finishReason!==void 0?{finishReason:_.finishReason}:{},...n.response?.maxOutputTokens!=null?{topeDelLlamante:n.response.maxOutputTokens}:{}}});return typeof fe=="object"&&this.
1280
- referenciasDeLider.set(St,fe),ho&&this.noReproducibles.add(St),Kt&&(St.toolCalls=_.toolCalls),_.finishReason!==void 0&&(St.finishReason=_.finishReason),_.refusal!==void 0&&(St.refusal=_.refusal),St}planearBusquedaNativa(e,n,r,o,i,s,a){
1281
- let c=Bo(n.toolSearch),u=e.tools??[];if(c.modo==="off"||u.length===0)return null;let l=ya(u,r==="TOOL_ACTION",o),d=va({opciones:c,capacidad:ri(this.config.provider),modelo:i.modeloServido,herramientas:l.
1282
- map(g=>({id:g.id,tokens:this.tokensFor(Qr(g),e)})),hayContrato:e.response?.schema!=null,cascadaActiva:i.modo!=="off",precio:s,lecturaDeCache:this.lecturaDeCacheDe(i.modeloServido,s)});if(a.record("too\
1283
- l-search",d.aplicar?"native":"selector",{mode:c.modo,variant:d.variante,reason:d.razon,deferred:d.diferidas,deferredTokens:d.tokensDiferidos,alwaysLoaded:d.siempreCargadas,...d.ahorroDelPrefijo!=null?
1284
- {prefixSavingPerRequest:d.ahorroDelPrefijo}:{},...d.costeDeUnaBusqueda!=null?{worstCaseSearchCost:d.costeDeUnaBusqueda}:{}}),!d.aplicar)return null;let p=new Set(l.map(g=>g.id)),h=new Set(d.siempreCargadas),
1285
- m=c.siempreCargadas.filter(g=>u.some(f=>f.id===g));return {seleccion:{tools:l,droppedIds:u.filter(g=>!p.has(g.id)).map(g=>g.id),reason:d.razon,setIsStable:m.every(g=>p.has(g))},prefijo:l.filter(g=>h.has(
1286
- g.id)),plan:{variant:d.variante,alwaysLoaded:d.siempreCargadas}}}lecturaDeCacheDe(e,n){let r=gs(e,this.config.compressionEconomics)?.cacheReadMultiplier??1,o=n.cachedInputPer1k!=null&&n.inputPer1k>0?n.
1287
- cachedInputPer1k/n.inputPer1k:void 0;return o!=null?Math.min(o,r):r}sinDescubrimientoPorBusquedaNativa(e,n,r){return e.toolDiscovery===true&&r.record("tool-discovery","skipped (native tool search applie\
1288
- s)",{reason:"the provider's tool search already keeps unused schemas out of the prompt, with no second call and without moving the cached prefix"}),{tools:n,tokensLocalesDelSondeo:0,aplicado:false}}avisarDeCatalogoRecortado(e,n,r){
1289
- let o=e.tools??[];n.droppedIds.length===0||!an(o)||ri(this.config.provider)===void 0||!$o(r)||this.avisar("catalogo-recortado-con-busqueda-nativa",`[bv-sala] Your tool catalogue declares no \`intents\` \
1290
- or \`risk\`, so the tool selector has nothing to select on and sent only the first ${n.tools.length} of ${o.length} tools: the model cannot call the others. This provider and model support native tool\
1291
- search: \`savings: { toolSearch: "auto" }\` sends all of them deferred and lets the model search, without breaking the prompt cache. Its effect is the provider's and the layer credits nothing for it.`);}async descubrirHerramientas(e,n,r,o,i,s,a,c){
1292
- let u={tools:o,tokensLocalesDelSondeo:0,aplicado:false};if(r.toolDiscovery!==true)return u;if(o.length<2)return c.record("tool-discovery","skipped (nothing to discover)",{candidates:o.length}),u;let l=f=>this.
1293
- tokensFor(Qr(f),n),d=o.map(el),p=Xu({promptTokens:this.tokensFor(this.assemblePromptText(i),n),esquemasCompletos:o.reduce((f,v)=>f+l(v),0),descriptoresLigeros:d.reduce((f,v)=>f+l(v),0),esquemasDeLaSegunda:nl(
1294
- o.map(f=>({risk:f.risk,tokens:l(f)})),3),salidaFinal:n.response?.maxOutputTokens??256,salidaDelSondeo:96,precio:a});if(!p.aplicar)return c.record("tool-discovery","skipped (not worth a second call)",{
1295
- reason:p.razon,oneCall:p.costeDeUnaLlamada,twoCalls:p.costeDeDosLlamadas}),u;let h,m=this.tokensFor(this.assemblePromptText(i,d),n);try{h=await this.llamarProveedor({model:n.model,messages:i,tools:d,maxOutputTokens:96,
1296
- ...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{}},e);}catch(f){return c.record("tool-discovery","failed (falling back to a single call with every schema)",{error:f instanceof
1297
- Error?f.message:String(f)}),u}s.actualLlm+=1,s.actualInput+=h.usage.inputTokens,s.actualOutput+=h.usage.outputTokens,s.discoveryInput+=h.usage.inputTokens,s.discoveryOutput+=h.usage.outputTokens;let g=tl(
1298
- (h.toolCalls??[]).map(f=>f.name),o,3);return g.reconocidos.length===0?(c.record("tool-discovery","degraded: probe named no known tool",{finishReason:h.finishReason??null,...g.ignorados.length?{unknownNames:g.
1299
- ignorados}:{}}),{tools:o,tokensLocalesDelSondeo:m,aplicado:false}):(c.record("tool-discovery","applied (two provider calls)",{chosen:g.reconocidos,sent:g.tools.map(f=>f.id),candidates:o.length,...g.ignorados.
1300
- length?{unknownNames:g.ignorados}:{}}),{tools:g.tools,tokensLocalesDelSondeo:m,aplicado:true})}informeDeCascada(e,n={}){if(e.modo!=="off")return {mode:e.modo,servedModel:n.servedModel??e.modeloServido,eligible:e.
1301
- elegible,reason:e.razon,verifier:e.fuerza,creditedLedger:"none",...e.candidato?{candidateModel:e.candidato}:{},...e.economia?{costRatio:Tn(e.economia.r),breakEvenEscalationRate:Tn(e.economia.equilibrio),
1302
- targetEscalationRate:Tn(e.economia.escaladoMaximo)}:{},...e.bucket?{workload:e.bucket}:{},...e.observada!=null?{escalationRate:Tn(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,r,o=false){
1303
- if(e.deferrable!==true)return;let i=ur(n),s=i?.origen??null,a=n.servedServiceTier;if(o)return {...dt(this.config.provider)!==void 0?{requestedTier:Rt}:{},...a?{servedTier:a}:{},credited:false,capacityFallback:true,
1304
- creditedLedger:"none",latency:"the cheaper tier refused the request for lack of capacity, and it was repeated once at the standard tier: the wait is the refused attempt plus a standard-tier call.",reason:'\
1305
- the cheaper tier had no capacity (HTTP 429 or 503), so, as configured with priceLevers.onCapacityError: "standard", the request was repeated once at the standard tier and price; the refused attempt is\
1306
- not counted as a call and nothing is credited'};let c=n.requestedServiceTier,u={...c?{requestedTier:c}:{},...a?{servedTier:a}:{},credited:false,creditedLedger:"none",latency:Ua(c,s),reason:""};if(!c)return {
1307
- ...u,reason:Va};let l=this.precioDelCliente(r),d=sr({modelo:r,uso:n.usage,tierServido:a,origen:s,...i?.tierLeidoDe?{tierLeidoDe:i.tierLeidoDe}:{},...l?{precioDelCliente:l}:{},ahoraMs:this.now()});if(!d.
1308
- ok){let p=d.motivo==="no-tier-price"&&s==="openai"&&qa(r,s,this.now())?"; this model's deferred discount is published for the provider's batch API instead: send such requests with layer.batches.submit\
1309
- ()":"";return {...u,reason:Zm(d.motivo,c,a)+p}}return {...u,credited:true,discountRate:Tn(d.factorEfectivo),estimatedTierSaving:d.importe,tierSaving:{amount:d.importe,basis:d.basis,standardCost:gt(d.costeEstandar),
1310
- appliedCost:gt(d.costeAplicado),pricesCheckedOn:d.consultado,basisReason:d.motivoBasis},reason:`the provider reports serving the "${a}" tier; this call's usage was priced at the standard and at the "${a}\
1311
- " published rate cards, component by component (${(d.factorEfectivo*100).toFixed(1)}% of standard). The discount stacks with provider prefix caching rather than replacing it`}}informeDeEscrituras(e,n,r,o,i,s,a=false){
1312
- if(e.standalone!==true&&!a)return;let c=n?.cacheExplicita;if(!c){let f=dt(this.config.provider),v="the provider chose where to write its prompt cache, as it does by default";return {mode:"provider-defaul\
1313
- t",breakpoints:0,reason:lt(i,"openai")?f===void 0?`this provider is not one of this package's adapters, so nothing attests explicit prompt-cache control on it: ${v}`:f!=="openai"?`explicit prompt-cach\
1314
- e control only exists on OpenAI's own API, and this endpoint is not it: ${v}`:`model "${i}" has no list price of its own here, so the layer cannot tell whether writing its prefix pays: ${v}`:`model "${i}\
1315
- " is not an OpenAI model that bills prompt-cache writes above the input rate, so there was no write premium to avoid: ${v}`}}let u=c.puntos,l=(a?`Chosen by cacheBreakpoints: "auto" because continuatio\
1316
- ns of this traffic within 30 minutes were measured below the write premium's break-even (see the prefix-cache-placement trace). `:"")+"Trade-off: repeats and continuations of this exact prompt lose th\
1317
- e cache reads the provider default would have given them.",d=u===1?"explicit mode: the provider wrote its prompt cache only at the end of the stable prefix, so the rest of this request was billed at t\
1318
- he input rate with no cache-write charge. "+l:(s?"explicit mode with no breakpoint: the message at the prefix boundary cannot carry one":"explicit mode with no breakpoint: there was no stable prefix w\
1319
- orth writing, or the measured hit rate on it did not pay for the write premium")+", so the provider neither wrote nor read its prompt cache for this request. "+l,p=o?dn("openai",o,i,this.now()):void 0,
1320
- h=rr(i),m=p&&p.cacheWritePer1k!==void 0?{inputPer1k:p.inputPer1k,cacheWritePer1k:p.cacheWritePer1k,consultado:p.consultado}:h?{inputPer1k:h.inputPer1k,cacheWritePer1k:h.cacheWritePer1k,consultado:void 0}:
1321
- void 0;if(!m||r.complete===false)return {mode:"explicit",breakpoints:u,reason:d};let g=Wa({uso:r,fila:{inputPer1k:m.inputPer1k,cacheWritePer1k:m.cacheWritePer1k},...m.consultado?{consultado:m.consultado}:
1322
- {}});return {mode:"explicit",breakpoints:u,avoidedWritePremium:{amount:g.importe,basis:"estimated",standardCost:gt(g.costeEstandar),appliedCost:gt(g.costeAplicado),pricesCheckedOn:g.consultado,basisReason:g.
1323
- tokensOrdinarios>0&&r.inputTokens>=1024?"estimated: the provider default was not run for this request. This is the write premium the default would have charged on the tokens after the last breakpoint;\
1324
- it does not subtract the cache reads the default could have given a later repeat":"estimated: below the provider's minimum cacheable length (or with nothing written past the breakpoint) the default w\
1325
- ould not have charged a write premium either"},reason:d}}escriturasSinLlamada(e){if(e.savings?.standalone===true)return {mode:"provider-default",breakpoints:0,reason:"no provider call was made, so nothin\
1326
- g was written to or read from the provider's prompt cache for this request"}}respaldaFaltaDeCapacidad(e,n,r){return e.deferrable!==true||r!==null||this.config.priceLevers?.onCapacityError!=="standard"||
1327
- dt(this.config.provider)===void 0?false:n instanceof Error&&/^provider (429|503)\b/.test(n.message)}diferidoSinLlamada(e){if(e.savings?.deferrable===true)return {credited:false,creditedLedger:"none",latency:"n\
1328
- ot applicable: no provider call was made for this request.",reason:"no provider call was made, so no processing tier was served and none is credited; the call was avoided outright, which is worth more\
1329
- than any tier discount on it"}}finish(e,n,r,o,i,s,a,c,u,l,d,p,h="none",m=0,g,f,v,b,y){let k=e.response?.schema,T,w=p===null?null:p??(k?(()=>{let S=de(r.data,k);return T={resultado:S.valid?"passed":"f\
1330
- ailed",errores:S.errors.length,desenvuelto:false},S.valid})():true),P=T&&!y?.validacion?{...y,validacion:T}:y,x=this.buildReport(e,n,o,i,s,a,c,u,l,d,w,h,m,g,f??this.diferidoSinLlamada(e),v,b??this.escriturasSinLlamada(
1331
- e),P);return {requestId:x.requestId,data:r.data,text:r.text,...r.rendered!==void 0?{rendered:r.rendered}:{},report:x}}buildReport(e,n,r,o,i,s,a,c,u,l,d,p,h,m,g,f,v,b){let y=o.estimateCost(i),k=s.elapsed(),
1332
- T=m!=null&&m.servedModel!==m.requestedModel;return {requestId:f??this.generateId(),model:m?.servedModel??e.model,calls:{baselineLlm:o.baselineLlm,actualLlm:o.actualLlm,avoidedLlm:o.avoidedLlm,baselineRetrieval:o.
1333
- baselineRetrieval,actualRetrieval:o.actualRetrieval,baselineTools:o.baselineTools,actualTools:o.actualTools,retries:o.retries},tokens:{baselineInput:o.baselineInput,actualInput:o.actualInput,eliminatedInput:o.
1334
- eliminatedInput,compressedInput:o.compressedInput,baselineOutput:o.publishedBaselineOutput,actualOutput:o.actualOutput,eliminatedOutput:o.eliminatedOutput,...o.providerCachedInput?{providerCachedInput:o.
1335
- providerCachedInput}:{}},cache:{result:r,...l!==void 0?{confidence:l}:{},...u!==void 0?{ageMs:u}:{},...o.reference?{reference:{...o.reference}}:{},...o.referenceRejected?{referenceRejected:o.referenceRejected}:
1336
- {}},routing:{executionClass:a.executionClass,confidence:a.confidence,rounds:o.actualRetrieval,reason:a.reason},serialization:{chosen:c.chosen,candidateTokens:c.candidateTokens,instructionOverheadTokens:c.
1337
- instructionOverheadTokens},...o.compressionReport?{compression:o.compressionReport}:{},constraints:{backend:p,schemaVersion:n.schemaVersion,...d===null?{}:{structurallyValid:d}},qualityStatus:Gm(r,d,T),
1338
- qualityLedger:al({cacheResult:r,structurallyValid:d,backend:p,hayEsquema:e.response?.schema!=null,ageMs:u,cascada:m,hechos:b}),...m?{modelCascade:m}:{},...g?{deferred:g}:{},...v?{cacheWrites:v}:{},quality:{
1339
- ...r!=="miss"?{freshnessPassed:!Fn(n).requiresFreshData}:{},...r==="semantic"&&b?.semantico?{semanticScore:b.semantico.similarity}:{}},cost:y,latencyMs:{total:k,preprocessing:Math.max(0,k-h),provider:h},
1340
- traces:s.all()}}async failOpenDirect(e,n){let r=new mn(this.now);r.record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",{error:n instanceof Error?n.message:String(n)});
1341
- let o=new Et,i=this.costModelFor(e.model),s;try{s=Ro(e);}catch{s={schemaVersion:e.response?.version??e.response?.contractId??"none"};}let a=e.response?.schema,c=[...e.messages];e.structuredData!==void 0&&
1342
- Rn(c,{role:"system",content:JSON.stringify(e.structuredData)});let u=this.now(),l=await this.config.provider.generate({model:e.model,messages:c,...e.tools?.length?{tools:e.tools}:{},...a?{schema:a}:{},
1343
- ...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),d=this.now()-u;o.baselineLlm=
1344
- 1,o.actualLlm=1,o.actualInput=l.usage.inputTokens,o.actualOutput=l.usage.outputTokens,o.baselineInput=l.usage.inputTokens,o.baselineOutput=l.usage.outputTokens,l.usage.cachedInputTokens&&o.providerCached(
1345
- l.usage.cachedInputTokens);let p=un(e.model);p>1&&(l.usage.cacheWriteInputTokens??0)>0&&o.providerCacheWritePremium(l.usage.cacheWriteInputTokens??0,p,i),l.usage.complete===false&&(o.callsWithoutUsage=1);
1346
- let h=l.text,m=true,g={origen:"fail_open",final:{...l.finishReason!==void 0?{finishReason:l.finishReason}:{},...e.response?.maxOutputTokens!=null?{topeDelLlamante:e.response.maxOutputTokens}:{}}},f=(l.toolCalls?.
1347
- length??0)>0;if(f&&(m=null),a&&!f){let b=ze(l.text),y=b.ok?de(b.value,a).errors.length:1;m=y===0,g.validacion={resultado:m?"passed":"failed",errores:y,desenvuelto:false},b.ok&&(h=b.value);}let v=this.buildReport(
1348
- e,s,"miss",o,i,r,Cn(),En(),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 req\
1349
- uest was scheduled 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 o\
1350
- f capacity, and trading availability for a discount on a last-resort call is the wrong trade"}:void 0,void 0,e.savings?.standalone===true?{mode:"provider-default",breakpoints:0,reason:"the optimizer fai\
1351
- led and this request went out unchanged on the direct fail-open path, so the provider chose where to write its prompt cache, as it does by default"}:void 0,g);return {requestId:v.requestId,data:h,text:l.
1352
- text,...f?{toolCalls:l.toolCalls}:{},...l.finishReason!==void 0?{finishReason:l.finishReason}:{},...l.refusal!==void 0?{refusal:l.refusal}:{},report:v}}asCoalescedFollower(e,n,r,o,i,s={ok:false,reason:"a\
1353
- bsent"}){let a=new Et;s.ok?a.avoidCallByReference(s.credit):(a.avoidCall(n,r),a.referenceRejected=s.reason);let c=a.estimateCost(o),u=this.generateId(),l=this.diferidoSinLlamada(i),d=l?{deferred:l}:{},
1354
- p=this.escriturasSinLlamada(i),{deferred:h,streaming:m,cacheWrites:g,...f}=e.report;return {...e,requestId:u,report:{...f,requestId:u,calls:{...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:a.
1355
- baselineInput,actualInput:a.actualInput,eliminatedInput:a.eliminatedInput,compressedInput:a.compressedInput,baselineOutput:a.publishedBaselineOutput,actualOutput:a.actualOutput,eliminatedOutput:a.eliminatedOutput,
1356
- ...a.providerCachedInput?{providerCachedInput:a.providerCachedInput}:{}},cache:{result:"singleflight",...a.reference?{reference:{...a.reference}}:a.referenceRejected?{referenceRejected:a.referenceRejected}:
1357
- {}},...d,...p?{cacheWrites:p}:{},qualityLedger:cl(e.report.qualityLedger),cost:c}}}creditoPorReferencia(e,n){if(typeof e=="string")return {ok:false,reason:e};let r;try{r=n.calidad();}catch{r=false;}try{return sl(
1358
- e,{ahoraMs:this.now(),modeloPedido:n.request.model,modeloServido:n.cascada.modeloServido,huella:n.huella(),textoServidoSha256:Y(n.texto),claveLeida:n.claveLeida,calidadOk:r,precio:this.precioDocumentado(
1359
- n.request.model),determinista:rl(n.request),salidaDelModelo:Cu(n.request.model),topeDeSalida:n.request.response?.maxOutputTokens,diferible:n.toggles.deferrable===!0})}catch{return {ok:false,reason:"differ\
1360
- ent-request"}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,r){let o=e.map(i=>i.content);r!==void 0&&o.push(JSON.stringify(r));for(let i of n??
1361
- [])o.push(Qr(i));return o.join(`
1254
+ Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],H=this.tokensFor(this.assemblePromptText(ie),n),De=s.sentInputLocal>0?s.actualInput/s.sentInputLocal:1,Se=Math.
1255
+ round(De*H),ue=Math.min(A.usage.outputTokens,n.response?.maxOutputTokens??Number.POSITIVE_INFINITY),We=Se/1e3*Jt.inputPer1k+ue/1e3*Jt.outputPer1k,ye=this.config.skipRepairAboveBaseline?s.estimateCost(
1256
+ Jt):void 0;if(ye!=null&&ye.baselineEstimate>0&&ye.actual+We>ye.baselineEstimate&&ye!=null)c.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the\
1257
+ invalid answer is served as-is and reported as invalid",errors:M.errors,baselineUsd:ye.baselineEstimate,actualUsd:ye.actual,repairEstimateUsd:We}),this.avisar("reparacion-mas-cara-que-el-baseline",`[\
1258
+ bvsala] The answer did not satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${ye.baselineEstimate}, already spent ~$${ye.
1259
+ actual}, repair ~$${We.toFixed(6)}). The repair was skipped and the invalid answer is returned with \`constraints.structurallyValid: false\` \u2014 check it before using it. This combination is usually a req\
1260
+ uest carrying both tools and an output contract; see the adapter warning for the cheaper shapes.`),Le.reparacion={outcome:"skipped",skipReason:"would_cost_more_than_no_layer"};else {s.retries=1,c.record(
1261
+ "validation","repair-attempt",{errors:M.errors}),A=await this.llamarProveedor({model:Re,messages:ie,schema:_,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),Ns=
1262
+ A.usage,s.actualLlm+=1,s.actualInput+=A.usage.inputTokens,s.actualOutput+=A.usage.outputTokens,s.repairOutput+=A.usage.outputTokens,s.repairInput+=A.usage.inputTokens,A.unbilledRefusal===true&&s.unbilledCall(
1263
+ A.usage),s.sentInputLocal+=H,fe=A.text;let J=Ve(fe);M=J.ok?pe(J.value,_):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},J.ok&&(Ln=J.value,J.rescatado!=null&&M.valid&&(fe=J.rescatado)),Le.reparacion=
1264
+ {outcome:M.valid?"repaired":"still_invalid"};}}else P.ok&&(Ln=P.value);xt=M.valid,!M.valid&&Le.reparacion===void 0&&(Le.reparacion={outcome:"skipped",skipReason:"decode_time_constraint"}),Le.validacion=
1265
+ {resultado:M.valid?"passed":"failed",errores:M.errors.length,desenvuelto:N},c.record("validation",xt?"valid":"invalid");}let id=this.now()-se,sd=eh(Ln),wt={text:fe,data:Ln,rendered:sd,storedAtMs:this.now()},
1266
+ de=this.informeDeDiferido(i,A,Re,Ls),we=this.informeDeEscrituras(i,Zl,Me,Yl,d.modeloServido,L.marcar,L.explicitaPorColocador);we&&c.record("cache-writes",we.mode,{breakpoints:we.breakpoints,...we.avoidedWritePremium?
1267
+ {avoidedWritePremium:we.avoidedWritePremium.amount,basis:"estimated"}:{},creditedLedger:"none",reason:we.reason}),de&&c.record("deferred-tier",de.credited?"credited":"not-credited",{...de.requestedTier?
1268
+ {requestedTier:de.requestedTier}:{},...de.servedTier?{servedTier:de.servedTier}:{},creditedLedger:"none",reason:de.reason});let ad=ae.aplicado,Bs=A.finishReason==="length",go=A.replayable===false,Fs=Tl(A),
1269
+ St=xt!==false&&!Kt&&!ad&&!Bs&&!go&&!Fs,zs=this.generateId(),me;try{me=sl({contadorSimulado:Zo(this.config.provider),origen:nd,usoPrimario:Xl,usoReparacion:Ns,tierServido:ed,eliminatedInput:s.eliminatedInput,
1270
+ compressedInput:s.compressedInput,elididoLocal:s.elididoLocal,sentLocalSinSondeo:rd,baselineInput:l,codebookAplicado:O?.applied===!0,tokensDelSondeo:ae.tokensLocalesDelSondeo,sondeoAplicado:ae.aplicado,
1271
+ busquedaNativa:b!==null,hayEsquema:_!=null,esquemaNativo:td,esquemaEnFormatoNativo:Mn?.esquemaEnFormatoNativo===!0&&j===_,esquemaEstricto:Mn?.esquemaEstricto===!0,esquemaPorPrompt:Mn?.esquemaPorPrompt===
1272
+ !0,piezasDelAdaptador:Mn?.piezasDelAdaptador??0,modeloPedido:n.model,modeloServido:Re,cacheable:St,mensajesDeLaCapa:x.length-n.messages.length,requestId:zs,at:this.now(),textoServido:fe,huella:()=>gs(
1273
+ n)});}catch{me="fingerprint-failed";}let qs=St&&o.allowExactCache&&i.exactCache!==false;typeof me=="object"?c.record("reference","written",{inputTokens:me.inputTokens,outputTokens:me.outputTokens,layerInsertions:me.
1274
+ layerInsertions,...me.reasoningTokens!==void 0?{reasoningTokens:me.reasoningTokens}:{},exactCache:qs}):c.record("reference","not-written",{reason:me});try{St||c.record("cache-write",Kt?"skipped: tool-\
1275
+ call turn (an action request must not be replayed from cache)":xt===!1?"skipped: response fails its output contract":Bs?'skipped: answer cut off by the output cap (finish_reason "length"); replaying h\
1276
+ alf an answer would bill it as a 100% avoided call':go?"skipped: the provider answer carries content this layer cannot replay":Fs?'skipped: the provider refused (stop_reason "refusal" / finish_reason \
1277
+ "content_filter" / a refusal message); a refusal is not an answer, and replaying it would credit an avoided call the provider may not have billed':"skipped: answered with a reduced tool view (tool dis\
1278
+ covery), so it must not be replayed");let P=ut?Io(r,{servedModel:Re}):u;if(qs){let N=this.config.exactCacheTtlMs??864e5,U=o.maxCacheAgeMs==null?N:Math.min(N,o.maxCacheAgeMs);await this.deps.exactCache.
1279
+ set(P,typeof me=="object"?{...wt,meta:{...wt.meta??{},reference:{...me,cacheKey:P}}}:wt,U);}let M=Re!==n.model;St&&!M&&o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache?await this.deps.semanticCache.
1280
+ store(r,wt):St&&M&&i.semanticCache&&c.record("cache-write","semantic write skipped: a cheaper model answered, and this cache keys on the model the caller asked for"),g&&this.deps.semanticCache&&(St&&!M&&
1281
+ o.allowSemanticCache&&i.semanticCache?(c.record("semantic-calibration","label requested",{reason:g.reason,score:g.score}),this.deps.semanticCache.observe(g,wt)):c.record("semantic-calibration","no lab\
1282
+ el: the cache would not store this answer"));}catch(P){c.record("cache-write","failed (non-fatal; answer already served)",{error:P instanceof Error?P.message:String(P)});}s.callsWithoutUsage=e.sinContador;
1283
+ let Gt=A.unbilledRefusal===true;Gt&&(s.servedUnbilledRefusal=true,c.record("cost","unbilled refusal: measured at 0, no saving credited",{reason:"the provider documents a refusal before any output in this \
1284
+ category as not billed; its tokens stay counted, priced at 0, and nothing is credited against a request that cost nothing"}));let cd=Gt&&de?.credited?{...de.requestedTier?{requestedTier:de.requestedTier}:
1285
+ {},...de.servedTier?{servedTier:de.servedTier}:{},credited:false,creditedLedger:"none",latency:de.latency,reason:"the provider did not bill this call (a refusal it documents as not billed), so no tier di\
1286
+ scount is credited"}:de,ud=Gt&&we?.avoidedWritePremium?{mode:we.mode,breakpoints:we.breakpoints,reason:we.reason}:we,lt=this.finish(n,r,wt,"miss",s,Jt,c,v,T,void 0,void 0,xt,B.backend,id,this.informeDeCascada(
1287
+ d,{servedModel:Re,...d.enruta?{escalated:ut}:{},...d.elegible&&d.precioBarato&&!Gt?{estimatedSwapSaving:rh(s,ut,d.precioBarato,this.costModelFor(n.model,h))}:{},...kt?{sampled:true,sampleCost:bt(kt.coste),
1288
+ ...kt.divergio!==null?{divergedOnSample:kt.divergio}:{}}:{},...s.cascadeInput>0||s.cascadeOutput>0?{cascadeInputTokens:s.cascadeInput,cascadeOutputTokens:s.cascadeOutput}:{}}),cd,zs,ud,{...Le,final:{...A.
1289
+ finishReason!==void 0?{finishReason:A.finishReason}:{},...n.response?.maxOutputTokens!=null?{topeDelLlamante:n.response.maxOutputTokens}:{}}});return typeof me=="object"&&this.referenciasDeLider.set(lt,
1290
+ me),go&&this.noReproducibles.add(lt),Gt&&this.negativasSinCobro.add(lt),Kt&&(lt.toolCalls=A.toolCalls),A.finishReason!==void 0&&(lt.finishReason=A.finishReason),A.refusal!==void 0&&(lt.refusal=A.refusal),
1291
+ lt}planearBusquedaNativa(e,n,r,o,i,s,a){let c=Fo(n.toolSearch),u=e.tools??[];if(c.modo==="off"||u.length===0)return null;let l=xa(u,r==="TOOL_ACTION",o),d=ka({opciones:c,capacidad:oi(this.config.provider),
1292
+ modelo:i.modeloServido,herramientas:l.map(g=>({id:g.id,tokens:this.tokensFor(Xr(g),e)})),hayContrato:e.response?.schema!=null,cascadaActiva:i.modo!=="off",precio:s,lecturaDeCache:this.lecturaDeCacheDe(
1293
+ i.modeloServido,s)});if(a.record("tool-search",d.aplicar?"native":"selector",{mode:c.modo,variant:d.variante,reason:d.razon,deferred:d.diferidas,deferredTokens:d.tokensDiferidos,alwaysLoaded:d.siempreCargadas,
1294
+ ...d.ahorroDelPrefijo!=null?{prefixSavingPerRequest:d.ahorroDelPrefijo}:{},...d.costeDeUnaBusqueda!=null?{worstCaseSearchCost:d.costeDeUnaBusqueda}:{}}),!d.aplicar)return null;let p=new Set(l.map(g=>g.
1295
+ id)),h=new Set(d.siempreCargadas),m=c.siempreCargadas.filter(g=>u.some(f=>f.id===g));return {seleccion:{tools:l,droppedIds:u.filter(g=>!p.has(g.id)).map(g=>g.id),reason:d.razon,setIsStable:m.every(g=>p.
1296
+ has(g))},prefijo:l.filter(g=>h.has(g.id)),plan:{variant:d.variante,alwaysLoaded:d.siempreCargadas}}}lecturaDeCacheDe(e,n){let r=vs(e,this.config.compressionEconomics)?.cacheReadMultiplier??1,o=n.cachedInputPer1k!=
1297
+ null&&n.inputPer1k>0?n.cachedInputPer1k/n.inputPer1k:void 0;return o!=null?Math.min(o,r):r}sinDescubrimientoPorBusquedaNativa(e,n,r){return e.toolDiscovery===true&&r.record("tool-discovery","skipped (na\
1298
+ tive tool search applies)",{reason:"the provider's tool search already keeps unused schemas out of the prompt, with no second call and without moving the cached prefix"}),{tools:n,tokensLocalesDelSondeo:0,
1299
+ aplicado:false}}avisarDeCatalogoRecortado(e,n,r){let o=e.tools??[];n.droppedIds.length===0||!cn(o)||oi(this.config.provider)===void 0||!Bo(r)||this.avisar("catalogo-recortado-con-busqueda-nativa",`[bv-sa\
1300
+ la] Your tool catalogue declares no \`intents\` or \`risk\`, so the tool selector has nothing to select on and sent only the first ${n.tools.length} of ${o.length} tools: the model cannot call the oth\
1301
+ ers. This provider and model support native tool search: \`savings: { toolSearch: "auto" }\` sends all of them deferred and lets the model search, without breaking the prompt cache. Its effect is the pr\
1302
+ ovider's and the layer credits nothing for it.`);}async descubrirHerramientas(e,n,r,o,i,s,a,c){let u={tools:o,tokensLocalesDelSondeo:0,aplicado:false};if(r.toolDiscovery!==true)return u;if(o.length<2)return c.
1303
+ record("tool-discovery","skipped (nothing to discover)",{candidates:o.length}),u;let l=f=>this.tokensFor(Xr(f),n),d=o.map(nl),p=tl({promptTokens:this.tokensFor(this.assemblePromptText(i),n),esquemasCompletos:o.
1304
+ reduce((f,v)=>f+l(v),0),descriptoresLigeros:d.reduce((f,v)=>f+l(v),0),esquemasDeLaSegunda:ol(o.map(f=>({risk:f.risk,tokens:l(f)})),3),salidaFinal:n.response?.maxOutputTokens??256,salidaDelSondeo:96,precio:a});
1305
+ if(!p.aplicar)return c.record("tool-discovery","skipped (not worth a second call)",{reason:p.razon,oneCall:p.costeDeUnaLlamada,twoCalls:p.costeDeDosLlamadas}),u;let h,m=this.tokensFor(this.assemblePromptText(
1306
+ i,d),n);try{h=await this.llamarProveedor({model:n.model,messages:i,tools:d,maxOutputTokens:96,...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{}},e);}catch(f){return c.
1307
+ record("tool-discovery","failed (falling back to a single call with every schema)",{error:f instanceof Error?f.message:String(f)}),u}s.actualLlm+=1,s.actualInput+=h.usage.inputTokens,s.actualOutput+=h.
1308
+ usage.outputTokens,s.discoveryInput+=h.usage.inputTokens,s.discoveryOutput+=h.usage.outputTokens;let g=rl((h.toolCalls??[]).map(f=>f.name),o,3);return g.reconocidos.length===0?(c.record("tool-discover\
1309
+ y","degraded: probe named no known tool",{finishReason:h.finishReason??null,...g.ignorados.length?{unknownNames:g.ignorados}:{}}),{tools:o,tokensLocalesDelSondeo:m,aplicado:false}):(c.record("tool-discov\
1310
+ ery","applied (two provider calls)",{chosen:g.reconocidos,sent:g.tools.map(f=>f.id),candidates:o.length,...g.ignorados.length?{unknownNames:g.ignorados}:{}}),{tools:g.tools,tokensLocalesDelSondeo:m,aplicado:true})}informeDeCascada(e,n={}){
1311
+ 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}:{},
1312
+ ...e.economia?{costRatio:Cn(e.economia.r),breakEvenEscalationRate:Cn(e.economia.equilibrio),targetEscalationRate:Cn(e.economia.escaladoMaximo)}:{},...e.bucket?{workload:e.bucket}:{},...e.observada!=null?
1313
+ {escalationRate:Cn(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,r,o=false){if(e.deferrable!==true)return;let i=lr(n),s=i?.origen??null,a=n.servedServiceTier;
1314
+ if(o)return {...pt(this.config.provider)!==void 0?{requestedTier:Rt}:{},...a?{servedTier:a}:{},credited:false,capacityFallback:true,creditedLedger:"none",latency:"the cheaper tier refused the request for la\
1315
+ ck of capacity, and it was repeated once at the standard tier: the wait is the refused attempt plus a standard-tier call.",reason:'the cheaper tier had no capacity (HTTP 429 or 503), so, as configured\
1316
+ with priceLevers.onCapacityError: "standard", the request was repeated once at the standard tier and price; the refused attempt is not counted as a call and nothing is credited'};let c=n.requestedServiceTier,
1317
+ u={...c?{requestedTier:c}:{},...a?{servedTier:a}:{},credited:false,creditedLedger:"none",latency:Wa(c,s),reason:""};if(!c)return {...u,reason:Ha};let l=this.precioDelCliente(r),d=ar({modelo:r,uso:n.usage,
1318
+ tierServido:a,origen:s,...i?.tierLeidoDe?{tierLeidoDe:i.tierLeidoDe}:{},...l?{precioDelCliente:l}:{},ahoraMs:this.now()});if(!d.ok){let p=d.motivo==="no-tier-price"&&s==="openai"&&Ua(r,s,this.now())?"\
1319
+ ; this model's deferred discount is published for the provider's batch API instead: send such requests with layer.batches.submit()":"";return {...u,reason:nh(d.motivo,c,a)+p}}return {...u,credited:true,discountRate:Cn(
1320
+ d.factorEfectivo),estimatedTierSaving:d.importe,tierSaving:{amount:d.importe,basis:d.basis,standardCost:bt(d.costeEstandar),appliedCost:bt(d.costeAplicado),pricesCheckedOn:d.consultado,basisReason:d.motivoBasis},
1321
+ reason:`the provider reports serving the "${a}" tier; this call's usage was priced at the standard and at the "${a}" published rate cards, component by component (${(d.factorEfectivo*100).toFixed(1)}%\
1322
+ of standard). The discount stacks with provider prefix caching rather than replacing it`}}informeDeEscrituras(e,n,r,o,i,s,a=false){if(e.standalone!==true&&!a)return;let c=n?.cacheExplicita;if(!c){let f=pt(
1323
+ this.config.provider),v="the provider chose where to write its prompt cache, as it does by default";return {mode:"provider-default",breakpoints:0,reason:dt(i,"openai")?f===void 0?`this provider is not \
1324
+ one of this package's adapters, so nothing attests explicit prompt-cache control on it: ${v}`:f!=="openai"?`explicit prompt-cache control only exists on OpenAI's own API, and this endpoint is not it: ${v}`:
1325
+ `model "${i}" has no list price of its own here, so the layer cannot tell whether writing its prefix pays: ${v}`:`model "${i}" is not an OpenAI model that bills prompt-cache writes above the input rat\
1326
+ e, so there was no write premium to avoid: ${v}`}}let u=c.puntos,l=(a?`Chosen by cacheBreakpoints: "auto" because continuations of this traffic within 30 minutes were measured below the write premium'\
1327
+ s break-even (see the prefix-cache-placement trace). `:"")+"Trade-off: repeats and continuations of this exact prompt lose the cache reads the provider default would have given them.",d=u===1?"explici\
1328
+ t mode: the provider wrote its prompt cache only at the end of the stable prefix, so the rest of this request was billed at the input rate with no cache-write charge. "+l:(s?"explicit mode with no bre\
1329
+ akpoint: the message at the prefix boundary cannot carry one":"explicit mode with no breakpoint: there was no stable prefix worth writing, or the measured hit rate on it did not pay for the write prem\
1330
+ ium")+", so the provider neither wrote nor read its prompt cache for this request. "+l,p=o?pn("openai",o,i,this.now()):void 0,h=or(i),m=p&&p.cacheWritePer1k!==void 0?{inputPer1k:p.inputPer1k,cacheWritePer1k:p.
1331
+ cacheWritePer1k,consultado:p.consultado}:h?{inputPer1k:h.inputPer1k,cacheWritePer1k:h.cacheWritePer1k,consultado:void 0}:void 0;if(!m||r.complete===false)return {mode:"explicit",breakpoints:u,reason:d};let g=Ka(
1332
+ {uso:r,fila:{inputPer1k:m.inputPer1k,cacheWritePer1k:m.cacheWritePer1k},...m.consultado?{consultado:m.consultado}:{}});return {mode:"explicit",breakpoints:u,avoidedWritePremium:{amount:g.importe,basis:"\
1333
+ estimated",standardCost:bt(g.costeEstandar),appliedCost:bt(g.costeAplicado),pricesCheckedOn:g.consultado,basisReason:g.tokensOrdinarios>0&&r.inputTokens>=1024?"estimated: the provider default was not \
1334
+ run for this request. This is the write premium the default would have charged on the tokens after the last breakpoint; it does not subtract the cache reads the default could have given a later repeat":
1335
+ "estimated: below the provider's minimum cacheable length (or with nothing written past the breakpoint) the default would not have charged a write premium either"},reason:d}}escriturasSinLlamada(e){if(e.
1336
+ savings?.standalone===true)return {mode:"provider-default",breakpoints:0,reason:"no provider call was made, so nothing was written to or read from the provider's prompt cache for this request"}}respaldaFaltaDeCapacidad(e,n,r){
1337
+ return e.deferrable!==true||r!==null||this.config.priceLevers?.onCapacityError!=="standard"||pt(this.config.provider)===void 0?false:n instanceof Error&&/^provider (429|503)\b/.test(n.message)}diferidoSinLlamada(e){
1338
+ 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 made, so no processing tier wa\
1339
+ s 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,i,s,a,c,u,l,d,p,h="none",m=0,g,f,v,b,y){let k=e.response?.schema,T,x=p===
1340
+ null?null:p??(k?(()=>{let I=pe(r.data,k);return T={resultado:I.valid?"passed":"failed",errores:I.errors.length,desenvuelto:false},I.valid})():true),R=T&&!y?.validacion?{...y,validacion:T}:y,D=this.buildReport(
1341
+ e,n,o,i,s,a,c,u,l,d,x,h,m,g,f??this.diferidoSinLlamada(e),v,b??this.escriturasSinLlamada(e),R);return {requestId:D.requestId,data:r.data,text:r.text,...r.rendered!==void 0?{rendered:r.rendered}:{},report:D}}buildReport(e,n,r,o,i,s,a,c,u,l,d,p,h,m,g,f,v,b){
1342
+ let y=o.estimateCost(i),k=s.elapsed(),T=m!=null&&m.servedModel!==m.requestedModel;return {requestId:f??this.generateId(),model:m?.servedModel??e.model,calls:{baselineLlm:o.baselineLlm,actualLlm:o.actualLlm,
1343
+ avoidedLlm:o.avoidedLlm,baselineRetrieval:o.baselineRetrieval,actualRetrieval:o.actualRetrieval,baselineTools:o.baselineTools,actualTools:o.actualTools,retries:o.retries},tokens:{baselineInput:o.baselineInput,
1344
+ actualInput:o.actualInput,eliminatedInput:o.eliminatedInput,compressedInput:o.compressedInput,baselineOutput:o.publishedBaselineOutput,actualOutput:o.actualOutput,eliminatedOutput:o.eliminatedOutput,...o.
1345
+ providerCachedInput?{providerCachedInput:o.providerCachedInput}:{}},cache:{result:r,...l!==void 0?{confidence:l}:{},...u!==void 0?{ageMs:u}:{},...o.reference?{reference:{...o.reference}}:{},...o.referenceRejected?
1346
+ {referenceRejected:o.referenceRejected}:{}},routing:{executionClass:a.executionClass,confidence:a.confidence,rounds:o.actualRetrieval,reason:a.reason},serialization:{chosen:c.chosen,candidateTokens:c.
1347
+ candidateTokens,instructionOverheadTokens:c.instructionOverheadTokens},...o.compressionReport?{compression:o.compressionReport}:{},constraints:{backend:p,schemaVersion:n.schemaVersion,...d===null?{}:{
1348
+ structurallyValid:d}},qualityStatus:th(r,d,T),qualityLedger:ul({cacheResult:r,structurallyValid:d,backend:p,hayEsquema:e.response?.schema!=null,ageMs:u,cascada:m,hechos:b}),...m?{modelCascade:m}:{},...g?
1349
+ {deferred:g}:{},...v?{cacheWrites:v}:{},quality:{...r!=="miss"?{freshnessPassed:!zn(n).requiresFreshData}:{},...r==="semantic"&&b?.semantico?{semanticScore:b.semantico.similarity}:{}},cost:y,latencyMs:{
1350
+ total:k,preprocessing:Math.max(0,k-h),provider:h},traces:s.all()}}async failOpenDirect(e,n){let r=new hn(this.now);r.record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",
1351
+ {error:n instanceof Error?n.message:String(n)});let o=new Et,i=this.costModelFor(e.model),s;try{s=Do(e);}catch{s={schemaVersion:e.response?.version??e.response?.contractId??"none"};}let a=e.response?.schema,
1352
+ c=[...e.messages];e.structuredData!==void 0&&Dn(c,{role:"system",content:JSON.stringify(e.structuredData)});let u=this.now(),l=await this.config.provider.generate({model:e.model,messages:c,...e.tools?.
1353
+ length?{tools:e.tools}:{},...a?{schema:a}:{},...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?
1354
+ {seed:e.seed}:{}}),d=this.now()-u;o.baselineLlm=1,o.actualLlm=1,o.actualInput=l.usage.inputTokens,o.actualOutput=l.usage.outputTokens,o.baselineInput=l.usage.inputTokens,o.baselineOutput=l.usage.outputTokens,
1355
+ l.usage.cachedInputTokens&&o.providerCached(l.usage.cachedInputTokens),l.unbilledRefusal===true&&(o.unbilledCall(l.usage),o.servedUnbilledRefusal=true);let p=ln(e.model);p>1&&l.unbilledRefusal!==true&&(l.usage.
1356
+ cacheWriteInputTokens??0)>0&&o.providerCacheWritePremium(l.usage.cacheWriteInputTokens??0,p,i),l.usage.complete===false&&(o.callsWithoutUsage=1);let h=l.text,m=true,g={origen:"fail_open",final:{...l.finishReason!==
1357
+ void 0?{finishReason:l.finishReason}:{},...e.response?.maxOutputTokens!=null?{topeDelLlamante:e.response.maxOutputTokens}:{}}},f=(l.toolCalls?.length??0)>0;if(f&&(m=null),a&&!f){let b=Ve(l.text),y=b.ok?
1358
+ pe(b.value,a).errors.length:1;m=y===0,g.validacion={resultado:m?"passed":"failed",errores:y,desenvuelto:false},b.ok&&(h=b.value);}let v=this.buildReport(e,s,"miss",o,i,r,En(),Pn(),void 0,void 0,m,"none",d,
1359
+ 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:"\
1360
+ 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\
1361
+ last-resort call is the wrong trade"}:void 0,void 0,e.savings?.standalone===true?{mode:"provider-default",breakpoints:0,reason:"the optimizer failed and this request went out unchanged on the direct fa\
1362
+ il-open path, so the provider chose where to write its prompt cache, as it does by default"}:void 0,g);return {requestId:v.requestId,data:h,text:l.text,...f?{toolCalls:l.toolCalls}:{},...l.finishReason!==
1363
+ void 0?{finishReason:l.finishReason}:{},...l.refusal!==void 0?{refusal:l.refusal}:{},report:v}}asCoalescedFollower(e,n,r,o,i,s={ok:false,reason:"absent"}){let a=new Et;this.negativasSinCobro.has(e)&&(a.servedUnbilledRefusal=
1364
+ true),s.ok?a.avoidCallByReference(s.credit):(a.avoidCall(n,r),a.referenceRejected=s.reason);let c=a.estimateCost(o),u=this.generateId(),l=this.diferidoSinLlamada(i),d=l?{deferred:l}:{},p=this.escriturasSinLlamada(
1365
+ i),{deferred:h,streaming:m,cacheWrites:g,...f}=e.report;return {...e,requestId:u,report:{...f,requestId:u,calls:{...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:a.baselineInput,actualInput:a.
1366
+ actualInput,eliminatedInput:a.eliminatedInput,compressedInput:a.compressedInput,baselineOutput:a.publishedBaselineOutput,actualOutput:a.actualOutput,eliminatedOutput:a.eliminatedOutput,...a.providerCachedInput?
1367
+ {providerCachedInput:a.providerCachedInput}:{}},cache:{result:"singleflight",...a.reference?{reference:{...a.reference}}:a.referenceRejected?{referenceRejected:a.referenceRejected}:{}},...d,...p?{cacheWrites:p}:
1368
+ {},qualityLedger:ll(e.report.qualityLedger),cost:c}}}creditoPorReferencia(e,n){if(typeof e=="string")return {ok:false,reason:e};let r;try{r=n.calidad();}catch{r=false;}try{return cl(e,{ahoraMs:this.now(),modeloPedido:n.
1369
+ request.model,modeloServido:n.cascada.modeloServido,huella:n.huella(),textoServidoSha256:Y(n.texto),claveLeida:n.claveLeida,calidadOk:r,precio:this.precioDocumentado(n.request.model),determinista:il(n.
1370
+ request),salidaDelModelo:Pu(n.request.model),topeDeSalida:n.request.response?.maxOutputTokens,diferible:n.toggles.deferrable===!0})}catch{return {ok:false,reason:"different-request"}}}assembleBaselinePrompt(e){
1371
+ return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,r){let o=e.map(i=>i.content);r!==void 0&&o.push(JSON.stringify(r));for(let i of n??[])o.push(Xr(i));return o.
1372
+ join(`
1362
1373
  `)}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;
1363
1374
  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(
1364
- e)}precioConocido(e,n=this.now()){return this.precioDelCliente(e)??jn(e,n)}precioDelCliente(e){let n=this.config.costModels;if(!n)return;let r=n[e];if(r)return r;let o=e.indexOf("/");if(o>=0){let i=n[e.
1365
- slice(o+1)];if(i)return i}}precioDocumentado(e){return this.precioDelCliente(e)??We(e,this.now())}costModelFor(e,n=this.now()){let r=this.precioConocido(e,n);return r||(this.config.defaultCostModel?this.
1375
+ e)}precioConocido(e,n=this.now()){return this.precioDelCliente(e)??Nn(e,n)}precioDelCliente(e){let n=this.config.costModels;if(!n)return;let r=n[e];if(r)return r;let o=e.indexOf("/");if(o>=0){let i=n[e.
1376
+ slice(o+1)];if(i)return i}}precioDocumentado(e){return this.precioDelCliente(e)??Je(e,this.now())}costModelFor(e,n=this.now()){let r=this.precioConocido(e,n);return r||(this.config.defaultCostModel?this.
1366
1377
  config.defaultCostModel:(this.avisar(`precio-ilustrativo:${e}`,`[bv-sala] no cost model configured for "${e}"; falling back to the ILLUSTRATIVE default price. Dollar figures will not match your bill. \
1367
- Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),Su))}};function Hm(t,e){if((e.toolCalls?.length??0)>0||!t.schema)return "none";let n=ze(typeof e.text=="string"?e.text:"");return n.ok&&de(
1368
- n.value,t.schema).valid?"met":"missed"}function ze(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of Wm(t))try{return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function Wm(t){
1369
- let e=[],n=/```[ \t]*[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g;for(let r of t.matchAll(n)){let o=r[1]?.trim();o&&e.push(o);}for(let r of ["{","["]){let o=t.indexOf(r);if(o===-1)continue;let i=Jm(t,o);i&&
1370
- e.push(i);}return e}function Jm(t,e){let n=t[e],r=n==="{"?"}":"]",o=0,i=false,s=false;for(let a=e;a<t.length;a+=1){let c=t[a];if(i){s?s=false:c==="\\"?s=true:c==='"'&&(i=false);continue}if(c==='"'){i=true;continue}if(c===
1371
- n)o+=1;else if(c===r&&(o-=1,o===0))return t.slice(e,a+1)}}function Km(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function Gm(t,e,n=false){if(e===false)return "rejected";if(n)return "bounded_degra\
1372
- dation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "not_verified"}}function Zm(t,e,n){switch(t){case "no-served-tier":return `asked the \
1378
+ Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),Cu))}};function Ym(t,e){if((e.toolCalls?.length??0)>0||!t.schema)return "none";let n=Ve(typeof e.text=="string"?e.text:"");return n.ok&&pe(
1379
+ n.value,t.schema).valid?"met":"missed"}function Ve(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of Qm(t))try{return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function Qm(t){
1380
+ let e=[],n=/```[ \t]*[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g;for(let r of t.matchAll(n)){let o=r[1]?.trim();o&&e.push(o);}for(let r of ["{","["]){let o=t.indexOf(r);if(o===-1)continue;let i=Xm(t,o);i&&
1381
+ e.push(i);}return e}function Xm(t,e){let n=t[e],r=n==="{"?"}":"]",o=0,i=false,s=false;for(let a=e;a<t.length;a+=1){let c=t[a];if(i){s?s=false:c==="\\"?s=true:c==='"'&&(i=false);continue}if(c==='"'){i=true;continue}if(c===
1382
+ n)o+=1;else if(c===r&&(o-=1,o===0))return t.slice(e,a+1)}}function eh(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function th(t,e,n=false){if(e===false)return "rejected";if(n)return "bounded_degra\
1383
+ dation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "not_verified"}}function nh(t,e,n){switch(t){case "no-served-tier":return `asked the \
1373
1384
  provider for the "${e}" tier, and it reported none back: the rate this request was billed at cannot be known, so nothing is credited`;case "unknown-tier":return `asked for "${e}" and the provider report\
1374
1385
  s serving "${n}", a tier this layer has no published rate for: nothing is credited`;case "standard-rate-tier":return `asked for "${e}" and the provider reports serving "${n}", which bills at the standar\
1375
1386
  d rate: this request was billed as if it had never been deferred`;case "no-tier-price":return `the provider reports serving "${n}", but there is no published price for the "${n}" tier of this model from\
1376
1387
  this provider (or it has expired): nothing is credited`;case "no-standard-price":return `the provider reports serving "${n}", but this model has no list price of its own here, so there is no standard r\
1377
1388
  ate card to price the difference against: nothing is credited`;case "incomplete-usage":return `the provider reports serving "${n}", but its usage for this call is incomplete, so the difference cannot be\
1378
- priced: nothing is credited`;case "no-difference":return `the provider reports serving "${n}", and this call's usage costs the same at both published rate cards: nothing is credited`}}function Tn(t){return Math.
1379
- round(t*1e6)/1e6}function gt(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Ym(t,e,n,r){if(e)return gt(-t.extraCostUsd);let o=i=>t.actualInput/1e3*i.inputPer1k+t.actualOutput/1e3*i.outputPer1k;
1380
- return gt(o(r)-o(n))}function Qm(t,e){if(!(e>0))return false;if(e>=1)return true;let n=Y(`${t}:cascade-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function xl(t,e){if(!e.isAgentic||e.allowSemanticCache)
1381
- return false;let n=t.original;return Fn({...t,original:{...n,savings:{...n.savings??{},semanticCache:"include-agentic"}}}).allowSemanticCache}function Cn(){return {executionClass:"NO_RETRIEVAL",confidence:1,
1382
- reason:"n/a (short-circuited)",rounds:0}}function En(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,reason:"no structured payload"}}function bs(t,e="",n=null){
1389
+ priced: nothing is credited`;case "no-difference":return `the provider reports serving "${n}", and this call's usage costs the same at both published rate cards: nothing is credited`}}function Cn(t){return Math.
1390
+ round(t*1e6)/1e6}function bt(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function rh(t,e,n,r){if(e)return bt(-t.extraCostUsd);let o=i=>t.actualInput/1e3*i.inputPer1k+t.actualOutput/1e3*i.outputPer1k;
1391
+ return bt(o(r)-o(n))}function oh(t,e){if(!(e>0))return false;if(e>=1)return true;let n=Y(`${t}:cascade-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function Sl(t,e){if(!e.isAgentic||e.allowSemanticCache)
1392
+ return false;let n=t.original;return zn({...t,original:{...n,savings:{...n.savings??{},semanticCache:"include-agentic"}}}).allowSemanticCache}function En(){return {executionClass:"NO_RETRIEVAL",confidence:1,
1393
+ reason:"n/a (short-circuited)",rounds:0}}function Pn(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,reason:"no structured payload"}}function ys(t,e="",n=null){
1383
1394
  if(t==null||typeof t!="object")return "";let r=t,o=[],i=e||"the value",s=m=>typeof r[m]=="number"?r[m]:null,a=s("maxLength"),c=s("minLength"),u=s("maxItems"),l=s("minItems"),d=s("maximum"),p=s("minimum");
1384
1395
  if(a!=null){let m=n!=null?Math.min(a,n):a;o.push(`${i}<=${m}ch`);}c!=null&&o.push(`${i}>=${c}ch`),u!=null&&o.push(`${i}<=${u} items`),l!=null&&o.push(`${i}>=${l} items`),d!=null&&o.push(`${i}<=${d}`),p!=
1385
- null&&o.push(`${i}>=${p}`),typeof r.pattern=="string"&&o.push(`${i} matches /${r.pattern}/`);let h=r.properties;if(h&&typeof h=="object")for(let[m,g]of Object.entries(h)){let f=bs(g,e?`${e}.${m}`:m,n);
1386
- f&&o.push(f);}if(r.items!==void 0){let m=bs(r.items,`${i} entries`,n);m&&o.push(m);}return o.join("; ")}function Pn(t){let e=t.response;return e?e.contractId??e.version??JSON.stringify(e.schema??{}).slice(
1387
- 0,200):""}function wl(t){return t.finishReason==="content_filter"||typeof t.refusal=="string"&&t.refusal!==""}function Xm(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.
1388
- test(e.message))}function Qr(t){return JSON.stringify({type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function Rn(t,e){
1389
- for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}function eh(t,e){if(e===false)return null;let n=typeof t=="object"&&t!==null?t:{};return e===true||t?n:null}function vs(t,e=false){
1390
- if(e){let n=0;for(;n<t.length&&t[n].role==="system";)n+=1;return n}for(let n=t.length-1;n>=0;n--)if(t[n].role==="user")return n;return vs(t,true)}function Sl(t){return t instanceof Error?t.name:typeof t}
1391
- function gs(t,e){let n=Kr(t,e);return n.cacheReadMultiplier<1?n:null}var Pl={anthropic:{peticiones:1e5,bytes:256e6},openai:{peticiones:5e4,bytes:2e8}},th=/^[A-Za-z0-9_-]{1,64}$/,Rl="/v1/chat/completions",nh=new Set(["completed","failed","expired","cancelled"]);function Dl(t){
1392
- return {submit:(e,n)=>rh(t,e,n??{}),status:(e,n)=>lh(t,e,n?.signal),results:(e,n)=>mh(t,e,n?.signal),cancel:(e,n)=>fh(t,e,n?.signal)}}function ro(t){let e=ic(t.provider);if(!e)throw new Error("[bvsala]\
1396
+ null&&o.push(`${i}>=${p}`),typeof r.pattern=="string"&&o.push(`${i} matches /${r.pattern}/`);let h=r.properties;if(h&&typeof h=="object")for(let[m,g]of Object.entries(h)){let f=ys(g,e?`${e}.${m}`:m,n);
1397
+ f&&o.push(f);}if(r.items!==void 0){let m=ys(r.items,`${i} entries`,n);m&&o.push(m);}return o.join("; ")}function Rn(t){let e=t.response;return e?e.contractId??e.version??JSON.stringify(e.schema??{}).slice(
1398
+ 0,200):""}function Tl(t){return t.finishReason==="content_filter"||typeof t.refusal=="string"&&t.refusal!==""}function ih(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.
1399
+ test(e.message))}function Xr(t){return JSON.stringify({type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function Dn(t,e){
1400
+ for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}function sh(t,e){if(e===false)return null;let n=typeof t=="object"&&t!==null?t:{};return e===true||t?n:null}function ks(t,e=false){
1401
+ if(e){let n=0;for(;n<t.length&&t[n].role==="system";)n+=1;return n}for(let n=t.length-1;n>=0;n--)if(t[n].role==="user")return n;return ks(t,true)}function Cl(t){return t instanceof Error?t.name:typeof t}
1402
+ function vs(t,e){let n=Gr(t,e);return n.cacheReadMultiplier<1?n:null}var Dl={anthropic:{peticiones:1e5,bytes:256e6},openai:{peticiones:5e4,bytes:2e8}},ah=/^[A-Za-z0-9_-]{1,64}$/,Il="/v1/chat/completions",ch=new Set(["completed","failed","expired","cancelled"]);function _l(t){
1403
+ return {submit:(e,n)=>uh(t,e,n??{}),status:(e,n)=>gh(t,e,n?.signal),results:(e,n)=>kh(t,e,n?.signal),cancel:(e,n)=>yh(t,e,n?.signal)}}function oo(t){let e=ac(t.provider);if(!e)throw new Error("[bvsala]\
1393
1404
  layer.batches needs one of the built-in providers: AnthropicProvider (Message Batches API) or OpenAICompatibleProvider (OpenAI's Batch API). This provider has no batch support in the layer.");if(e.origen===
1394
1405
  "google")throw new Error("[bvsala] Gemini's batch mode is not supported by layer.batches yet: its OpenAI-compatible endpoint creates batches but does not upload or download their files (that needs Gem\
1395
- ini's own Files API). Nothing was sent.");return e}async function rh(t,e,n){t.exigirLicencia();let r=ro(t);oh(e);let o=ih(n.maxRequestsPerBatch,r.protocolo),i=n.cacheSharedPrefix===true&&r.protocolo==="\
1396
- anthropic",s=new TextEncoder,a=e.map(({customId:m,request:g})=>{let f;try{f=r.cuerpo(sh(g,i));}catch(y){throw new TypeError(`[bvsala] batch request "${m}": ${eo(y)}`)}let v=r.protocolo==="anthropic"?{custom_id:m,
1397
- params:f}:{custom_id:m,method:"POST",url:Rl,body:f},b=JSON.stringify(v);return {customId:m,linea:v,bytes:s.encode(b).length,modelo:typeof f.model=="string"?f.model:g.model}}),c=ah(a,r.protocolo,o),u=[],
1406
+ ini's own Files API). Nothing was sent.");return e}async function uh(t,e,n){t.exigirLicencia();let r=oo(t);lh(e);let o=dh(n.maxRequestsPerBatch,r.protocolo),i=n.cacheSharedPrefix===true&&r.protocolo==="\
1407
+ anthropic",s=new TextEncoder,a=e.map(({customId:m,request:g})=>{let f;try{f=r.cuerpo(ph(g,i));}catch(y){throw new TypeError(`[bvsala] batch request "${m}": ${to(y)}`)}let v=r.protocolo==="anthropic"?{custom_id:m,
1408
+ params:f}:{custom_id:m,method:"POST",url:Il,body:f},b=JSON.stringify(v);return {customId:m,linea:v,bytes:s.encode(b).length,modelo:typeof f.model=="string"?f.model:g.model}}),c=fh(a,r.protocolo,o),u=[],
1398
1409
  l=new Map,d=new Map;c.forEach((m,g)=>m.forEach(f=>d.set(f.customId,g)));let p=e.map(({customId:m,request:g})=>{let f=g.response?.schema,v;if(f){let b=JSON.stringify(f);v=l.get(b),v===void 0&&(v=u.length,
1399
1410
  u.push(f),l.set(b,v));}return {customId:m,model:g.model,batch:d.get(m),...v!==void 0?{schema:v}:{}}}),h={kind:"bvsala.batch",version:1,provider:r.protocolo,endpoint:r.endpoint,batchIds:[],submittedAt:new Date(
1400
- t.now()).toISOString(),requests:p,schemas:u};for(let m=0;m<c.length;m++)try{let g=r.protocolo==="anthropic"?await ch(r,c[m],n.signal):await uh(r,c[m],n.signal);h.batchIds.push(g);}catch(g){let f=h.batchIds.
1401
- length,v={...h,batchIds:[...h.batchIds],requests:h.requests.filter(y=>y.batch<f)},b=h.requests.filter(y=>y.batch>=f).map(y=>y.customId);throw new Fr(f===0?`[bvsala] batch submission failed before any \
1402
- provider batch was created: ${eo(g)}.`:`[bvsala] batch submission failed after ${f} of ${c.length} provider batches were created: ${eo(g)}. The created batches run and are billed; error.job holds them\
1403
- .`,v,b,{cause:g})}return h}function oh(t){if(!Array.isArray(t)||t.length===0)throw new TypeError("[bvsala] layer.batches.submit() needs a non-empty array of { customId, request }.");let e=new Set;for(let[
1404
- n,r]of t.entries()){let o=r?.customId;if(typeof o!="string"||!th.test(o))throw new TypeError(`[bvsala] batch request #${n}: customId must be 1 to 64 letters, digits, "_" or "-" (got ${JSON.stringify(o)}\
1411
+ t.now()).toISOString(),requests:p,schemas:u};for(let m=0;m<c.length;m++)try{let g=r.protocolo==="anthropic"?await mh(r,c[m],n.signal):await hh(r,c[m],n.signal);h.batchIds.push(g);}catch(g){let f=h.batchIds.
1412
+ length,v={...h,batchIds:[...h.batchIds],requests:h.requests.filter(y=>y.batch<f)},b=h.requests.filter(y=>y.batch>=f).map(y=>y.customId);throw new zr(f===0?`[bvsala] batch submission failed before any \
1413
+ provider batch was created: ${to(g)}.`:`[bvsala] batch submission failed after ${f} of ${c.length} provider batches were created: ${to(g)}. The created batches run and are billed; error.job holds them\
1414
+ .`,v,b,{cause:g})}return h}function lh(t){if(!Array.isArray(t)||t.length===0)throw new TypeError("[bvsala] layer.batches.submit() needs a non-empty array of { customId, request }.");let e=new Set;for(let[
1415
+ n,r]of t.entries()){let o=r?.customId;if(typeof o!="string"||!ah.test(o))throw new TypeError(`[bvsala] batch request #${n}: customId must be 1 to 64 letters, digits, "_" or "-" (got ${JSON.stringify(o)}\
1405
1416
  ).`);if(e.has(o))throw new TypeError(`[bvsala] batch request "${o}": customId is repeated; it must be unique.`);e.add(o);let i=r.request;if(!i||typeof i.model!="string"||i.model===""||!Array.isArray(i.
1406
1417
  messages)||i.messages.length===0)throw new TypeError(`[bvsala] batch request "${o}": request needs a model and at least one message.`);if(i.retrieval&&i.retrieval.mode!=="off")throw new TypeError(`[bv\
1407
1418
  sala] batch request "${o}": retrieval runs in the layer's pipeline, which batches skip. Send the retrieved context in the messages instead.`);if(i.structuredData!==void 0)throw new TypeError(`[bvsala]\
1408
- batch request "${o}": structuredData is serialized by the layer's pipeline, which batches skip. Put the payload in the messages instead.`)}}function ih(t,e){let n=Pl[e].peticiones;if(t===void 0)return n;
1409
- if(!Number.isInteger(t)||t<1)throw new TypeError(`[bvsala] maxRequestsPerBatch must be a positive integer (got ${String(t)}).`);return Math.min(t,n)}function sh(t,e){let n=0;for(;n<t.messages.length&&
1419
+ batch request "${o}": structuredData is serialized by the layer's pipeline, which batches skip. Put the payload in the messages instead.`)}}function dh(t,e){let n=Dl[e].peticiones;if(t===void 0)return n;
1420
+ if(!Number.isInteger(t)||t<1)throw new TypeError(`[bvsala] maxRequestsPerBatch must be a positive integer (got ${String(t)}).`);return Math.min(t,n)}function ph(t,e){let n=0;for(;n<t.messages.length&&
1410
1421
  t.messages[n].role==="system";)n+=1;return {model:t.model,messages:t.messages,...t.tools&&t.tools.length>0?{tools:t.tools}:{},...t.response?.schema?{schema:t.response.schema}:{},...t.response?.maxOutputTokens!=
1411
- null?{maxOutputTokens:t.response.maxOutputTokens}:{},...t.temperature!=null?{temperature:t.temperature}:{},...t.seed!=null?{seed:t.seed}:{},...e&&n>0?{stablePrefixMessages:n}:{}}}function ah(t,e,n){let r=Pl[e],
1422
+ null?{maxOutputTokens:t.response.maxOutputTokens}:{},...t.temperature!=null?{temperature:t.temperature}:{},...t.seed!=null?{seed:t.seed}:{},...e&&n>0?{stablePrefixMessages:n}:{}}}function fh(t,e,n){let r=Dl[e],
1412
1423
  o=new Map;for(let a of t){let c=e==="openai"?a.modelo:"",u=o.get(c);u?u.push(a):o.set(c,[a]);}let i=e==="anthropic"?15:0,s=[];for(let a of o.values()){let c=[],u=i;for(let l of a){let d=l.bytes+1;if(i+
1413
1424
  d>r.bytes)throw new TypeError(`[bvsala] batch request "${l.customId}" is ${l.bytes} bytes, larger than a whole ${e} batch may be. Send it with generate() instead.`);c.length>0&&(c.length>=n||u+d>r.bytes)&&
1414
- (s.push(c),c=[],u=i),c.push(l),u+=d;}c.length>0&&s.push(c);}return s}async function ch(t,e,n){let r=await Dn(t,"/messages/batches",{method:"POST",json:{requests:e.map(o=>o.linea)},...n?{signal:n}:{}});return xs(
1415
- r,"Message Batch")}async function uh(t,e,n){let r=e.map(a=>JSON.stringify(a.linea)).join(`
1425
+ (s.push(c),c=[],u=i),c.push(l),u+=d;}c.length>0&&s.push(c);}return s}async function mh(t,e,n){let r=await In(t,"/messages/batches",{method:"POST",json:{requests:e.map(o=>o.linea)},...n?{signal:n}:{}});return Ss(
1426
+ r,"Message Batch")}async function hh(t,e,n){let r=e.map(a=>JSON.stringify(a.linea)).join(`
1416
1427
  `)+`
1417
- `,o=new FormData;o.append("purpose","batch"),o.append("file",new Blob([r],{type:"application/jsonl"}),"bvsala-batch.jsonl");let i=await Dn(t,"/files",{method:"POST",form:o,...n?{signal:n}:{}}),s=await Dn(
1418
- t,"/batches",{method:"POST",json:{input_file_id:xs(i,"file"),endpoint:Rl,completion_window:"24h"},...n?{signal:n}:{}});return xs(s,"batch")}async function lh(t,e,n){t.exigirLicencia();let r=ro(t);ws(e,
1419
- r);let o=await to(r,e,n);return Il(e,o)}async function to(t,e,n){let r=[];for(let[o,i]of e.batchIds.entries()){let s=await Dn(t,Ss(t,i),{method:"GET",...n?{signal:n}:{}}),a=e.requests.filter(c=>c.batch===
1420
- o).length;r.push(t.protocolo==="anthropic"?dh(i,s):ph(i,s,a));}return r}function dh(t,e){let n=oe(e),r=typeof n.processing_status=="string"?n.processing_status:"unknown",o=oe(n.request_counts);return {id:t,
1421
- estado:r,terminado:r==="ended",cancelando:r==="canceling",cuentas:{processing:st(o.processing),succeeded:st(o.succeeded),errored:st(o.errored),canceled:st(o.canceled),expired:st(o.expired)}}}function ph(t,e,n){
1422
- let r=oe(e),o=typeof r.status=="string"?r.status:"unknown",i=oe(r.request_counts),s=st(i.total)||n,a=st(i.completed),c=st(i.failed),u=Math.max(0,s-a-c),l=nh.has(o),d=o==="failed"?{processing:0,succeeded:0,
1428
+ `,o=new FormData;o.append("purpose","batch"),o.append("file",new Blob([r],{type:"application/jsonl"}),"bvsala-batch.jsonl");let i=await In(t,"/files",{method:"POST",form:o,...n?{signal:n}:{}}),s=await In(
1429
+ t,"/batches",{method:"POST",json:{input_file_id:Ss(i,"file"),endpoint:Il,completion_window:"24h"},...n?{signal:n}:{}});return Ss(s,"batch")}async function gh(t,e,n){t.exigirLicencia();let r=oo(t);Ts(e,
1430
+ r);let o=await no(r,e,n);return Al(e,o)}async function no(t,e,n){let r=[];for(let[o,i]of e.batchIds.entries()){let s=await In(t,Cs(t,i),{method:"GET",...n?{signal:n}:{}}),a=e.requests.filter(c=>c.batch===
1431
+ o).length;r.push(t.protocolo==="anthropic"?bh(i,s):vh(i,s,a));}return r}function bh(t,e){let n=oe(e),r=typeof n.processing_status=="string"?n.processing_status:"unknown",o=oe(n.request_counts);return {id:t,
1432
+ estado:r,terminado:r==="ended",cancelando:r==="canceling",cuentas:{processing:at(o.processing),succeeded:at(o.succeeded),errored:at(o.errored),canceled:at(o.canceled),expired:at(o.expired)}}}function vh(t,e,n){
1433
+ let r=oe(e),o=typeof r.status=="string"?r.status:"unknown",i=oe(r.request_counts),s=at(i.total)||n,a=at(i.completed),c=at(i.failed),u=Math.max(0,s-a-c),l=ch.has(o),d=o==="failed"?{processing:0,succeeded:0,
1423
1434
  errored:s,canceled:0,expired:0}:{processing:l?0:u,succeeded:a,errored:c+(o==="completed"?u:0),canceled:o==="cancelled"?u:0,expired:o==="expired"?u:0},p=Array.isArray(oe(r.errors).data)?oe(r.errors).data.
1424
1435
  map(h=>oe(h).message).filter(h=>typeof h=="string"):[];return {id:t,estado:o,terminado:l,cancelando:o==="cancelling",cuentas:d,...typeof r.output_file_id=="string"&&r.output_file_id!==""?{salida:r.output_file_id}:
1425
- {},...typeof r.error_file_id=="string"&&r.error_file_id!==""?{errores:r.error_file_id}:{},...o==="failed"?{fallo:p.length>0?p.join("; "):"the provider rejected the batch"}:{}}}function Il(t,e){let n={
1436
+ {},...typeof r.error_file_id=="string"&&r.error_file_id!==""?{errores:r.error_file_id}:{},...o==="failed"?{fallo:p.length>0?p.join("; "):"the provider rejected the batch"}:{}}}function Al(t,e){let n={
1426
1437
  processing:0,succeeded:0,errored:0,canceled:0,expired:0};for(let o of e)n.processing+=o.cuentas.processing,n.succeeded+=o.cuentas.succeeded,n.errored+=o.cuentas.errored,n.canceled+=o.cuentas.canceled,
1427
1438
  n.expired+=o.cuentas.expired;return {state:e.every(o=>o.terminado)?"ended":e.some(o=>o.cancelando)?"canceling":"in_progress",requestCount:t.requests.length,counts:n,batches:e.map(o=>({id:o.id,status:o.
1428
- estado}))}}async function fh(t,e,n){t.exigirLicencia();let r=ro(t);ws(e,r);let o=await to(r,e,n);for(let i of o)i.terminado||i.cancelando||await Dn(r,`${Ss(r,i.id)}/cancel`,{method:"POST",...n?{signal:n}:
1429
- {}});return Il(e,await to(r,e,n))}async function mh(t,e,n){t.exigirLicencia();let r=ro(t);ws(e,r);let o=await to(r,e,n),i=new Map;for(let u of o)if(u.terminado)if(r.protocolo==="anthropic"){let l=await ks(
1430
- r,`${Ss(r,u.id)}/results`,{method:"GET",...n?{signal:n}:{}});for await(let d of El(l))hh(i,d);}else for(let l of [u.salida,u.errores]){if(!l)continue;let d=await ks(r,`/files/${encodeURIComponent(l)}/co\
1431
- ntent`,{method:"GET",...n?{signal:n}:{}});for await(let p of El(d))gh(i,p);}let s=Math.max(t.now(),Date.parse(e.submittedAt)||0),a=[],c=0;for(let u of e.requests){let l=o[u.batch];if(!l.terminado){c+=1;
1432
- continue}let d=u.schema!==void 0?e.schemas[u.schema]:void 0;a.push(bh(t,r,u,d,i.get(u.customId),l,s));}return {ended:o.every(u=>u.terminado),items:a,summary:kh(e,a,c)}}function hh(t,e){let n=oe(e),r=n.custom_id;
1439
+ estado}))}}async function yh(t,e,n){t.exigirLicencia();let r=oo(t);Ts(e,r);let o=await no(r,e,n);for(let i of o)i.terminado||i.cancelando||await In(r,`${Cs(r,i.id)}/cancel`,{method:"POST",...n?{signal:n}:
1440
+ {}});return Al(e,await no(r,e,n))}async function kh(t,e,n){t.exigirLicencia();let r=oo(t);Ts(e,r);let o=await no(r,e,n),i=new Map;for(let u of o)if(u.terminado)if(r.protocolo==="anthropic"){let l=await ws(
1441
+ r,`${Cs(r,u.id)}/results`,{method:"GET",...n?{signal:n}:{}});for await(let d of Rl(l))xh(i,d);}else for(let l of [u.salida,u.errores]){if(!l)continue;let d=await ws(r,`/files/${encodeURIComponent(l)}/co\
1442
+ ntent`,{method:"GET",...n?{signal:n}:{}});for await(let p of Rl(d))wh(i,p);}let s=Math.max(t.now(),Date.parse(e.submittedAt)||0),a=[],c=0;for(let u of e.requests){let l=o[u.batch];if(!l.terminado){c+=1;
1443
+ continue}let d=u.schema!==void 0?e.schemas[u.schema]:void 0;a.push(Sh(t,r,u,d,i.get(u.customId),l,s));}return {ended:o.every(u=>u.terminado),items:a,summary:Eh(e,a,c)}}function xh(t,e){let n=oe(e),r=n.custom_id;
1433
1444
  if(typeof r!="string"||t.has(r))return;let o=oe(n.result);switch(o.type){case "succeeded":t.set(r,{tipo:"ok",cuerpo:o.message});return;case "errored":{let i=oe(oe(o.error).error);t.set(r,{tipo:"errored",
1434
1445
  error:{type:typeof i.type=="string"?i.type:"error",message:typeof i.message=="string"?i.message:"the provider reported an error"}});return}case "canceled":t.set(r,{tipo:"canceled"});return;case "expired":
1435
- t.set(r,{tipo:"expired"});return;default:return}}function gh(t,e){let n=oe(e),r=n.custom_id;if(typeof r!="string"||t.has(r))return;let o=n.error;if(o!=null){let u=oe(o),l=typeof u.code=="string"?u.code:
1446
+ t.set(r,{tipo:"expired"});return;default:return}}function wh(t,e){let n=oe(e),r=n.custom_id;if(typeof r!="string"||t.has(r))return;let o=n.error;if(o!=null){let u=oe(o),l=typeof u.code=="string"?u.code:
1436
1447
  "error";if(l==="batch_expired"){t.set(r,{tipo:"expired"});return}if(l==="batch_cancelled"||l==="batch_canceled"){t.set(r,{tipo:"canceled"});return}t.set(r,{tipo:"errored",error:{type:l,message:typeof u.
1437
1448
  message=="string"?u.message:"the provider reported an error"}});return}let i=oe(n.response),s=i.status_code,a=i.body;if(typeof s=="number"&&s>=200&&s<300&&a!==void 0){t.set(r,{tipo:"ok",cuerpo:a});return}
1438
1449
  let c=oe(oe(a).error);t.set(r,{tipo:"errored",error:{type:typeof c.type=="string"?c.type:`http_${typeof s=="number"?s:"error"}`,message:typeof c.message=="string"?c.message:"the provider reported an e\
1439
- rror"}});}function bh(t,e,n,r,o,i,s){let a={customId:n.customId,model:n.model},c=e.protocolo==="anthropic";if(!o)return i.estado==="failed"?{...a,outcome:"errored",reason:`the provider rejected the who\
1450
+ rror"}});}function Sh(t,e,n,r,o,i,s){let a={customId:n.customId,model:n.model},c=e.protocolo==="anthropic";if(!o)return i.estado==="failed"?{...a,outcome:"errored",reason:`the provider rejected the who\
1440
1451
  le batch before running it: ${i.fallo??"no reason given"}`,error:{type:"batch_failed",message:i.fallo??"the provider rejected the batch"}}:i.estado==="expired"?{...a,outcome:"expired",reason:"the batc\
1441
1452
  h expired before this request ran: no answer and no usage"}:i.estado==="cancelled"?{...a,outcome:"canceled",reason:"the batch was canceled before this request ran: no answer and no usage"}:{...a,outcome:"\
1442
1453
  missing",reason:"the provider returned no result line for this request; nothing is assumed about it"};switch(o.tipo){case "errored":return {...a,outcome:"errored",reason:`the provider could not run this\
1443
1454
  request (${o.error.type}: ${o.error.message})`+(c?"; Anthropic documents that errored requests are not billed":""),error:o.error};case "canceled":return {...a,outcome:"canceled",reason:c?"canceled befo\
1444
1455
  re it was sent to the model; Anthropic documents that it is not billed":"canceled before it ran: no answer and no usage"};case "expired":return {...a,outcome:"expired",reason:c?"the batch reached its 24\
1445
1456
  -hour expiration before this request was sent to the model; Anthropic documents that it is not billed":"not executed before the batch's completion window expired: no answer and no usage"};}
1446
- let u={model:n.model,messages:[],...r?{schema:r}:{}},l;try{l=e.leer(o.cuerpo,u);}catch(b){return {...a,outcome:"succeeded",reason:`the provider ran this request but its answer could not be read (${eo(b)}\
1447
- ): nothing is credited`}}let d=vh(l,r),p=c?l.servedServiceTier:"batch",h=e.origen==="anthropic"||e.origen==="openai"?e.origen:null,m=xh(t.costModels,n.model),g=sr({modelo:n.model,uso:l.usage,tierServido:p,
1457
+ let u={model:n.model,messages:[],...r?{schema:r}:{}},l;try{l=e.leer(o.cuerpo,u);}catch(b){return {...a,outcome:"succeeded",reason:`the provider ran this request but its answer could not be read (${to(b)}\
1458
+ ): nothing is credited`}}let d=Th(l,r),p=c?l.servedServiceTier:"batch",h=e.origen==="anthropic"||e.origen==="openai"?e.origen:null,m=Ph(t.costModels,n.model),g=ar({modelo:n.model,uso:l.usage,tierServido:p,
1448
1459
  origen:h,tierLeidoDe:c?"cuerpo":"lote",...m?{precioDelCliente:m}:{},ahoraMs:s}),f={...a,outcome:"succeeded",text:l.text,...d,...l.toolCalls&&l.toolCalls.length>0?{toolCalls:l.toolCalls}:{},...l.finishReason?
1449
- {finishReason:l.finishReason}:{},usage:l.usage,...p?{servedTier:p}:{}};if(!g.ok)return {...f,reason:yh(g.motivo,p)};let v={amount:g.importe,basis:g.basis,standardCost:no(g.costeEstandar),appliedCost:no(
1460
+ {finishReason:l.finishReason}:{},usage:l.usage,...p?{servedTier:p}:{}};if(!g.ok)return {...f,reason:Ch(g.motivo,p)};let v={amount:g.importe,basis:g.basis,standardCost:ro(g.costeEstandar),appliedCost:ro(
1450
1461
  g.costeAplicado),pricesCheckedOn:g.consultado,basisReason:g.motivoBasis};return {...f,tierSaving:v,reason:`billed at the "${p}" tier; this request's usage was priced at the standard and at the batch pu\
1451
- blished rate cards, component by component (${(g.factorEfectivo*100).toFixed(1)}% of standard)`}}function vh(t,e){if(!e||(t.toolCalls?.length??0)>0)return {};let n=ze(typeof t.text=="string"?t.text:"");
1452
- return n.ok?de(n.value,e).valid?{data:n.value,contract:"met"}:{contract:"missed"}:{contract:"missed"}}function yh(t,e){switch(t){case "no-served-tier":return "the provider reported no service tier for t\
1462
+ blished rate cards, component by component (${(g.factorEfectivo*100).toFixed(1)}% of standard)`}}function Th(t,e){if(!e||(t.toolCalls?.length??0)>0)return {};let n=Ve(typeof t.text=="string"?t.text:"");
1463
+ return n.ok?pe(n.value,e).valid?{data:n.value,contract:"met"}:{contract:"missed"}:{contract:"missed"}}function Ch(t,e){switch(t){case "no-served-tier":return "the provider reported no service tier for t\
1453
1464
  his result, so the rate it was billed at cannot be known: nothing is credited";case "unknown-tier":return `the provider reports the "${e}" tier for this result, a tier this layer has no published rate f\
1454
1465
  or: nothing is credited`;case "standard-rate-tier":return `the provider reports the "${e}" tier for this result, which is not billed below the standard rate: nothing is credited`;case "no-tier-price":return "\
1455
1466
  there is no published batch price for this model from this provider (or it has expired): nothing is credited";case "no-standard-price":return "this model has no list price of its own here, so there is n\
1456
1467
  o standard rate card to price the difference against: nothing is credited";case "incomplete-usage":return "the provider's usage for this result is incomplete, so the difference cannot be priced: nothing\
1457
- is credited";case "no-difference":return "this result's usage costs the same at both published rate cards: nothing is credited"}}var Cl=1e10;function kh(t,e,n){let r=0,o=0,i=0,s=0,a=0,c=0,u=0,l=0n,d=0,
1468
+ is credited";case "no-difference":return "this result's usage costs the same at both published rate cards: nothing is credited"}}var Pl=1e10;function Eh(t,e,n){let r=0,o=0,i=0,s=0,a=0,c=0,u=0,l=0n,d=0,
1458
1469
  p=0,h;for(let f of e){f.outcome==="succeeded"?r+=1:f.outcome==="errored"?o+=1:f.outcome==="canceled"?i+=1:f.outcome==="expired"?s+=1:a+=1;let v=f.tierSaving;v&&(c+=1,v.basis==="measured"&&(u+=1),l+=BigInt(
1459
- Math.round(v.amount*Cl)),d+=v.standardCost,p+=v.appliedCost,(!h||v.pricesCheckedOn<h)&&(h=v.pricesCheckedOn));}let m=c===0?"none":u===c?"measured":"estimated",g=`${r} of ${t.requests.length} requests s\
1470
+ Math.round(v.amount*Pl)),d+=v.standardCost,p+=v.appliedCost,(!h||v.pricesCheckedOn<h)&&(h=v.pricesCheckedOn));}let m=c===0?"none":u===c?"measured":"estimated",g=`${r} of ${t.requests.length} requests s\
1460
1471
  ucceeded`+(n>0?` (${n} still running)`:"")+`; ${c} were valued at the provider's standard and batch published rate cards`+(m==="none"?"":` (${m})`)+". Reported only: batch requests are not metered and\
1461
1472
  this saving is never billed. The layer's own per-request savings do not run on batches.";return {requestCount:t.requests.length,succeeded:r,errored:o,canceled:i,expired:s,missing:a,pending:n,credited:c,
1462
- tierSaving:Number(l)/Cl,standardCost:no(d),appliedCost:no(p),basis:m,...h?{pricesCheckedOn:h}:{},creditedLedger:"none",reason:g}}function ws(t,e){let n=t;if(!n||n.kind!=="bvsala.batch"||n.version!==1||
1473
+ tierSaving:Number(l)/Pl,standardCost:ro(d),appliedCost:ro(p),basis:m,...h?{pricesCheckedOn:h}:{},creditedLedger:"none",reason:g}}function Ts(t,e){let n=t;if(!n||n.kind!=="bvsala.batch"||n.version!==1||
1463
1474
  !Array.isArray(n.batchIds)||!Array.isArray(n.requests)||!Array.isArray(n.schemas)||n.requests.some(r=>!Number.isInteger(r?.batch)||r.batch<0||r.batch>=n.batchIds.length))throw new TypeError("[bvsala] \
1464
1475
  not a batch job returned by layer.batches.submit().");if(n.provider!==e.protocolo||n.endpoint!==e.endpoint)throw new TypeError(`[bvsala] this job was submitted to ${n.provider} at ${n.endpoint}; this \
1465
- layer's provider is ${e.protocolo} at ${e.endpoint}. Read it with a layer configured like the one that submitted it.`)}function Ss(t,e){return t.protocolo==="anthropic"?`/messages/batches/${encodeURIComponent(
1466
- e)}`:`/batches/${encodeURIComponent(e)}`}async function ks(t,e,n){let r=await t.solicitar(e,n);if(!r.ok){let o="";try{o=await r.text();}catch{o="";}throw new Error(`provider ${r.status}: ${o}`)}return r}
1467
- async function Dn(t,e,n){return await(await ks(t,e,n)).json()}function xs(t,e){let n=oe(t).id;if(typeof n!="string"||n==="")throw new Error(`the provider returned no ${e} id`);return n}async function*El(t){
1476
+ layer's provider is ${e.protocolo} at ${e.endpoint}. Read it with a layer configured like the one that submitted it.`)}function Cs(t,e){return t.protocolo==="anthropic"?`/messages/batches/${encodeURIComponent(
1477
+ e)}`:`/batches/${encodeURIComponent(e)}`}async function ws(t,e,n){let r=await t.solicitar(e,n);if(!r.ok){let o="";try{o=await r.text();}catch{o="";}throw new Error(`provider ${r.status}: ${o}`)}return r}
1478
+ async function In(t,e,n){return await(await ws(t,e,n)).json()}function Ss(t,e){let n=oe(t).id;if(typeof n!="string"||n==="")throw new Error(`the provider returned no ${e} id`);return n}async function*Rl(t){
1468
1479
  let e=t.body;if(!e||typeof e.getReader!="function"){for(let s of (await t.text()).split(`
1469
- `)){let a=ys(s);a!==void 0&&(yield a);}return}let n=e.getReader(),r=new TextDecoder,o="";for(;;){let{done:s,value:a}=await n.read();if(s)break;o+=r.decode(a,{stream:true});let c=o.indexOf(`
1470
- `);for(;c>=0;){let u=ys(o.slice(0,c));u!==void 0&&(yield u),o=o.slice(c+1),c=o.indexOf(`
1471
- `);}}o+=r.decode();let i=ys(o);i!==void 0&&(yield i);}function ys(t){let e=t.trim();if(e!=="")try{return JSON.parse(e)}catch{return}}function xh(t,e){if(!t)return;let n=t[e];if(n)return n;let r=e.indexOf(
1472
- "/");return r>=0?t[e.slice(r+1)]:void 0}function oe(t){return typeof t=="object"&&t!==null?t:{}}function st(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0}function eo(t){return t instanceof
1473
- Error?t.message:String(t)}function no(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}var wh=36e5,Sh=7*86400,Th=3e4,oo=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;avisadoDeCredencial=false;currentExpiresAt;currentOrg;constructor(e){this.opts=
1474
- e,this.pollIntervalMs=e.pollIntervalMs??wh,this.refreshLeadSeconds=e.refreshLeadSeconds??Sh;let n=jt(Lt(e.initialToken),e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.expires_at:
1475
- 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=
1476
- 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.
1477
- 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??
1478
- Th);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\
1479
- 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\
1480
- 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 \
1481
- will stop operating when the grace period ends.`)),!1;let i=await o.json();if(typeof i.token!="string")return !1;let s=Lt(i.token),a=jt(s,this.opts.publicKey);return !a.signatureValid||!a.payload||a.payload.
1482
- 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.
1483
- currentOrg=a.payload.org_id,this.opts.onNewToken(s),!0)}catch{return false}finally{clearTimeout(n),this.controller===e&&(this.controller=null),this.enVuelo=false;}}};var _l=2e3,Al=200,Ch=200,Eh=10,Ph=1e7,Rh=5,Dh=48*3600*1e3,Ts=/^[A-Za-z0-9._:/-]{1,128}$/,Ut=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,In=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=
1484
- 1e3;function Ih(t,e={}){if(!Ts.test(t.requestId)||!Ts.test(t.requestedModel)||!Ts.test(t.servedModel)||typeof t.at!="number"||!Number.isFinite(t.at)||t.at<1e12)return null;let n=typeof e?.ahora=="numb\
1485
- er"?e.ahora:Date.now();if(t.at>n+Dh)return null;let r=t.optimized;if(!In(r.cost)||!Ut(r.inputTokens)||!Ut(r.cachedInputTokens)||!Ut(r.outputTokens))return null;let o=t.prices;if(!In(o.inputPer1k)||!In(
1486
- o.outputPer1k)||o.cachedInputPer1k!==void 0&&!In(o.cachedInputPer1k))return null;let i={basis:"verification",requestId:t.requestId,at:Math.floor(t.at),stratum:t.stratum,outcome:t.outcome,requestedModel:t.
1480
+ `)){let a=xs(s);a!==void 0&&(yield a);}return}let n=e.getReader(),r=new TextDecoder,o="";for(;;){let{done:s,value:a}=await n.read();if(s)break;o+=r.decode(a,{stream:true});let c=o.indexOf(`
1481
+ `);for(;c>=0;){let u=xs(o.slice(0,c));u!==void 0&&(yield u),o=o.slice(c+1),c=o.indexOf(`
1482
+ `);}}o+=r.decode();let i=xs(o);i!==void 0&&(yield i);}function xs(t){let e=t.trim();if(e!=="")try{return JSON.parse(e)}catch{return}}function Ph(t,e){if(!t)return;let n=t[e];if(n)return n;let r=e.indexOf(
1483
+ "/");return r>=0?t[e.slice(r+1)]:void 0}function oe(t){return typeof t=="object"&&t!==null?t:{}}function at(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0}function to(t){return t instanceof
1484
+ Error?t.message:String(t)}function ro(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Rh(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.hash="",e.toString()}catch{return "the configured licenseServerUrl"}}var Dh=36e5,Ih=7*86400,_h=3e4,io=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;credencialAvisada=new Set;currentExpiresAt;currentOrg;constructor(e){
1485
+ this.opts=e,this.pollIntervalMs=e.pollIntervalMs??Dh,this.refreshLeadSeconds=e.refreshLeadSeconds??Ih;let n=jt(Lt(e.initialToken),e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.
1486
+ expires_at:0,this.currentOrg=n.signatureValid?n.payload?.org_id:void 0;}start(){this.timer||(this.checkNow(),this.timer=setInterval(()=>{this.checkNow();},this.pollIntervalMs),this.timer.unref?.());}stop(){
1487
+ this.parado=true,this.timer&&clearInterval(this.timer),this.timer=null,this.controller?.abort(),this.controller=null;}avisarCredencialRechazada(e){this.credencialAvisada.has(e)||(this.credencialAvisada.add(
1488
+ e),console.warn(`[bv-sala] automatic pickup of the renewed license is failing with HTTP ${e} at ${Rh(this.opts.url)}. Check 'serviceAccountKey' (rotated? from another organization?) and 'licenseServer\
1489
+ Url': until this works, the token will NOT renew itself and the SDK will stop operating when the grace period ends. (This warning is not muted by 'silenceWarnings'.)`));}nowSeconds(){return Math.floor(
1490
+ (this.opts.now?this.opts.now():Date.now())/1e3)}async checkNow(){if(this.enVuelo||this.parado||this.currentExpiresAt-this.nowSeconds()>this.refreshLeadSeconds)return false;this.enVuelo=true;let e=new AbortController;
1491
+ this.controller=e;let n=setTimeout(()=>e.abort(),this.opts.requestTimeoutMs??_h);n.unref?.();try{let o=await(this.opts.fetchImpl??globalThis.fetch.bind(globalThis))(this.opts.url,{signal:e.signal,headers:{
1492
+ authorization:`Bearer ${this.opts.serviceAccountKey}`,accept:"application/json"}});if(!o.ok)return (o.status===401||o.status===403||o.status===404)&&this.avisarCredencialRechazada(o.status),!1;this.credencialAvisada.
1493
+ clear();let i=await o.json();if(typeof i.token!="string")return !1;let s=Lt(i.token),a=jt(s,this.opts.publicKey);return !a.signatureValid||!a.payload||a.payload.expires_at<=this.currentExpiresAt||this.currentOrg&&
1494
+ a.payload.org_id!==this.currentOrg||this.opts.revocados?.snapshot().has(a.payload.jti)||this.parado?!1:(this.currentExpiresAt=a.payload.expires_at,this.currentOrg=a.payload.org_id,this.opts.onNewToken(
1495
+ s),!0)}catch{return false}finally{clearTimeout(n),this.controller===e&&(this.controller=null),this.enVuelo=false;}}};var Ol=2e3,Ml=200,Ah=200,Oh=10,Mh=1e7,Lh=5,jh=48*3600*1e3,Es=/^[A-Za-z0-9._:/-]{1,128}$/,Ut=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,_n=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=
1496
+ 1e3;function Nh(t,e={}){if(!Es.test(t.requestId)||!Es.test(t.requestedModel)||!Es.test(t.servedModel)||typeof t.at!="number"||!Number.isFinite(t.at)||t.at<1e12)return null;let n=typeof e?.ahora=="numb\
1497
+ er"?e.ahora:Date.now();if(t.at>n+jh)return null;let r=t.optimized;if(!_n(r.cost)||!Ut(r.inputTokens)||!Ut(r.cachedInputTokens)||!Ut(r.outputTokens))return null;let o=t.prices;if(!_n(o.inputPer1k)||!_n(
1498
+ o.outputPer1k)||o.cachedInputPer1k!==void 0&&!_n(o.cachedInputPer1k))return null;let i={basis:"verification",requestId:t.requestId,at:Math.floor(t.at),stratum:t.stratum,outcome:t.outcome,requestedModel:t.
1487
1499
  requestedModel,servedModel:t.servedModel,cacheResult:t.cacheResult,optimizedCost:r.cost,optimizedInputTokens:r.inputTokens,optimizedCachedInputTokens:Math.min(r.cachedInputTokens,r.inputTokens),optimizedOutputTokens:r.
1488
- outputTokens,inputPer1k:o.inputPer1k,...o.cachedInputPer1k!==void 0?{cachedInputPer1k:o.cachedInputPer1k}:{},outputPer1k:o.outputPer1k};if(t.outcome==="paired"){let s=t.naive;if(!s||!In(s.cost)||!Ut(s.
1500
+ outputTokens,inputPer1k:o.inputPer1k,...o.cachedInputPer1k!==void 0?{cachedInputPer1k:o.cachedInputPer1k}:{},outputPer1k:o.outputPer1k};if(t.outcome==="paired"){let s=t.naive;if(!s||!_n(s.cost)||!Ut(s.
1489
1501
  inputTokens)||!Ut(s.cachedInputTokens)||!Ut(s.outputTokens)||s.cachedInputTokens>s.inputTokens)return null;if(i.naiveCost=s.cost,i.naiveInputTokens=s.inputTokens,i.naiveCachedInputTokens=s.cachedInputTokens,
1490
- i.naiveOutputTokens=s.outputTokens,s.finishReason!==void 0){if(!/^[a-z_]{1,32}$/.test(s.finishReason))return null;i.naiveFinishReason=s.finishReason;}i.naiveContract=s.contract;}return i}var io=class{o;flushIntervalMs;pendientes=[];conteos=new Map;reintentos=[];inflight=null;timer;fallosSeguidos=0;ultimoFallo=Number.
1491
- 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=Ih(e,{ahora:this.ahora()});}catch{n=null;}n&&(this.pendientes.
1492
- push(n),this.pendientes.length>_l&&this.pendientes.splice(0,this.pendientes.length-_l),this.pendientes.length>=Al&&this.flushSiToca());}flushSiToca(){return this.reintentos.length>0&&this.ahora()-this.
1502
+ i.naiveOutputTokens=s.outputTokens,s.finishReason!==void 0){if(!/^[a-z_]{1,32}$/.test(s.finishReason))return null;i.naiveFinishReason=s.finishReason;}i.naiveContract=s.contract;}return i}var so=class{o;flushIntervalMs;pendientes=[];conteos=new Map;reintentos=[];inflight=null;timer;fallosSeguidos=0;ultimoFallo=Number.
1503
+ 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=Nh(e,{ahora:this.ahora()});}catch{n=null;}n&&(this.pendientes.
1504
+ push(n),this.pendientes.length>Ol&&this.pendientes.splice(0,this.pendientes.length-Ol),this.pendientes.length>=Ml&&this.flushSiToca());}flushSiToca(){return this.reintentos.length>0&&this.ahora()-this.
1493
1505
  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();},
1494
1506
  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();
1495
1507
  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;
1496
- if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,Al),r=[];for(let[o,i]of this.conteos){if(r.length>=Ch)break;let[s="",a=""]=o.split("|"),c=Math.min(i,Ph);
1497
- r.push({day:s,category:a,requests:c}),i>c?this.conteos.set(o,i-c):this.conteos.delete(o);}return {batchId:(this.o.randomId??Qt)(),samples:n,counts:r}}async hacerFlush(){let e=this.o.fetchImpl??globalThis.
1498
- fetch;if(e)for(let n=0;n<Rh&&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:`\
1499
- Bearer ${this.o.serviceAccountKey}`,"content-type":"application/json",[Nn]:`sdk/${Me}`},body:JSON.stringify(n)});return r.ok?(this.fallosSeguidos=0,!0):r.status>=500?(this.fallosSeguidos++,this.ultimoFallo=
1500
- this.ahora(),this.reencolar(n),this.avisarDeFallo(`the server responded ${r.status}`),!1):r.status===401||r.status===403?(this.o.silenceWarnings||ye(`verification-auth-${r.status}`,`[bvsala] verificat\
1508
+ if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,Ml),r=[];for(let[o,i]of this.conteos){if(r.length>=Ah)break;let[s="",a=""]=o.split("|"),c=Math.min(i,Mh);
1509
+ r.push({day:s,category:a,requests:c}),i>c?this.conteos.set(o,i-c):this.conteos.delete(o);}return {batchId:(this.o.randomId??Xt)(),samples:n,counts:r}}async hacerFlush(){let e=this.o.fetchImpl??globalThis.
1510
+ fetch;if(e)for(let n=0;n<Lh&&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:`\
1511
+ Bearer ${this.o.serviceAccountKey}`,"content-type":"application/json",[$n]:`sdk/${je}`},body:JSON.stringify(n)});return r.ok?(this.fallosSeguidos=0,!0):r.status>=500?(this.fallosSeguidos++,this.ultimoFallo=
1512
+ this.ahora(),this.reencolar(n),this.avisarDeFallo(`the server responded ${r.status}`),!1):r.status===401||r.status===403?(this.o.silenceWarnings||ke(`verification-auth-${r.status}`,`[bvsala] verificat\
1501
1513
  ion 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):
1502
1514
  (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 \
1503
1515
  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.
1504
- reintentos.unshift(e);this.reintentos.length>Eh;)this.reintentos.pop();}avisarDeFallo(e){if(this.o.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.warn(`[bvsala] verificatio\
1516
+ reintentos.unshift(e);this.reintentos.length>Oh;)this.reintentos.pop();}avisarDeFallo(e){if(this.o.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.warn(`[bvsala] verificatio\
1505
1517
  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,
1506
- conteos:this.conteos.size,reintentos:this.reintentos.length}}};var _h=72*3600,Ah,Ol=new Set(Object.values($n).flatMap(t=>t.flatMap(e=>[e,`openai/${e}`]))),Ml="[bvsala] `gpt-tokenizer` is not installed, so token counts for OpenAI models are ESTIMATED with a built-\
1518
+ conteos:this.conteos.size,reintentos:this.reintentos.length}}};var $h=72*3600,Bh,Ll=new Set(Object.values(Bn).flatMap(t=>t.flatMap(e=>[e,`openai/${e}`]))),jl="[bvsala] `gpt-tokenizer` is not installed, so token counts for OpenAI models are ESTIMATED with a built-\
1507
1519
  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 \
1508
- (`npm i gpt-tokenizer`) and the SDK loads it automatically.";function bx(t){let e=(h,m)=>{t.silenceWarnings!==true&&ye(h,m);};t.licenseGate&&(e("licenseGate-ignorado","[bvsala] Ignoring the injected `lic\
1520
+ (`npm i gpt-tokenizer`) and the SDK loads it automatically.";function Tx(t){let e=(h,m)=>{t.silenceWarnings!==true&&ke(h,m);};t.licenseGate&&(e("licenseGate-ignorado","[bvsala] Ignoring the injected `lic\
1509
1521
  enseGate`: in the published package a license is only accepted as a `licenseKey` verified against BiVelio's embedded public key. Get yours at https://savings.bivelio.com/dashboard/install"),t={...t,licenseGate:void 0});
1510
- let r={...t,tokenizer:t.tokenizer??wo},o=t.tokenizer==null&&t.exactTokenizer!==false?Ah??=To(wo).catch(()=>false):Promise.resolve(true),i,s;if(t.licenseKey&&!t.licenseGate){let h=hu;if(t.
1511
- licenseServerUrl){let m=new Nt,g=b=>Nr(b,h,{revocation:m,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??_h}),f=g(t.licenseKey);r.licenseGate={isEntitled:b=>f.isEntitled(
1512
- b),isActive:()=>f.isActive(),status:()=>f.status(),reason:()=>f.reason()};let v=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;i=new $r({url:v,publicKeyPem:h,snapshot:m,getRefreshAfter:()=>f.
1522
+ let r={...t,tokenizer:t.tokenizer??So},o=t.tokenizer==null&&t.exactTokenizer!==false?Bh??=Co(So).catch(()=>false):Promise.resolve(true),i,s;if(t.licenseKey&&!t.licenseGate){let h=bu;if(t.
1523
+ licenseServerUrl){let m=new Nt,g=b=>$r(b,h,{revocation:m,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??$h}),f=g(t.licenseKey);r.licenseGate={isEntitled:b=>f.isEntitled(
1524
+ b),isActive:()=>f.isActive(),status:()=>f.status(),reason:()=>f.reason()};let v=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;i=new Br({url:v,publicKeyPem:h,snapshot:m,getRefreshAfter:()=>f.
1513
1525
  refreshAfter?.(),...t.now?{nowSeconds:()=>Math.floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.licensePollIntervalSeconds}:
1514
- {},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{},...t.licenseRevocation??{}}),i.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(s=new oo({url:`${t.licenseServerUrl.replace(
1526
+ {},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{},...t.licenseRevocation??{}}),i.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(s=new io({url:`${t.licenseServerUrl.replace(
1515
1527
  /\/+$/,"")}/api/license/current`,serviceAccountKey:t.serviceAccountKey,publicKey:h,initialToken:t.licenseKey,revocados:m,onNewToken:b=>{f=g(b);},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?
1516
1528
  {now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),s.start());}else
1517
- r.licenseGate=xu(t.licenseKey,h,t.now);}let a=Zr(t.verification);!a.activo&&a.motivo==="invalido"&&e("verificacion-invalida",ll(t.verification));let c,u;if(a.activo){let h;if(t.serviceAccountKey&&t.metering?.
1529
+ r.licenseGate=Su(t.licenseKey,h,t.now);}let a=Yr(t.verification);!a.activo&&a.motivo==="invalido"&&e("verificacion-invalida",pl(t.verification));let c,u;if(a.activo){let h;if(t.serviceAccountKey&&t.metering?.
1518
1530
  enabled!==false)if(t.meteringUrl){let m=/^(.*)\/api\/metering\/usage\/?$/.exec(t.meteringUrl);m&&(h=`${m[1]}/api/metering/verification`);}else t.licenseServerUrl&&(h=`${t.licenseServerUrl.replace(/\/+$/,"")}\
1519
- /api/metering/verification`);if(!h&&!a.onCheck)e("verificacion-sin-destino",dl);else {h&&t.serviceAccountKey&&(c=new io({url:h,serviceAccountKey:t.serviceAccountKey,...t.meteringFetch?{fetchImpl:t.meteringFetch}:
1531
+ /api/metering/verification`);if(!h&&!a.onCheck)e("verificacion-sin-destino",fl);else {h&&t.serviceAccountKey&&(c=new so({url:h,serviceAccountKey:t.serviceAccountKey,...t.meteringFetch?{fetchImpl:t.meteringFetch}:
1520
1532
  t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.silenceWarnings!=null?{silenceWarnings:t.
1521
- silenceWarnings}:{}}),c.start());let m=c;u={encolar:g=>m?.encolar(g),...m?{contar:(g,f)=>m.contar(g,f)}:{},enReposo:()=>m?.flushSiToca()},e(`verificacion-activa:${a.tasa}`,ul(a.tasa));}}let l=new Xr(r,
1533
+ silenceWarnings}:{}}),c.start());let m=c;u={encolar:g=>m?.encolar(g),...m?{contar:(g,f)=>m.contar(g,f)}:{},enReposo:()=>m?.flushSiToca()},e(`verificacion-activa:${a.tasa}`,dl(a.tasa));}}let l=new eo(r,
1522
1534
  u?{verificacion:u}:{}),d;if(t.serviceAccountKey&&t.metering?.enabled!==false){let h=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/usage`:void 0);if(h||e("clave\
1523
1535
  -de-servicio-sin-servidor",'[bvsala] `serviceAccountKey` is set but there is no `licenseServerUrl` (or `meteringUrl`): seat metering and automatic license renewal are OFF, so nothing will reach your d\
1524
- ashboard and a renewed license will not be picked up. Add `licenseServerUrl: "https://savings.bivelio.com"` \u2014 or drop `serviceAccountKey` for a zero-network deployment.'),h){d=new xn({url:h,serviceAccountKey:t.
1536
+ ashboard and a renewed license will not be picked up. Add `licenseServerUrl: "https://savings.bivelio.com"` \u2014 or drop `serviceAccountKey` for a zero-network deployment.'),h){d=new wn({url:h,serviceAccountKey:t.
1525
1537
  serviceAccountKey,surface:"sdk",...t.metering?.orgId?{orgId:t.metering.orgId}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.metering?.maxBatch!=null?{maxBatch:t.
1526
1538
  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}:
1527
- {},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let m=t.metering?.ci??Vi();if(t.metering?.seatId)d.setSeat(t.metering.seatId,m);else {
1528
- let g=d;Ui(t.serviceAccountKey).then(f=>g.setSeat(f,m)).catch(()=>{});}d.start();}}return {batches:Dl({provider:r.provider,...r.costModels?{costModels:r.costModels}:{},exigirLicencia:()=>l.exigirLicencia(),
1529
- now:r.now??Date.now}),generate:async h=>{let m=await o,g=await l.generate(h);if(!m&&Ol.has(h.model)&&e("tokenizador-exacto-ausente",Ml),d)try{d.record(g.report);}catch{}return g},generateStream:(h,m)=>{
1530
- let g=l.generateStream(h,m??{},o);return g.result.then(async f=>{if(d)try{d.record(f.report);}catch{}!await o&&Ol.has(h.model)&&e("tokenizador-exacto-ausente",Ml);},()=>{}),g},close:()=>{l.cerrarVerificacion(),
1531
- c?.stop(),i?.stop(),s?.stop(),d?.stop();}}}function Cs(t){if(!Number.isFinite(t))throw new TypeError(`[bvsala] cannot write a non-finite number (${String(t)}) as a decimal`);if(Math.abs(t)>=1e21)return BigInt(Math.round(t)).toString();let e=t.
1532
- toFixed(10).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return e==="-0"?"0":e}function Ll(t,e){if(t==null)return "";if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`[bvsala] toCsv: \
1533
- column "${e}" holds a non-finite number`);return Cs(t)}if(typeof t=="boolean")return t?"true":"false";if(typeof t!="string")throw new TypeError(`[bvsala] toCsv: column "${e}" holds a ${typeof t}; writ\
1534
- e strings, numbers, booleans or null (flatten objects such as a series row's \`dimensions\` into their own columns first)`);let n=t;return n===""||/[",\r\n]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}function Oh(t,e){
1535
- let n;if(e?.columns)n=e.columns;else {if(t.length===0)return "";let o=new Set;for(let i of t)for(let s of Object.keys(i))o.add(s);n=[...o];}let r=[n.map(o=>Ll(o,o)).join(",")];for(let o of t)r.push(n.map(
1536
- i=>Ll(o[i],i)).join(","));return r.map(o=>`${o}\r
1537
- `).join("")}var jl={openai:{otel:"openai",nombre:"OpenAI"},anthropic:{otel:"anthropic",nombre:"Anthropic"},google:{otel:"gcp.gen_ai",nombre:"Google"},mistral:{otel:"mistral_ai",nombre:"Mistral AI"},deepseek:{otel:"\
1538
- deepseek",nombre:"DeepSeek"},groq:{otel:"groq",nombre:"Groq"},xai:{otel:"x_ai",nombre:"xAI"},cohere:{otel:"cohere",nombre:"Cohere"},perplexity:{otel:"perplexity",nombre:"Perplexity"}};function Nl(t){let e=t.
1539
- indexOf("/");return e>0?t.slice(0,e):void 0}function Es(t){let e=Nl(t)?.toLowerCase();return e!==void 0&&Object.hasOwn(jl,e)?jl[e]:void 0}function $l(t){return Es(t)?.otel??Nl(t)}function Bl(t){return Es(
1540
- t)?.nombre}function bt(t){return Es(t)?t.slice(t.indexOf("/")+1):t}var le={operacion:"gen_ai.operation.name",proveedor:"gen_ai.provider.name",modeloPedido:"gen_ai.request.model",temperatura:"gen_ai.request.temperature",semilla:"gen_ai.request.seed",maxTokens:"gen_ai.\
1539
+ {},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let m=t.metering?.ci??Hi();if(t.metering?.seatId)d.setSeat(t.metering.seatId,m);else {
1540
+ let g=d;Wi(t.serviceAccountKey).then(f=>g.setSeat(f,m)).catch(()=>{});}d.start();}}return {batches:_l({provider:r.provider,...r.costModels?{costModels:r.costModels}:{},exigirLicencia:()=>l.exigirLicencia(),
1541
+ now:r.now??Date.now}),generate:async h=>{let m=await o,g=await l.generate(h);if(!m&&Ll.has(h.model)&&e("tokenizador-exacto-ausente",jl),d)try{d.record(g.report);}catch{}return g},generateStream:(h,m)=>{
1542
+ let g=l.generateStream(h,m??{},o);return g.result.then(async f=>{if(d)try{d.record(f.report);}catch{}!await o&&Ll.has(h.model)&&e("tokenizador-exacto-ausente",jl);},()=>{}),g},close:()=>{l.cerrarVerificacion(),
1543
+ c?.stop(),i?.stop(),s?.stop(),d?.stop();}}}function Ps(t){if(!Number.isFinite(t))throw new TypeError(`[bvsala] cannot write a non-finite number (${String(t)}) as a decimal`);if(Math.abs(t)>=1e21)return BigInt(Math.round(t)).toString();let e=t.
1544
+ toFixed(10).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return e==="-0"?"0":e}function Nl(t,e){if(t==null)return "";if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`[bvsala] toCsv: \
1545
+ column "${e}" holds a non-finite number`);return Ps(t)}if(typeof t=="boolean")return t?"true":"false";if(typeof t!="string")throw new TypeError(`[bvsala] toCsv: column "${e}" holds a ${typeof t}; writ\
1546
+ e strings, numbers, booleans or null (flatten objects such as a series row's \`dimensions\` into their own columns first)`);let n=t;return n===""||/[",\r\n]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}function Fh(t,e){
1547
+ let n;if(e?.columns)n=e.columns;else {if(t.length===0)return "";let o=new Set;for(let i of t)for(let s of Object.keys(i))o.add(s);n=[...o];}let r=[n.map(o=>Nl(o,o)).join(",")];for(let o of t)r.push(n.map(
1548
+ i=>Nl(o[i],i)).join(","));return r.map(o=>`${o}\r
1549
+ `).join("")}var $l={openai:{otel:"openai",nombre:"OpenAI"},anthropic:{otel:"anthropic",nombre:"Anthropic"},google:{otel:"gcp.gen_ai",nombre:"Google"},mistral:{otel:"mistral_ai",nombre:"Mistral AI"},deepseek:{otel:"\
1550
+ deepseek",nombre:"DeepSeek"},groq:{otel:"groq",nombre:"Groq"},xai:{otel:"x_ai",nombre:"xAI"},cohere:{otel:"cohere",nombre:"Cohere"},perplexity:{otel:"perplexity",nombre:"Perplexity"}};function Bl(t){let e=t.
1551
+ indexOf("/");return e>0?t.slice(0,e):void 0}function Rs(t){let e=Bl(t)?.toLowerCase();return e!==void 0&&Object.hasOwn($l,e)?$l[e]:void 0}function Fl(t){return Rs(t)?.otel??Bl(t)}function zl(t){return Rs(
1552
+ t)?.nombre}function vt(t){return Rs(t)?t.slice(t.indexOf("/")+1):t}var le={operacion:"gen_ai.operation.name",proveedor:"gen_ai.provider.name",modeloPedido:"gen_ai.request.model",temperatura:"gen_ai.request.temperature",semilla:"gen_ai.request.seed",maxTokens:"gen_ai.\
1541
1553
  request.max_tokens",stream:"gen_ai.request.stream",conversacion:"gen_ai.conversation.id",modeloRespuesta:"gen_ai.response.model",motivosDeFin:"gen_ai.response.finish_reasons",primerTrozo:"gen_ai.respo\
1542
- nse.time_to_first_chunk",entrada:"gen_ai.usage.input_tokens",salida:"gen_ai.usage.output_tokens",lecturaDeCache:"gen_ai.usage.cache_read.input_tokens"},Fl="error.type",q="com.bivelio.",zl=`${q}stream.\
1543
- request_sent`;function qe(t){return t==="measured"||t==="reference"||t==="estimated"}function Ht(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function ql(t){return Ht(t.cost.baselineEstimate-t.cost.
1544
- actual)}function F(t,e,n){(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))&&(t[e]=n);}function Ps(t,e){let{cost:n,tokens:r,calls:o,cache:i}=t,s={bivelio_request_id:t.requestId,
1545
- bivelio_basis:n.basis,bivelio_currency:e};qe(n.basis)&&(s.bivelio_baseline_cost=n.baselineEstimate,s.bivelio_actual_cost=n.actual,s[`bivelio_saved_${n.basis}`]=ql(t),s.bivelio_net_savings_ratio=n.netSavings),
1554
+ nse.time_to_first_chunk",entrada:"gen_ai.usage.input_tokens",salida:"gen_ai.usage.output_tokens",lecturaDeCache:"gen_ai.usage.cache_read.input_tokens"},ql="error.type",q="com.bivelio.",Vl=`${q}stream.\
1555
+ request_sent`;function Ue(t){return t==="measured"||t==="reference"||t==="estimated"}function Ht(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Ul(t){return Ht(t.cost.baselineEstimate-t.cost.
1556
+ actual)}function F(t,e,n){(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))&&(t[e]=n);}function Ds(t,e){let{cost:n,tokens:r,calls:o,cache:i}=t,s={bivelio_request_id:t.requestId,
1557
+ bivelio_basis:n.basis,bivelio_currency:e};Ue(n.basis)&&(s.bivelio_baseline_cost=n.baselineEstimate,s.bivelio_actual_cost=n.actual,s[`bivelio_saved_${n.basis}`]=Ul(t),s.bivelio_net_savings_ratio=n.netSavings),
1546
1558
  s.bivelio_avoided_calls=o.avoidedLlm,s.bivelio_eliminated_input_tokens=r.eliminatedInput,s.bivelio_compressed_input_tokens=r.compressedInput,r.providerCachedInput!==void 0&&(s.bivelio_provider_cached_input_tokens=
1547
1559
  r.providerCachedInput),s.bivelio_cache_result=i.result,t.qualityStatus!==void 0&&(s.bivelio_quality_status=t.qualityStatus);for(let[a,c]of Object.entries(s))typeof c=="number"&&!Number.isFinite(c)&&delete s[a];
1548
- return s}function Rs(t){let e={};return F(e,le.modeloRespuesta,bt(t.model)),qe(t.cost.basis)&&(F(e,le.entrada,t.tokens.actualInput),F(e,le.salida,t.tokens.actualOutput),t.tokens.providerCachedInput!==
1549
- void 0&&F(e,le.lecturaDeCache,t.tokens.providerCachedInput)),e}function so(t,e){let n=e?.currency??"USD",{cost:r,tokens:o,calls:i,cache:s}=t,a={};F(a,`${q}request_id`,t.requestId),F(a,`${q}sdk.version`,
1550
- Me),F(a,`${q}model.id`,t.model),F(a,`${q}model.requested_id`,t.modelCascade?.requestedModel),F(a,`${q}cost.basis`,r.basis),F(a,`${q}cost.currency`,n),qe(r.basis)&&(F(a,`${q}cost.baseline`,r.baselineEstimate),
1551
- F(a,`${q}cost.actual`,r.actual),F(a,`${q}cost.saved.${r.basis}`,ql(t)),F(a,`${q}cost.net_savings_ratio`,r.netSavings),F(a,`${q}cost.eliminated_input_floor`,r.eliminatedInputFloorCost)),F(a,`${q}calls.\
1560
+ return s}function Is(t){let e={};return F(e,le.modeloRespuesta,vt(t.model)),Ue(t.cost.basis)&&(F(e,le.entrada,t.tokens.actualInput),F(e,le.salida,t.tokens.actualOutput),t.tokens.providerCachedInput!==
1561
+ void 0&&F(e,le.lecturaDeCache,t.tokens.providerCachedInput)),e}function ao(t,e){let n=e?.currency??"USD",{cost:r,tokens:o,calls:i,cache:s}=t,a={};F(a,`${q}request_id`,t.requestId),F(a,`${q}sdk.version`,
1562
+ je),F(a,`${q}model.id`,t.model),F(a,`${q}model.requested_id`,t.modelCascade?.requestedModel),F(a,`${q}cost.basis`,r.basis),F(a,`${q}cost.currency`,n),Ue(r.basis)&&(F(a,`${q}cost.baseline`,r.baselineEstimate),
1563
+ F(a,`${q}cost.actual`,r.actual),F(a,`${q}cost.saved.${r.basis}`,Ul(t)),F(a,`${q}cost.net_savings_ratio`,r.netSavings),F(a,`${q}cost.eliminated_input_floor`,r.eliminatedInputFloorCost)),F(a,`${q}calls.\
1552
1564
  baseline`,i.baselineLlm),F(a,`${q}calls.actual`,i.actualLlm),F(a,`${q}calls.avoided`,i.avoidedLlm),F(a,`${q}calls.retries`,i.retries),F(a,`${q}tokens.baseline_input`,o.baselineInput),F(a,`${q}tokens.a\
1553
1565
  ctual_input`,o.actualInput),F(a,`${q}tokens.eliminated_input`,o.eliminatedInput),F(a,`${q}tokens.compressed_input`,o.compressedInput),F(a,`${q}tokens.provider_cached_input`,o.providerCachedInput),F(a,
1554
1566
  `${q}tokens.baseline_output`,o.baselineOutput),F(a,`${q}tokens.actual_output`,o.actualOutput),F(a,`${q}tokens.eliminated_output`,o.eliminatedOutput),F(a,`${q}cache.result`,s.result),F(a,`${q}cache.ref\
1555
1567
  erence_request_id`,s.reference?.requestId),F(a,`${q}cache.reference_rejected`,s.referenceRejected),F(a,`${q}quality.status`,t.qualityStatus),F(a,`${q}latency.preprocessing_ms`,t.latencyMs?.preprocessing),
1556
- F(a,`${q}latency.provider_ms`,t.latencyMs?.provider);let u=e?.langfuse?.metadata||e?.datadog?.metadata?Ps(t,n):void 0;if(u&&e?.langfuse?.metadata)for(let[l,d]of Object.entries(u))a[`langfuse.observati\
1557
- on.metadata.${l}`]=typeof d=="number"?Cs(d):d;if(e?.langfuse?.cost&&n==="USD"&&qe(r.basis)&&Number.isFinite(r.actual)&&(a["langfuse.observation.cost_details"]=JSON.stringify({total:r.actual})),u&&e?.datadog?.
1558
- metadata){let l={};for(let[d,p]of Object.entries(u))l[d.replace(/^bivelio_/,"")]=p;a["_dd.ml_obs.metadata"]=JSON.stringify({bivelio:l});}return a}var Mh=2,Lh=2,jh="@bivelio/savings-layer";function Nh(t,e,n){try{if(t.isRecording?.()===!1)return;let r=so(e,n);n?.genAi&&Object.assign(r,Rs(e)),t.setAttributes(r);}catch{}}function Ds(t){return typeof t==
1559
- "function"}function $h(t){let e=t;if(e&&Ds(e.startActiveSpan))return e;if(e&&Ds(e.getTracer)){let n=e.getTracer(jh,Me);if(n&&Ds(n.startActiveSpan))return n}throw new TypeError("[bvsala] instrumentSavi\
1560
- ngsLayer: `tracer` must be an OpenTelemetry Tracer, a TracerProvider or the `trace` object of the OpenTelemetry API")}function Bh(t){let e=t?.name;return typeof e=="string"&&/^[A-Za-z_$][\w$.-]{0,127}$/.
1561
- test(e)?e:"_OTHER"}function Fh(t,e,n){let r={[le.operacion]:"chat"},o=n??$l(t.model);typeof o=="string"&&o!==""&&(r[le.proveedor]=o),r[le.modeloPedido]=bt(t.model);let i=(a,c)=>{typeof c=="number"&&Number.
1568
+ F(a,`${q}latency.provider_ms`,t.latencyMs?.provider);let u=e?.langfuse?.metadata||e?.datadog?.metadata?Ds(t,n):void 0;if(u&&e?.langfuse?.metadata)for(let[l,d]of Object.entries(u))a[`langfuse.observati\
1569
+ on.metadata.${l}`]=typeof d=="number"?Ps(d):d;if(e?.langfuse?.cost&&n==="USD"&&Ue(r.basis)&&Number.isFinite(r.actual)&&(a["langfuse.observation.cost_details"]=JSON.stringify({total:r.actual})),u&&e?.datadog?.
1570
+ metadata){let l={};for(let[d,p]of Object.entries(u))l[d.replace(/^bivelio_/,"")]=p;a["_dd.ml_obs.metadata"]=JSON.stringify({bivelio:l});}return a}var zh=2,qh=2,Vh="@bivelio/savings-layer";function Uh(t,e,n){try{if(t.isRecording?.()===!1)return;let r=ao(e,n);n?.genAi&&Object.assign(r,Is(e)),t.setAttributes(r);}catch{}}function _s(t){return typeof t==
1571
+ "function"}function Hh(t){let e=t;if(e&&_s(e.startActiveSpan))return e;if(e&&_s(e.getTracer)){let n=e.getTracer(Vh,je);if(n&&_s(n.startActiveSpan))return n}throw new TypeError("[bvsala] instrumentSavi\
1572
+ ngsLayer: `tracer` must be an OpenTelemetry Tracer, a TracerProvider or the `trace` object of the OpenTelemetry API")}function Wh(t){let e=t?.name;return typeof e=="string"&&/^[A-Za-z_$][\w$.-]{0,127}$/.
1573
+ test(e)?e:"_OTHER"}function Jh(t,e,n){let r={[le.operacion]:"chat"},o=n??Fl(t.model);typeof o=="string"&&o!==""&&(r[le.proveedor]=o),r[le.modeloPedido]=vt(t.model);let i=(a,c)=>{typeof c=="number"&&Number.
1562
1574
  isFinite(c)&&(r[a]=c);};i(le.temperatura,t.temperature),i(le.semilla,t.seed),i(le.maxTokens,t.response?.maxOutputTokens),e&&(r[le.stream]=true);let s=t.context?.sessionId;return typeof s=="string"&&s!==""&&
1563
- (r[le.conversacion]=s),r}function Vl(t,e,n){try{if(t.isRecording?.()!==!1){let r=e.report,o={...Rs(r),...so(r,n)};typeof e.finishReason=="string"&&e.finishReason!==""&&(o[le.motivosDeFin]=[e.finishReason]);
1575
+ (r[le.conversacion]=s),r}function Hl(t,e,n){try{if(t.isRecording?.()!==!1){let r=e.report,o={...Is(r),...ao(r,n)};typeof e.finishReason=="string"&&e.finishReason!==""&&(o[le.motivosDeFin]=[e.finishReason]);
1564
1576
  let i=r.streaming;i?.delivery==="live"&&typeof i.firstEventMs=="number"&&Number.isFinite(i.firstEventMs)&&(o[le.primerTrozo]=i.firstEventMs/1e3),t.setAttributes(o);}}catch{}finally{try{t.end();}catch{}}}
1565
- function Is(t,e){try{if(t.isRecording?.()!==!1){let n={[Fl]:Bh(e)};e instanceof ke&&(n[zl]=e.requestSent),t.setAttributes(n),t.setStatus?.({code:Lh});}}catch{}finally{try{t.end();}catch{}}}function zh(t,e){
1566
- let n=$h(e?.tracer);if(e.currency!==void 0&&!/^[A-Z]{3}$/.test(e.currency))throw new TypeError(`[bvsala] instrumentSavingsLayer: currency must be an ISO 4217 code such as "USD" (got "${e.currency}")`);
1567
- let r={...e.currency!==void 0?{currency:e.currency}:{},...e.langfuse?{langfuse:e.langfuse}:{},...e.datadog?{datadog:e.datadog}:{}},o=e.providerName;function i(s,a,c,u){let l,d,p=false,h;try{h=Fh(s,a,o);}catch{
1568
- h=void 0;}let m=`chat ${qh(s)}`;try{n.startActiveSpan(m,{kind:Mh,...h?{attributes:h}:{}},g=>{if(l)return l.valor;if(d)throw d.error;if(p){try{g.end();}catch{}return}let f;try{f=c();}catch(v){throw d={error:v},
1569
- Is(g,v),v}try{l={valor:u(g,f)};}catch{l={valor:f};try{g.end();}catch{}}return l.valor});}catch{}if(d)throw d.error;return l?l.valor:(p=true,c())}return {batches:t.batches,generate(s){return i(s,false,()=>t.generate(
1570
- s),(a,c)=>c.then(u=>(Vl(a,u,r),u),u=>{throw Is(a,u),u}))},generateStream(s,a){return i(s,true,()=>t.generateStream(s,a),(c,u)=>(u.result.then(l=>Vl(c,l,r),l=>Is(c,l)),u))},close(){t.close();}}}function qh(t){
1571
- try{return typeof t.model=="string"?bt(t.model):""}catch{return ""}}function Vh(t,e){let n=e?.currency??"USD",r={model:bt(t.model),metadata:Ps(t,n)};if(qe(t.cost.basis)){let{actualInput:o,actualOutput:i,providerCachedInput:s}=t.tokens,a={input:Math.max(0,o-(s??0)),output:i};
1572
- s!==void 0&&(a.cache_read_input_tokens=s),r.usageDetails=a,e?.includeCost&&n==="USD"&&Number.isFinite(t.cost.actual)&&(r.costDetails={total:t.cost.actual});}return r}var Ul=["measured","reference","estimated","unmeasured"],_s=36e5,Hl=24*_s;function ao(t,e){if(t===void 0)return "day";if(t==="hour"||t==="day")return t;throw new TypeError(`[bvsala] ${e}: granularity m\
1573
- ust be "hour" or "day"`)}function co(t,e){if(t===void 0)return "USD";if(typeof t=="string"&&/^[A-Z]{3}$/.test(t))return t;throw new TypeError(`[bvsala] ${e}: currency must be an ISO 4217 code such as "\
1574
- USD"`)}function Uh(t,e){let n=t.at,r=Number.NaN;if(n instanceof Date?r=n.getTime():typeof n=="number"?r=n:typeof n=="string"&&n.trim()!==""&&(r=Date.parse(n)),!Number.isFinite(r))throw new TypeError(`\
1575
- [bvsala] ${e}: invalid "at" for request ${String(t.report?.requestId)}: expected an ISO 8601 string, epoch milliseconds or a valid Date`);return r}function Hh(t,e){let n=e==="hour"?_s:Hl;return Math.floor(
1576
- t/n)*n}function Wh(t,e){return t+(e==="hour"?_s:Hl)}function at(t){return new Date(t).toISOString().replace(/\.\d{3}Z$/,"Z")}function ge(t,e,n,r){if(typeof t=="number"&&Number.isFinite(t))return t;throw new TypeError(
1577
- `[bvsala] ${r}: report ${n} has no finite number in ${e}`)}function uo(t,e,n,r){let o=new Map;for(let s of t){if(!s||typeof s!="object"||!s.report||typeof s.report!="object")throw new TypeError(`[bvsa\
1578
- la] ${n}: every record must be { at, report }`);let a=s.report,c=a.cost?.basis;if(c==="shadow")continue;if(!Ul.includes(c))throw new TypeError(`[bvsala] ${n}: report ${String(a.requestId)} has an unkn\
1579
- own cost basis`);let u=c,l=Hh(Uh(s,n),e),{clave:d,extra:p}=r(s,l),h=JSON.stringify([l,a.model,u,d]),m=o.get(h);m||(m={inicio:l,fin:Wh(l,e),modelo:a.model,basis:u,clave:d,extra:p,peticiones:0,llamadas:0,
1577
+ function As(t,e){try{if(t.isRecording?.()!==!1){let n={[ql]:Wh(e)};e instanceof xe&&(n[Vl]=e.requestSent),t.setAttributes(n),t.setStatus?.({code:qh});}}catch{}finally{try{t.end();}catch{}}}function Kh(t,e){
1578
+ let n=Hh(e?.tracer);if(e.currency!==void 0&&!/^[A-Z]{3}$/.test(e.currency))throw new TypeError(`[bvsala] instrumentSavingsLayer: currency must be an ISO 4217 code such as "USD" (got "${e.currency}")`);
1579
+ let r={...e.currency!==void 0?{currency:e.currency}:{},...e.langfuse?{langfuse:e.langfuse}:{},...e.datadog?{datadog:e.datadog}:{}},o=e.providerName;function i(s,a,c,u){let l,d,p=false,h;try{h=Jh(s,a,o);}catch{
1580
+ h=void 0;}let m=`chat ${Gh(s)}`;try{n.startActiveSpan(m,{kind:zh,...h?{attributes:h}:{}},g=>{if(l)return l.valor;if(d)throw d.error;if(p){try{g.end();}catch{}return}let f;try{f=c();}catch(v){throw d={error:v},
1581
+ As(g,v),v}try{l={valor:u(g,f)};}catch{l={valor:f};try{g.end();}catch{}}return l.valor});}catch{}if(d)throw d.error;return l?l.valor:(p=true,c())}return {batches:t.batches,generate(s){return i(s,false,()=>t.generate(
1582
+ s),(a,c)=>c.then(u=>(Hl(a,u,r),u),u=>{throw As(a,u),u}))},generateStream(s,a){return i(s,true,()=>t.generateStream(s,a),(c,u)=>(u.result.then(l=>Hl(c,l,r),l=>As(c,l)),u))},close(){t.close();}}}function Gh(t){
1583
+ try{return typeof t.model=="string"?vt(t.model):""}catch{return ""}}function Zh(t,e){let n=e?.currency??"USD",r={model:vt(t.model),metadata:Ds(t,n)};if(Ue(t.cost.basis)){let{actualInput:o,actualOutput:i,providerCachedInput:s}=t.tokens,a={input:Math.max(0,o-(s??0)),output:i};
1584
+ s!==void 0&&(a.cache_read_input_tokens=s),r.usageDetails=a,e?.includeCost&&n==="USD"&&Number.isFinite(t.cost.actual)&&(r.costDetails={total:t.cost.actual});}return r}var Wl=["measured","reference","estimated","unmeasured"],Os=36e5,Jl=24*Os;function co(t,e){if(t===void 0)return "day";if(t==="hour"||t==="day")return t;throw new TypeError(`[bvsala] ${e}: granularity m\
1585
+ ust be "hour" or "day"`)}function uo(t,e){if(t===void 0)return "USD";if(typeof t=="string"&&/^[A-Z]{3}$/.test(t))return t;throw new TypeError(`[bvsala] ${e}: currency must be an ISO 4217 code such as "\
1586
+ USD"`)}function Yh(t,e){let n=t.at,r=Number.NaN;if(n instanceof Date?r=n.getTime():typeof n=="number"?r=n:typeof n=="string"&&n.trim()!==""&&(r=Date.parse(n)),!Number.isFinite(r))throw new TypeError(`\
1587
+ [bvsala] ${e}: invalid "at" for request ${String(t.report?.requestId)}: expected an ISO 8601 string, epoch milliseconds or a valid Date`);return r}function Qh(t,e){let n=e==="hour"?Os:Jl;return Math.floor(
1588
+ t/n)*n}function Xh(t,e){return t+(e==="hour"?Os:Jl)}function ct(t){return new Date(t).toISOString().replace(/\.\d{3}Z$/,"Z")}function be(t,e,n,r){if(typeof t=="number"&&Number.isFinite(t))return t;throw new TypeError(
1589
+ `[bvsala] ${r}: report ${n} has no finite number in ${e}`)}function lo(t,e,n,r){let o=new Map;for(let s of t){if(!s||typeof s!="object"||!s.report||typeof s.report!="object")throw new TypeError(`[bvsa\
1590
+ la] ${n}: every record must be { at, report }`);let a=s.report,c=a.cost?.basis;if(c==="shadow")continue;if(!Wl.includes(c))throw new TypeError(`[bvsala] ${n}: report ${String(a.requestId)} has an unkn\
1591
+ own cost basis`);let u=c,l=Qh(Yh(s,n),e),{clave:d,extra:p}=r(s,l),h=JSON.stringify([l,a.model,u,d]),m=o.get(h);m||(m={inicio:l,fin:Xh(l,e),modelo:a.model,basis:u,clave:d,extra:p,peticiones:0,llamadas:0,
1580
1592
  evitadas:0,baseline:0,actual:0,ahorro:0,suelo:void 0,tokens:{baselineInput:0,actualInput:0,eliminatedInput:0,compressedInput:0,providerCachedInput:void 0,baselineOutput:0,actualOutput:0,eliminatedOutput:0}},
1581
- o.set(h,m));let g=String(a.requestId);m.peticiones+=1,m.llamadas+=ge(a.calls?.actualLlm,"calls.actualLlm",g,n),m.evitadas+=ge(a.calls?.avoidedLlm,"calls.avoidedLlm",g,n);let f=a.tokens;if(m.tokens.baselineInput+=
1582
- ge(f?.baselineInput,"tokens.baselineInput",g,n),m.tokens.actualInput+=ge(f?.actualInput,"tokens.actualInput",g,n),m.tokens.eliminatedInput+=ge(f?.eliminatedInput,"tokens.eliminatedInput",g,n),m.tokens.
1583
- compressedInput+=ge(f?.compressedInput,"tokens.compressedInput",g,n),m.tokens.baselineOutput+=ge(f?.baselineOutput,"tokens.baselineOutput",g,n),m.tokens.actualOutput+=ge(f?.actualOutput,"tokens.actual\
1584
- Output",g,n),m.tokens.eliminatedOutput+=ge(f?.eliminatedOutput,"tokens.eliminatedOutput",g,n),f.providerCachedInput!==void 0&&(m.tokens.providerCachedInput=(m.tokens.providerCachedInput??0)+ge(f.providerCachedInput,
1585
- "tokens.providerCachedInput",g,n)),qe(u)){let v=ge(a.cost.baselineEstimate,"cost.baselineEstimate",g,n),b=ge(a.cost.actual,"cost.actual",g,n);m.baseline+=v,m.actual+=b,m.ahorro+=v-b,a.cost.eliminatedInputFloorCost!==
1586
- void 0&&(m.suelo=(m.suelo??0)+ge(a.cost.eliminatedInputFloorCost,"cost.eliminatedInputFloorCost",g,n));}}let i=s=>Ul.indexOf(s);return [...o.values()].sort((s,a)=>s.inicio-a.inicio||(s.modelo<a.modelo?-1:
1587
- s.modelo>a.modelo?1:0)||i(s.basis)-i(a.basis)||(s.clave<a.clave?-1:s.clave>a.clave?1:0))}function lo(t){let e=qe(t.basis),n=Ht(t.ahorro);return {baseline:e?Ht(t.baseline):null,actual:e?Ht(t.actual):null,
1588
- measured:t.basis==="measured"?n:null,reference:t.basis==="reference"?n:null,estimated:t.basis==="estimated"?n:null,suelo:e&&t.suelo!==void 0?Ht(t.suelo):null}}function po(t){return JSON.stringify(Object.
1589
- keys(t).sort().map(e=>[e,t[e]]))}function fo(t,e,n){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new TypeError(`[bvsala] ${n}: ${e} must return an object of strings`);let r={};for(let[
1590
- o,i]of Object.entries(t)){if(typeof i!="string")throw new TypeError(`[bvsala] ${n}: ${e} value for "${o}" must be a string`);r[o]=i;}return r}var Jh=new Set(["periodStart","periodEnd","date","model","basis","currency","requests","providerCalls","avoidedCalls","baselineCost","actualCost","measuredSavings","referenceSavings","estimatedSavings",
1593
+ o.set(h,m));let g=String(a.requestId);m.peticiones+=1,m.llamadas+=be(a.calls?.actualLlm,"calls.actualLlm",g,n),m.evitadas+=be(a.calls?.avoidedLlm,"calls.avoidedLlm",g,n);let f=a.tokens;if(m.tokens.baselineInput+=
1594
+ be(f?.baselineInput,"tokens.baselineInput",g,n),m.tokens.actualInput+=be(f?.actualInput,"tokens.actualInput",g,n),m.tokens.eliminatedInput+=be(f?.eliminatedInput,"tokens.eliminatedInput",g,n),m.tokens.
1595
+ compressedInput+=be(f?.compressedInput,"tokens.compressedInput",g,n),m.tokens.baselineOutput+=be(f?.baselineOutput,"tokens.baselineOutput",g,n),m.tokens.actualOutput+=be(f?.actualOutput,"tokens.actual\
1596
+ Output",g,n),m.tokens.eliminatedOutput+=be(f?.eliminatedOutput,"tokens.eliminatedOutput",g,n),f.providerCachedInput!==void 0&&(m.tokens.providerCachedInput=(m.tokens.providerCachedInput??0)+be(f.providerCachedInput,
1597
+ "tokens.providerCachedInput",g,n)),Ue(u)){let v=be(a.cost.baselineEstimate,"cost.baselineEstimate",g,n),b=be(a.cost.actual,"cost.actual",g,n);m.baseline+=v,m.actual+=b,m.ahorro+=v-b,a.cost.eliminatedInputFloorCost!==
1598
+ void 0&&(m.suelo=(m.suelo??0)+be(a.cost.eliminatedInputFloorCost,"cost.eliminatedInputFloorCost",g,n));}}let i=s=>Wl.indexOf(s);return [...o.values()].sort((s,a)=>s.inicio-a.inicio||(s.modelo<a.modelo?-1:
1599
+ s.modelo>a.modelo?1:0)||i(s.basis)-i(a.basis)||(s.clave<a.clave?-1:s.clave>a.clave?1:0))}function po(t){let e=Ue(t.basis),n=Ht(t.ahorro);return {baseline:e?Ht(t.baseline):null,actual:e?Ht(t.actual):null,
1600
+ measured:t.basis==="measured"?n:null,reference:t.basis==="reference"?n:null,estimated:t.basis==="estimated"?n:null,suelo:e&&t.suelo!==void 0?Ht(t.suelo):null}}function fo(t){return JSON.stringify(Object.
1601
+ keys(t).sort().map(e=>[e,t[e]]))}function mo(t,e,n){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new TypeError(`[bvsala] ${n}: ${e} must return an object of strings`);let r={};for(let[
1602
+ o,i]of Object.entries(t)){if(typeof i!="string")throw new TypeError(`[bvsala] ${n}: ${e} value for "${o}" must be a string`);r[o]=i;}return r}var eg=new Set(["periodStart","periodEnd","date","model","basis","currency","requests","providerCalls","avoidedCalls","baselineCost","actualCost","measuredSavings","referenceSavings","estimatedSavings",
1591
1603
  "eliminatedInputFloorCost","baselineInputTokens","actualInputTokens","eliminatedInputTokens","compressedInputTokens","providerCachedInputTokens","baselineOutputTokens","actualOutputTokens","eliminated\
1592
- OutputTokens","dimensions"]),_n="toSavingsSeries";function Kh(t,e){let n=ao(e?.granularity,_n),r=co(e?.currency,_n),o=e?.dimensions;return uo(t,n,_n,s=>{let a=o?fo(o(s),"dimensions",_n):{};for(let c of Object.
1593
- keys(a))if(Jh.has(c))throw new TypeError(`[bvsala] ${_n}: dimension "${c}" repeats a column of the series`);return {clave:po(a),extra:a}}).map(s=>{let a=lo(s),c=at(s.inicio);return {periodStart:c,periodEnd:at(
1604
+ OutputTokens","dimensions"]),An="toSavingsSeries";function tg(t,e){let n=co(e?.granularity,An),r=uo(e?.currency,An),o=e?.dimensions;return lo(t,n,An,s=>{let a=o?mo(o(s),"dimensions",An):{};for(let c of Object.
1605
+ keys(a))if(eg.has(c))throw new TypeError(`[bvsala] ${An}: dimension "${c}" repeats a column of the series`);return {clave:fo(a),extra:a}}).map(s=>{let a=po(s),c=ct(s.inicio);return {periodStart:c,periodEnd:ct(
1594
1606
  s.fin),date:c.slice(0,10),model:s.modelo,basis:s.basis,currency:r,requests:s.peticiones,providerCalls:s.llamadas,avoidedCalls:s.evitadas,baselineCost:a.baseline,actualCost:a.actual,measuredSavings:a.measured,
1595
1607
  referenceSavings:a.reference,estimatedSavings:a.estimated,eliminatedInputFloorCost:a.suelo,baselineInputTokens:s.tokens.baselineInput,actualInputTokens:s.tokens.actualInput,eliminatedInputTokens:s.tokens.
1596
1608
  eliminatedInput,compressedInputTokens:s.tokens.compressedInput,providerCachedInputTokens:s.tokens.providerCachedInput??null,baselineOutputTokens:s.tokens.baselineOutput,actualOutputTokens:s.tokens.actualOutput,
1597
- eliminatedOutputTokens:s.tokens.eliminatedOutput,dimensions:Object.freeze({...s.extra})}})}var be="toFocusRows",Gh="BV-SALA savings ledger",Wl="bivelio/";function vt(t){return typeof t=="string"&&t.trim()!==""}function As(t,e,n,r){let o=typeof t=="function"?t(n):t??e;if(vt(o))return o;throw new TypeError(
1598
- `[bvsala] ${be}: cannot determine the FOCUS ${r} for model "${n}". FOCUS allows no placeholder there: pass it in the options.`)}function Zh(t,e,n){if(!n){let s=new Date(t);return {start:Date.UTC(s.getUTCFullYear(),
1609
+ eliminatedOutputTokens:s.tokens.eliminatedOutput,dimensions:Object.freeze({...s.extra})}})}var ve="toFocusRows",ng="BV-SALA savings ledger",Kl="bivelio/";function yt(t){return typeof t=="string"&&t.trim()!==""}function Ms(t,e,n,r){let o=typeof t=="function"?t(n):t??e;if(yt(o))return o;throw new TypeError(
1610
+ `[bvsala] ${ve}: cannot determine the FOCUS ${r} for model "${n}". FOCUS allows no placeholder there: pass it in the options.`)}function rg(t,e,n){if(!n){let s=new Date(t);return {start:Date.UTC(s.getUTCFullYear(),
1599
1611
  s.getUTCMonth(),1),end:Date.UTC(s.getUTCFullYear(),s.getUTCMonth()+1,1)}}let r=n(new Date(t)),o=r?.start instanceof Date?r.start.getTime():Number.NaN,i=r?.end instanceof Date?r.end.getTime():Number.NaN;
1600
- if(!Number.isFinite(o)||!Number.isFinite(i)||o>=i)throw new TypeError(`[bvsala] ${be}: billingPeriod must return valid Dates with start before end`);if(t<o||e>i)throw new TypeError(`[bvsala] ${be}: bi\
1601
- llingPeriod must contain the charge period it is given`);return {start:o,end:i}}function Yh(t,e){if(!e||typeof e!="object")throw new TypeError(`[bvsala] ${be}: options with a billingAccountId are requi\
1602
- red`);let n=ao(e.granularity,be),r=co(e.currency,be),{billingAccountId:o,billingAccountName:i,subAccount:s,tags:a}=e;if(typeof o!="function"&&!vt(o))throw new TypeError(`[bvsala] ${be}: billingAccount\
1603
- Id must be a non-empty string or a function`);let c=e.serviceName??Gh;if(!vt(c))throw new TypeError(`[bvsala] ${be}: serviceName must be a non-empty string`);return uo(t,n,be,l=>{let d=typeof o=="func\
1604
- tion"?o(l):o;if(!vt(d))throw new TypeError(`[bvsala] ${be}: billingAccountId returned no id for request ${String(l.report.requestId)}`);let p=typeof i=="function"?i(l):i,h=s?s(l):void 0;if(h!==void 0&&
1605
- (!vt(h?.id)||!vt(h?.name)))throw new TypeError(`[bvsala] ${be}: subAccount must return { id, name } as non-empty strings, or undefined`);let m=fo(a?a(l):void 0,"tags",be);for(let f of Object.keys(m))if(f.
1606
- startsWith(Wl))throw new TypeError(`[bvsala] ${be}: tag "${f}" uses the reserved "${Wl}" prefix`);let g={id:d,nombre:vt(p)?p:null,subId:h?h.id:null,subNombre:h?h.name:null,tags:m};return {clave:JSON.stringify(
1607
- [g.id,g.nombre,g.subId,g.subNombre,po(m)]),extra:g}}).map(l=>{let d=l.modelo,p=As(e.serviceProviderName,Bl(d),d,"ServiceProviderName"),h=As(e.invoiceIssuerName,p,d,"InvoiceIssuerName"),m=As(e.hostProviderName,
1608
- p,d,"HostProviderName"),g=Zh(l.inicio,l.fin,e.billingPeriod),f=lo(l),v=l.extra,b={"bivelio/basis":l.basis,"bivelio/model":d};for(let y of Object.keys(v.tags).sort())b[y]=v.tags[y];return {BilledCost:0,
1609
- EffectiveCost:0,ListCost:0,ContractedCost:0,BillingCurrency:r,BillingAccountId:v.id,BillingAccountName:v.nombre,BillingPeriodStart:at(g.start),BillingPeriodEnd:at(g.end),ChargePeriodStart:at(l.inicio),
1610
- ChargePeriodEnd:at(l.fin),ChargeCategory:"Adjustment",ChargeClass:null,ChargeDescription:`BV-SALA savings ledger for ${d} (basis: ${l.basis}). Not a charge: cost columns are 0 by design.`,ChargeFrequency:"\
1612
+ if(!Number.isFinite(o)||!Number.isFinite(i)||o>=i)throw new TypeError(`[bvsala] ${ve}: billingPeriod must return valid Dates with start before end`);if(t<o||e>i)throw new TypeError(`[bvsala] ${ve}: bi\
1613
+ llingPeriod must contain the charge period it is given`);return {start:o,end:i}}function og(t,e){if(!e||typeof e!="object")throw new TypeError(`[bvsala] ${ve}: options with a billingAccountId are requi\
1614
+ red`);let n=co(e.granularity,ve),r=uo(e.currency,ve),{billingAccountId:o,billingAccountName:i,subAccount:s,tags:a}=e;if(typeof o!="function"&&!yt(o))throw new TypeError(`[bvsala] ${ve}: billingAccount\
1615
+ Id must be a non-empty string or a function`);let c=e.serviceName??ng;if(!yt(c))throw new TypeError(`[bvsala] ${ve}: serviceName must be a non-empty string`);return lo(t,n,ve,l=>{let d=typeof o=="func\
1616
+ tion"?o(l):o;if(!yt(d))throw new TypeError(`[bvsala] ${ve}: billingAccountId returned no id for request ${String(l.report.requestId)}`);let p=typeof i=="function"?i(l):i,h=s?s(l):void 0;if(h!==void 0&&
1617
+ (!yt(h?.id)||!yt(h?.name)))throw new TypeError(`[bvsala] ${ve}: subAccount must return { id, name } as non-empty strings, or undefined`);let m=mo(a?a(l):void 0,"tags",ve);for(let f of Object.keys(m))if(f.
1618
+ startsWith(Kl))throw new TypeError(`[bvsala] ${ve}: tag "${f}" uses the reserved "${Kl}" prefix`);let g={id:d,nombre:yt(p)?p:null,subId:h?h.id:null,subNombre:h?h.name:null,tags:m};return {clave:JSON.stringify(
1619
+ [g.id,g.nombre,g.subId,g.subNombre,fo(m)]),extra:g}}).map(l=>{let d=l.modelo,p=Ms(e.serviceProviderName,zl(d),d,"ServiceProviderName"),h=Ms(e.invoiceIssuerName,p,d,"InvoiceIssuerName"),m=Ms(e.hostProviderName,
1620
+ p,d,"HostProviderName"),g=rg(l.inicio,l.fin,e.billingPeriod),f=po(l),v=l.extra,b={"bivelio/basis":l.basis,"bivelio/model":d};for(let y of Object.keys(v.tags).sort())b[y]=v.tags[y];return {BilledCost:0,
1621
+ EffectiveCost:0,ListCost:0,ContractedCost:0,BillingCurrency:r,BillingAccountId:v.id,BillingAccountName:v.nombre,BillingPeriodStart:ct(g.start),BillingPeriodEnd:ct(g.end),ChargePeriodStart:ct(l.inicio),
1622
+ ChargePeriodEnd:ct(l.fin),ChargeCategory:"Adjustment",ChargeClass:null,ChargeDescription:`BV-SALA savings ledger for ${d} (basis: ${l.basis}). Not a charge: cost columns are 0 by design.`,ChargeFrequency:"\
1611
1623
  Usage-Based",InvoiceIssuerName:h,ServiceProviderName:p,HostProviderName:m,ServiceName:c,ServiceCategory:"AI and Machine Learning",ServiceSubcategory:"Generative AI",PricingQuantity:null,PricingUnit:null,
1612
1624
  SubAccountId:v.subId,SubAccountName:v.subNombre,Tags:JSON.stringify(b),x_BiVelioBasis:l.basis,x_BiVelioModelId:d,x_BiVelioRequestCount:l.peticiones,x_BiVelioProviderCallCount:l.llamadas,x_BiVelioAvoidedCallCount:l.
1613
1625
  evitadas,x_BiVelioBaselineCost:f.baseline,x_BiVelioActualCost:f.actual,x_BiVelioMeasuredSavings:f.measured,x_BiVelioReferenceSavings:f.reference,x_BiVelioEstimatedSavings:f.estimated,x_BiVelioEliminatedInputFloorCost:f.
@@ -1621,4 +1633,4 @@ tokens.eliminatedOutput}})}/*! Bundled license information:
1621
1633
  @noble/curves/abstract/edwards.js:
1622
1634
  @noble/curves/ed25519.js:
1623
1635
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
1624
- */export{gc as AnthropicProvider,Me as BV_SALA_VERSION,Fr as BatchSubmitError,Yt as CATALOGO,Ko as COMPACTION_TRANSFORMS,cp as COMPACT_ROWS_INSTRUCTION,we as CalibrationStateError,Su as DEFAULT_COST_MODEL,_h as DEFAULT_MAX_STALENESS_SECONDS,bp as DEFAULT_MIN_SAVED_CHARS,hu as EMBEDDED_PUBLIC_KEY,So as ExactTokenizer,Kn as ExecutionRouter,er as FormatSelector,ko as HeuristicEstimator,da as InMemoryCacheBreakpointStore,zn as InMemoryExactCache,la as InMemorySemanticCache,Fo as InMemoryToolSetFreezer,Qe as LicenseError,gg as MODELOS_POR_CODIFICACION,$n as MODELS_BY_ENCODING,Zo as MockProvider,cc as OpenAICompatibleProvider,bo as PRECIOS_AL_DIA,rg as QUALITY_STATUSES,Ws as REFERENCE_MAX_AGE_MS,Ks as REFERENCE_MESSAGE_ALLOWANCE,Js as REFERENCE_OUTPUT_SHARE,No as ResolverRegistry,$r as RevocationPoller,Nt as RevocationSnapshot,Et as SavingsLedger,tr as SchemaRegistry,qn as Singleflight,ke as StreamAbortedError,xo as TokenizerRegistry,Zn as ToolSelector,mn as TraceCollector,ca as UMBRAL_LOCAL,xn as UsageEmitter,Yd as adaptiveK,Bd as arithmeticResolver,Do as buildExactKey,Qs as buildInflightKey,Fg as calibrateSemanticFloor,Ro as canonicalize,Ea as compactRowsSerializer,La as compactToolOutput,_a as compresionFiel,zf as computeNextDelay,_d as cosine,up as createCompactRowsSerializer,pa as createDefaultResolvers,ig as createHandoff,rb as createMockProvider,bx as createSavingsLayer,Ra as csvSerializer,wa as decodeCompactRows,Zd as dedupe,wo as defaultTokenizerRegistry,Ui as deriveSeatId,qi as deriveStatus,Vi as detectCi,aa as embebedorLocal,h0 as emptyState,ip as encodeCompactRows,qd as evalArithmetic,Fn as evaluatePolicy,ka as executeRetrievalPlan,xu as gateFromKey,Ct as heuristicEstimator,zh as instrumentSavingsLayer,jf as isKeyset,Ze as isStrictCompatible,xa as jsonCompactSerializer,Ld as keyTokensMatch,Fi as licenseKeyShape,Nr as liveGateFromKey,g0 as mergeDelta,Po as modelFamilyOf,jo as multisetEqual,sn as negationCount,K0 as noopCompressor,Lt as normalizeLicenseKey,Bn as normalizeText,rn as numericTokens,jn as precioDeLista,b0 as projectContext,F0 as providerNativeBackend,ii as quitarPrefijoDeProveedor,Qt as randomId,Nh as recordSavingsOnSpan,To as registerExactTokenizer,bg as registrarTokenizadorExacto,Xd as renderState,Ia as resolveConstraintBackend,Tu as resolveDependencies,jv as resolveLicense,Lo as sameAnswer,so as savingsSpanAttributes,Y as sha256,Jo as shouldCompress,he as stableStringify,Oh as toCsv,Yh as toFocusRows,Vh as toLangfuseGeneration,Kh as toSavingsSeries,Xn as uniformColumns,de as validateAgainstSchema,Id as vectorLocal,zi as verifyCompactSignature,jt as verifyLicenseToken,ku as verifyRevocationList,J0 as withProtectedSpans,on as words};
1636
+ */export{vc as AnthropicProvider,je as BV_SALA_VERSION,zr as BatchSubmitError,Qt as CATALOGO,Go as COMPACTION_TRANSFORMS,fp as COMPACT_ROWS_INSTRUCTION,Te as CalibrationStateError,Cu as DEFAULT_COST_MODEL,$h as DEFAULT_MAX_STALENESS_SECONDS,wp as DEFAULT_MIN_SAVED_CHARS,bu as EMBEDDED_PUBLIC_KEY,To as ExactTokenizer,Gn as ExecutionRouter,tr as FormatSelector,xo as HeuristicEstimator,fa as InMemoryCacheBreakpointStore,qn as InMemoryExactCache,pa as InMemorySemanticCache,zo as InMemoryToolSetFreezer,Xe as LicenseError,Sg as MODELOS_POR_CODIFICACION,Bn as MODELS_BY_ENCODING,Yo as MockProvider,lc as OpenAICompatibleProvider,vo as PRECIOS_AL_DIA,lg as QUALITY_STATUSES,Ks as REFERENCE_MAX_AGE_MS,Zs as REFERENCE_MESSAGE_ALLOWANCE,Gs as REFERENCE_OUTPUT_SHARE,$o as ResolverRegistry,Br as RevocationPoller,Nt as RevocationSnapshot,Et as SavingsLedger,nr as SchemaRegistry,Vn as Singleflight,xe as StreamAbortedError,wo as TokenizerRegistry,Yn as ToolSelector,hn as TraceCollector,la as UMBRAL_LOCAL,wn as UsageEmitter,np as adaptiveK,Ud as arithmeticResolver,Io as buildExactKey,ea as buildInflightKey,Jg as calibrateSemanticFloor,Do as canonicalize,Ra as compactRowsSerializer,Na as compactToolOutput,Oa as compresionFiel,Jf as computeNextDelay,jd as cosine,mp as createCompactRowsSerializer,ma as createDefaultResolvers,pg as createHandoff,lb as createMockProvider,Tx as createSavingsLayer,Ia as csvSerializer,Ta as decodeCompactRows,tp as dedupe,So as defaultTokenizerRegistry,Wi as deriveSeatId,Ui as deriveStatus,Hi as detectCi,ua as embebedorLocal,w0 as emptyState,lp as encodeCompactRows,Jd as evalArithmetic,zn as evaluatePolicy,wa as executeRetrievalPlan,Su as gateFromKey,Ct as heuristicEstimator,Kh as instrumentSavingsLayer,qf as isKeyset,Ye as isStrictCompatible,Sa as jsonCompactSerializer,Fd as keyTokensMatch,qi as licenseKeyShape,$r as liveGateFromKey,S0 as mergeDelta,Ro as modelFamilyOf,No as multisetEqual,an as negationCount,tb as noopCompressor,Lt as normalizeLicenseKey,Fn as normalizeText,on as numericTokens,Nn as precioDeLista,T0 as projectContext,J0 as providerNativeBackend,si as quitarPrefijoDeProveedor,Xt as randomId,Uh as recordSavingsOnSpan,Co as registerExactTokenizer,Tg as registrarTokenizadorExacto,op as renderState,Aa as resolveConstraintBackend,Eu as resolveDependencies,Vv as resolveLicense,jo as sameAnswer,ao as savingsSpanAttributes,Y as sha256,Ko as shouldCompress,ge as stableStringify,Fh as toCsv,og as toFocusRows,Zh as toLangfuseGeneration,tg as toSavingsSeries,er as uniformColumns,pe as validateAgainstSchema,Ld as vectorLocal,Vi as verifyCompactSignature,jt as verifyLicenseToken,wu as verifyRevocationList,eb as withProtectedSpans,sn as words};