@bivelio/savings-layer 0.4.34 → 0.4.35

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 _n="2026-09-29";var Rt={"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,cachedInputPer1k:25e-6},
1
+ var In="2026-09-29";var Rt={"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,cachedInputPer1k:25e-6},
2
2
  "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},"gpt-4":{inputPer1k:.03,
3
3
  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,cachedInputPer1k:125e-6},
4
4
  "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,outputPer1k:.01,cachedInputPer1k:125e-6},
@@ -20,24 +20,24 @@ cachedInputPer1k:.0015},"gemini-3.8-flash":{inputPer1k:75e-5,outputPer1k:.00375,
20
20
  h":{inputPer1k:75e-5,outputPer1k:.00375,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,
21
21
  cachedInputPer1k:5e-5},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5},"gemini-3.1-pro-p\
22
22
  review":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}},
23
- Yp={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},Zp={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{
23
+ Xp={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},Qp={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{
24
24
  inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.7-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.6-flash":[{vigenteDesde:"\
25
- 2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},Xp=Object.fromEntries(Object.keys(Rt).map(t=>[t,[{...Yp[t],precio:Rt[t]},...Zp[t]??[]]]));var Qp=864e13;function Qa(t){let e=t instanceof Date?t.getTime():t,n=typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=Qp?e:Date.now();return new Date(n).toISOString().slice(0,10)}function ec(t,e){
26
- for(let n of Xp[t]??[])if(!(n.vigenteDesde!==void 0&&e<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&e>=n.vigenteHasta))return n.precio}function ai(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 l=i.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return t[a]}}function ci(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var ef=["o3-dee\
25
+ 2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},ef=Object.fromEntries(Object.keys(Rt).map(t=>[t,[{...Xp[t],precio:Rt[t]},...Qp[t]??[]]]));var tf=864e13;function Qa(t){let e=t instanceof Date?t.getTime():t,n=typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=tf?e:Date.now();return new Date(n).toISOString().slice(0,10)}function ec(t,e){
26
+ for(let n of ef[t]??[])if(!(n.vigenteDesde!==void 0&&e<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&e>=n.vigenteHasta))return n.precio}function ai(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 l=i.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return t[a]}}function ci(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var nf=["o3-dee\
28
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"],si={...Rt,...Object.
29
- fromEntries(ef.map(t=>[t,null]))},tf=ci(si);function Xt(t,e){let n=Qt(t);return n===void 0?void 0:ec(n,Qa(e))}var nf=Object.fromEntries(Object.keys(si).map(t=>[t,si[t]===null?null:t]));function Qt(t){
30
- return ai(nf,tf,t)??void 0}var rf=/^\d{4}-?\d{2}-?\d{2}$/;function st(t,e){let n=Qt(t);if(n===void 0)return;let r=t.lastIndexOf("/"),o=r>=0?t.slice(r+1):t;if(!(n!==t&&n!==o&&!rf.test(o.slice(n.length+
31
- 1))))return ec(n,Qa(e))}var Ve="0.4.34",wr="x-bvsala-version";var of=0;function Pt(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++of,o=Date.now?Date.now():0;for(let i=0;i<
29
+ fromEntries(nf.map(t=>[t,null]))},rf=ci(si);function Xt(t,e){let n=Qt(t);return n===void 0?void 0:ec(n,Qa(e))}var of=Object.fromEntries(Object.keys(si).map(t=>[t,si[t]===null?null:t]));function Qt(t){
30
+ return ai(of,rf,t)??void 0}var sf=/^\d{4}-?\d{2}-?\d{2}$/;function st(t,e){let n=Qt(t);if(n===void 0)return;let r=t.lastIndexOf("/"),o=r>=0?t.slice(r+1):t;if(!(n!==t&&n!==o&&!sf.test(o.slice(n.length+
31
+ 1))))return ec(n,Qa(e))}var Ve="0.4.35",wr="x-bvsala-version";var af=0;function Pt(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++af,o=Date.now?Date.now():0;for(let i=0;i<
32
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]}\
33
- -${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var Yy=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function Xy(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 li=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 ek=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function nk(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 li=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.
34
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,
35
35
  Math.ceil(e.length/4))}},en=new li;var ui=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=en){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){
36
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.
37
37
  get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},di=new ui;var pi=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}},Sr={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini",
38
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 fi(t,e={}){let n=e.codificaciones??
39
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 pi(o,i)),r=true;for(let s of Sr[o]??
40
- [])t.mapModel(s,o),t.mapModel(`openai/${s}`,o);}}return r}var lk=Sr,uk=fi;var at=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;nativeCacheWriteInput=0;nativeCacheWrite1hInput=0;nativeCacheMarkedByLayer=null;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){
40
+ [])t.mapModel(s,o),t.mapModel(`openai/${s}`,o);}}return r}var fk=Sr,mk=fi;var at=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;nativeCacheWriteInput=0;nativeCacheWrite1hInput=0;nativeCacheMarkedByLayer=null;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){
41
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.
42
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.
43
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);}nativeCacheWrite(e,n){
@@ -51,24 +51,24 @@ removedInputLocal===0?"measured":"estimated";}else this.actualInput>0?(this.base
51
51
  repairOutput-this.discoveryOutput):this.baselineOutput,i=e.cachedInputPer1k??e.inputPer1k,s=Math.max(0,this.actualInput-this.unbilledInput),a=Math.max(0,this.actualOutput-this.unbilledOutput),c=Math.min(
52
52
  Math.max(0,this.providerCachedInput-this.unbilledCachedInput),s),l=y=>Math.max(0,y-c)/1e3*e.inputPer1k+c/1e3*i,u=n?null:this.reference,d=n?this.providerCacheWritePremiumUsd:0,p=this.servedUnbilledRefusal?
53
53
  0:u?u.tierFactor*(this.baselineInput/1e3*u.cachedInputPer1k+this.baselineOutput/1e3*u.outputPer1k):l(this.baselineInput)+o/1e3*e.outputPer1k+d;u&&(r=p>0?"reference":"estimated"),this.servedUnbilledRefusal&&
54
- (u?r="estimated":n&&r==="estimated"&&(r="measured"));let h=l(s)+a/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd+d,f=p===0?0:1-h/p,m=mi(p),g=mi(h),b=sf(f);return {baselineEstimate:m,actual:g,
55
- netSavings:b,netSavingsRatio:b,netSavingsUsd:mi(m-g),basis:r}}};function mi(t){return Math.round(t*1e10)/1e10}function sf(t){return Math.round(t*1e6)/1e6}var af=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
54
+ (u?r="estimated":n&&r==="estimated"&&(r="measured"));let h=l(s)+a/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd+d,f=p===0?0:1-h/p,m=mi(p),g=mi(h),b=cf(f);return {baselineEstimate:m,actual:g,
55
+ netSavings:b,netSavingsRatio:b,netSavingsUsd:mi(m-g),basis:r}}};function mi(t){return Math.round(t*1e10)/1e10}function cf(t){return Math.round(t*1e6)/1e6}var lf=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
56
56
  4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
57
57
  1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,
58
- 1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),cf=new TextEncoder;function $e(t,e){return t>>>e|t<<32-e}function tc(t){let e=cf.encode(t),n=e.length*
58
+ 1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),uf=new TextEncoder;function $e(t,e){return t>>>e|t<<32-e}function tc(t){let e=uf.encode(t),n=e.length*
59
59
  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(
60
60
  [1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let l=0;l<o.length;l+=64){for(let y=0;y<16;y++)a[y]=i.getUint32(l+y*4);for(let y=16;y<
61
61
  64;y++){let v=a[y-15],x=a[y-2],E=$e(v,7)^$e(v,18)^v>>>3,S=$e(x,17)^$e(x,19)^x>>>10;a[y]=a[y-16]+E+a[y-7]+S|0;}let u=s[0],d=s[1],p=s[2],h=s[3],f=s[4],m=s[5],g=s[6],b=s[7];for(let y=0;y<64;y++){let v=$e(
62
- f,6)^$e(f,11)^$e(f,25),x=f&m^~f&g,E=b+v+x+af[y]+a[y]|0,S=$e(u,2)^$e(u,13)^$e(u,22),C=u&d^u&p^d&p,A=S+C|0;b=g,g=m,m=f,f=h+E|0,h=p,p=d,d=u,u=E+A|0;}s[0]=s[0]+u|0,s[1]=s[1]+d|0,s[2]=s[2]+p|0,s[3]=s[3]+h|0,
63
- s[4]=s[4]+f|0,s[5]=s[5]+m|0,s[6]=s[6]+g|0,s[7]=s[7]+b|0;}let c="";for(let l=0;l<8;l++)c+=(s[l]>>>0).toString(16).padStart(8,"0");return c}var lf=/\s+/g,uf=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],df=/[¿?¡!;.,:'"·•]/g,pf=/([a-z])\p{M}+/gu,ff=/(^|\s)\p{M}+/gu,
64
- hi=/\p{L}/u;function ke(t){return t>="0"&&t<="9"}function tn(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,r]of uf)e=e.replace(n,r);return e=e.normalize("NFD").replace(pf,"$1").replace(ff,"$1").
65
- normalize("NFC"),e=e.replace(df,(n,r,o)=>{let i=o[r-1]??"",s=o[r+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return ke(i)&&ke(s)?n:"";case "!":return ke(i)?n:"";case ".":case ",":return ke(i)&&
66
- ke(s)||ke(s)&&!ke(i)&&!hi.test(i)?n:"";case ":":return ke(i)&&ke(s)?n:"";case "'":case '"':return hi.test(i)&&hi.test(s)||ke(i)||ke(s)?n:"";default:return ke(i)||ke(s)?n:""}}),e.replace(lf," ").trim()}function X(t){
62
+ f,6)^$e(f,11)^$e(f,25),x=f&m^~f&g,E=b+v+x+lf[y]+a[y]|0,S=$e(u,2)^$e(u,13)^$e(u,22),C=u&d^u&p^d&p,A=S+C|0;b=g,g=m,m=f,f=h+E|0,h=p,p=d,d=u,u=E+A|0;}s[0]=s[0]+u|0,s[1]=s[1]+d|0,s[2]=s[2]+p|0,s[3]=s[3]+h|0,
63
+ s[4]=s[4]+f|0,s[5]=s[5]+m|0,s[6]=s[6]+g|0,s[7]=s[7]+b|0;}let c="";for(let l=0;l<8;l++)c+=(s[l]>>>0).toString(16).padStart(8,"0");return c}var df=/\s+/g,pf=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],ff=/[¿?¡!;.,:'"·•]/g,mf=/([a-z])\p{M}+/gu,hf=/(^|\s)\p{M}+/gu,
64
+ hi=/\p{L}/u;function ke(t){return t>="0"&&t<="9"}function tn(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,r]of pf)e=e.replace(n,r);return e=e.normalize("NFD").replace(mf,"$1").replace(hf,"$1").
65
+ normalize("NFC"),e=e.replace(ff,(n,r,o)=>{let i=o[r-1]??"",s=o[r+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return ke(i)&&ke(s)?n:"";case "!":return ke(i)?n:"";case ".":case ",":return ke(i)&&
66
+ ke(s)||ke(s)&&!ke(i)&&!hi.test(i)?n:"";case ":":return ke(i)&&ke(s)?n:"";case "'":case '"':return hi.test(i)&&hi.test(s)||ke(i)||ke(s)?n:"";default:return ke(i)||ke(s)?n:""}}),e.replace(df," ").trim()}function X(t){
67
67
  return tc(t)}function de(t){return JSON.stringify(gi(t))}function gi(t){if(Array.isArray(t))return t.map(gi);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=gi(t[n]);return e}
68
- return t}function Dn(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function mf(t){let e=new Map,n=o=>{if(typeof o!="string"||o==="")return {sin:o??null};let i=e.
68
+ return t}function Dn(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function gf(t){let e=new Map,n=o=>{if(typeof o!="string"||o==="")return {sin:o??null};let i=e.
69
69
  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,
70
70
  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.
71
- keys(s).length>0?s:null});if(!r.every(o=>o===null))return X(de(r))}function nn(t){let e=t.context??{},n=mf(t.messages),r=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(`
71
+ keys(s).length>0?s:null});if(!r.every(o=>o===null))return X(de(r))}function nn(t){let e=t.context??{},n=gf(t.messages),r=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(`
72
72
  `),o=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${tn(s.content)}`).join(`
73
73
  `),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:Dn(t.model),messages:t.messages,normalizedText:o,
74
74
  systemPromptHash:X(r),toolsetHash:X(de(i)),...n!==void 0?{toolTurnsHash:n}:{},structuredDataHash:t.structuredData!==void 0?X(de(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.
@@ -79,7 +79,7 @@ t.model,r=de({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal
79
79
  schema:t.schemaVersion,tools:t.toolsetHash,...rc(t),data:t.structuredDataHash,locale:t.locale,temperature:t.temperature,seed:t.seed,...oc(t),knowledgeEpoch:t.knowledgeEpoch,freshness:t.freshnessBucket,
80
80
  safety:t.safetyPolicyVersion});return `bvsala:exact:${nc}:${X(r)}`}function An(t,e={}){let n=de({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,model:e.servedModel??
81
81
  t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,...rc(t),data:t.structuredDataHash,temperature:t.temperature,seed:t.seed,...oc(t),deferrable:e.deferrable===
82
- true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:inflight:${nc}:${X(n)}`}var K="\\p{L}*",hf=[`suicid${K}`,`self[- ]?harm${K}`,`self[- ]?injur${K}`,`self[- ]?mutilat${K}`,"(?:kill|killing|hang|hanging|drown|drowning|cut|cutting|hurt|hurting|harm|harming|shoot|poison|stab|st\
82
+ true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:inflight:${nc}:${X(n)}`}var K="\\p{L}*",bf=[`suicid${K}`,`self[- ]?harm${K}`,`self[- ]?injur${K}`,`self[- ]?mutilat${K}`,"(?:kill|killing|hang|hanging|drown|drowning|cut|cutting|hurt|hurting|harm|harming|shoot|poison|stab|st\
83
83
  arve|suffocate|strangle|electrocute|overdose) myself","end (?:my|my own) life","(?:want to|going to|gonna|just|i'll|i will) end it all","take my (?:own )?life","i (?:really |just )?(?:want|wanna) to d\
84
84
  ie","i(?:'m| am) (?:going|planning|trying|ready) to die","wish i (?:was|were) dead","better off dead","(?:don't|do not) want to (?:live|be alive|wake up) any ?more","(?:don't|do not) want to be alive",
85
85
  "no reason to (?:live|keep living)","take to die","(?:cut|sever|slit|pierce|open) (?:my|my own) (?:\\p{L}+ )?(?:artery|arteries|wrists?|veins?|throat)","(?:carve|cut) (?:\\p{L}+ ){0,3}into my (?:arm|ar\
@@ -93,31 +93,31 @@ rcar|enforcar-me|me afogar|me machucar)","tirar a (?:minha )?(?:pr\xF3pria )?vid
93
93
  en|ophangen|verdrinken|snijden|iets aandoen|van kant maken)","ik wil dood","overdosis",`samob\xF3j${K}`,`samookalecz${K}`,"(?:zabi\u0107 si\u0119|powiesi\u0107 si\u0119|utopi\u0107 si\u0119|poci\u0105\u0107 si\u0119|skrzywdzi\u0107 si\u0119|odebra\u0107 sobie \
94
94
  \u017Cycie)","chc\u0119 umrze\u0107","nie chc\u0119 ju\u017C \u017Cy\u0107",`przedawkowa${K}`,`intihar${K}`,"kendime zarar",`kendimi \xF6ld\xFCr${K}`,"\xF6lmek istiyorum","art\u0131k ya\u015Famak istemiyorum",
95
95
  "a\u015F\u0131r\u0131 doz","bunuh diri",`menyakiti diri${K}`,"(?:ingin|mau) mati","tidak ingin hidup lagi","t\u1EF1 t\u1EED|t\u1EF1 s\xE1t|t\u1EF1 l\xE0m h\u1EA1i|t\u1EF1 h\u1EA1i|mu\u1ED1n ch\u1EBFt|kh\xF4ng mu\u1ED1n s\u1ED1ng n\u1EEFa|qu\xE1 li\u1EC1u"],
96
- gf=["panic attacks?","(?:mental|nervous) breakdown","psychotic (?:episode|break)","hearing voices","mental health crisis","feel(?:ing)? (?:so |really |very |completely )?(?:hopeless|worthless|suicidal\
96
+ vf=["panic attacks?","(?:mental|nervous) breakdown","psychotic (?:episode|break)","hearing voices","mental health crisis","feel(?:ing)? (?:so |really |very |completely )?(?:hopeless|worthless|suicidal\
97
97
  |empty inside)","i(?:'m| am) (?:so |really |very )?(?:depressed|hopeless|worthless)","eating disorder",`anorexi${K}`,`bulimi${K}`,"ataques? de (?:p\xE1nico|panico|ansiedad)","crisis de (?:p\xE1nico|panic\
98
98
  o|ansiedad)","(?:me siento|estoy) (?:muy )?(?:deprimid[oa]|desesperad[oa]|sin esperanza)","atacs? de (?:p\xE0nic|p\xE1nico|ansietat)","(?:em sento|estic) (?:molt )?(?:deprimit|deprimida|desesperat|des\
99
99
  esperada)","crises? (?:de panique|d'angoisse)","attaques? de panique","je suis (?:tr\xE8s )?d\xE9prim\xE9e?",`panikattacke${K}`,"ich bin (?:so |sehr )?(?:depressiv|verzweifelt)","attacc(?:o|hi) di pan\
100
100
  ico","(?:sono|mi sento) (?:molto )?(?:depress[oa]|disperat[oa])","(?:ataques?|crises?) de (?:p\xE2nico|ansiedade)","(?:estou|me sinto) (?:muito )?(?:deprimid[oa]|desesperad[oa])",`paniekaanval${K}`,"a\
101
- tak(?:i)? paniki",`panik atak${K}`,"serangan panik","c\u01A1n ho\u1EA3ng lo\u1EA1n"],bf=["heart attack","having a stroke","(?:can't|cannot|can not) breathe","(?:not|stopped) breathing","chest pains?",
101
+ tak(?:i)? paniki",`panik atak${K}`,"serangan panik","c\u01A1n ho\u1EA3ng lo\u1EA1n"],yf=["heart attack","having a stroke","(?:can't|cannot|can not) breathe","(?:not|stopped) breathing","chest pains?",
102
102
  `anaphyla${K}`,"(?:is |was |went |gone )unconscious","(?:having|had|is having) a seizure","(?:severe|heavy) bleeding|bleeding (?:heavily|profusely|a lot|won't stop)","swallowed (?:bleach|poison|a batt\
103
103
  ery|batteries|pills)","call (?:911|999|112|an ambulance)","medical emergency","infarto","no (?:puedo|puede) respirar","(?:dolor|dolores) (?:en el|de) pecho","(?:est\xE1|esta) inconsciente","emergencia\
104
104
  m\xE9dica","infart","no (?:puc|pot) respirar","emerg\xE8ncia m\xE8dica","crise cardiaque","(?:je n'arrive pas \xE0|je ne peux pas|il ne peut pas|elle ne peut pas) respirer","urgence m\xE9dicale","her\
105
105
  zinfarkt","(?:kann|bekomme) (?:nicht|keine) (?:atmen|luft)","medizinischer notfall","non riesc[oe] a respirare","emergenza medica","ataque card\xEDaco","n\xE3o consig[oa] respirar","emerg\xEAncia m\xE9dica",
106
106
  "hartaanval","zawa\u0142 serca","nie mog\u0119 oddycha\u0107","kalp krizi","nefes alam\u0131yorum","serangan jantung","tidak bisa bernapas","nh\u1ED3i m\xE1u c\u01A1 tim|\u0111\u1ED9t qu\u1EF5|kh\xF4ng th\u1EDF \u0111\u01B0\u1EE3c"],
107
- vf=/(?<![\p{L}\p{N}])(?:suicide (?:squad|doors?|burn|king|linux|slide|bid)|shoot myself in the foot)(?![\p{L}\p{N}])/gu,bi=t=>new RegExp(`(?<![\\p{L}\\p{N}])(?:${t.join("|")})(?![\\p{L}\\p{N}])`,"u"),
108
- yf=bi(hf),kf=bi(gf),xf=bi(bf);function wf(t){return t.normalize("NFC").replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").replace(vf," ")}function Sf(t){if(typeof t!="string"||t==="")return null;
109
- let e=wf(t);return yf.test(e)?"self-harm":kf.test(e)?"mental-health-crisis":xf.test(e)?"medical-emergency":null}function ic(t){for(let e of t){let n=Sf(e);if(n!==null)return n}return null}var Ef=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\
107
+ kf=/(?<![\p{L}\p{N}])(?:suicide (?:squad|doors?|burn|king|linux|slide|bid)|shoot myself in the foot)(?![\p{L}\p{N}])/gu,bi=t=>new RegExp(`(?<![\\p{L}\\p{N}])(?:${t.join("|")})(?![\\p{L}\\p{N}])`,"u"),
108
+ xf=bi(bf),wf=bi(vf),Sf=bi(yf);function Ef(t){return t.normalize("NFC").replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").replace(kf," ")}function Cf(t){if(typeof t!="string"||t==="")return null;
109
+ let e=Ef(t);return xf.test(e)?"self-harm":wf.test(e)?"mental-health-crisis":Sf.test(e)?"medical-emergency":null}function ic(t){for(let e of t){let n=Cf(e);if(n!==null)return n}return null}var Tf=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\
110
110
  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|\
111
111
  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\
112
112
  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\
113
113
  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\
114
- nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),Cf=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nu\
114
+ nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),Rf=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nu\
115
115
  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\
116
116
  |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\
117
117
  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\
118
118
  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\
119
- 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 It(t){let e=[],n=t.normalizedText,
120
- r=(t.original.tools??[]).some(v=>v.risk==="write"||v.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||Ef.test(n),i=Cf.test(n),s=(t.temperature??0)>.3&&t.seed==null,a=ic(
119
+ 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 _t(t){let e=[],n=t.normalizedText,
120
+ r=(t.original.tools??[]).some(v=>v.risk==="write"||v.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||Tf.test(n),i=Rf.test(n),s=(t.temperature??0)>.3&&t.seed==null,a=ic(
121
121
  t.messages.filter(v=>v.role==="user").map(v=>typeof v.content=="string"?v.content:"")),c=t.messages.filter(v=>v.role==="user").length,l=(t.original?.tools?.length??0)>0,u=t.messages.some(v=>v.role==="\
122
122
  tool"||v.role==="assistant"&&(v.toolCalls?.length??0)>0),d=l||u||c>1,p=t.original?.savings?.semanticCache==="include-agentic";r&&e.push("write/destructive tools present"),o&&e.push("freshness-sensitiv\
123
123
  e request"),i&&e.push("personalized/account-scoped request"),s&&e.push("stochastic sampling (temp>0.3, no seed)"),a!==null&&e.push(`sensitive topic (${a}) \u2192 exact and semantic cache off, no reference \
@@ -132,18 +132,18 @@ now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store
132
132
  next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:sc(n),expiresAtMs:r!=null?this.now()+r:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};function sc(t){
133
133
  try{return structuredClone(t)}catch{return t}}var Cr=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.
134
134
  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.
135
- waiters.get(e)??1)+1),n}get activeKeys(){return this.inflight.size}};function Mn(t){return !Number.isFinite(t)||t<0?-1:t>=1?1e3:Math.floor(t*1e3+1e-9)}var $n=t=>t/1e3;function Tf(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),
135
+ waiters.get(e)??1)+1),n}get activeKeys(){return this.inflight.size}};function Mn(t){return !Number.isFinite(t)||t<0?-1:t>=1?1e3:Math.floor(t*1e3+1e-9)}var $n=t=>t/1e3;function Pf(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),
136
136
  o=Math.log1p(-n),i=t*o,s=[i],a=i;for(let l=0;l<e;l++)i+=Math.log(t-l)-Math.log(l+1)+r-o,s.push(i),i>a&&(a=i);let c=0;for(let l of s)c+=Math.exp(l-a);return Math.min(1,Math.exp(a+Math.log(c)))}function ki(t,e,n,r){
137
- return t<=0||e>=t*n?false:Tf(t,e,n)<=r}function Pr(t,e){return Math.ceil(Math.log(e)/Math.log1p(-t))}function Tr(t,e){return 6*t/(Math.PI*Math.PI*(e+1)*(e+1))}var ct=class{total=new Uint32Array(1001);erroneas=new Uint32Array(
137
+ return t<=0||e>=t*n?false:Pf(t,e,n)<=r}function Pr(t,e){return Math.ceil(Math.log(e)/Math.log1p(-t))}function Tr(t,e){return 6*t/(Math.PI*Math.PI*(e+1)*(e+1))}var ct=class{total=new Uint32Array(1001);erroneas=new Uint32Array(
138
138
  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(
139
- 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 Rf(t,e,n){let{n:r,e:o}=t.acumulados(),i=null;for(let s=1e3;s>=0;s--)ki(r[s],o[s],e,n)&&(i=
140
- s);if(i==null)return null;for(;i<1e3&&t.total[i]===0;)i++;return i}function xi(t,e,n){let r=[];for(let o of [1,1/4,1/16,1/64,1/256]){let i=Rf(t,e,n*o);i!=null&&r.push(i);}return r}function wi(t,e,n,r){let{
139
+ 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 _f(t,e,n){let{n:r,e:o}=t.acumulados(),i=null;for(let s=1e3;s>=0;s--)ki(r[s],o[s],e,n)&&(i=
140
+ s);if(i==null)return null;for(;i<1e3&&t.total[i]===0;)i++;return i}function xi(t,e,n){let r=[];for(let o of [1,1/4,1/16,1/64,1/256]){let i=_f(t,e,n*o);i!=null&&r.push(i);}return r}function wi(t,e,n,r){let{
141
141
  n:o,e:i}=t.acumulados(),s=[...new Set(e)].sort((c,l)=>l-c),a=null;for(let c of s){if(!ki(o[c],i[c],n,r))break;a={indice:c,retenidas:o[c],erroneas:i[c]};}return a}var Ln=class t{constructor(e,n){this.delta=
142
142
  e;this.alfa=n;this.primeraMirada=2*Pr(e,Tr(n,0));}delta;alfa;seleccion=new ct;retenida=new ct;etiquetas=0;miradas=0;candidatoPrevio=null;certificado=null;primeraMirada;etiquetasDeLaMirada(e){return vi(
143
143
  this.primeraMirada,e)}exportar(){return {labeled:this.etiquetas,looks:this.miradas,previousCandidate:this.candidatoPrevio,certified:this.certificado?{floorIndex:this.certificado.indice,heldOut:this.certificado.
144
- retenidas,wrong:this.certificado.erroneas}:null,selection:ac(this.seleccion),heldOut:ac(this.retenida)}}static restaurar(e,n,r,o){let i=new t(e,n),s=g=>{throw new _e(`importCalibration: ${o}: ${g}`)};
144
+ retenidas,wrong:this.certificado.erroneas}:null,selection:ac(this.seleccion),heldOut:ac(this.retenida)}}static restaurar(e,n,r,o){let i=new t(e,n),s=g=>{throw new Ie(`importCalibration: ${o}: ${g}`)};
145
145
  (r===null||typeof r!="object"||Array.isArray(r))&&s("not an object");let a=r,c=a.labeled;On(c)||s("`labeled` must be a non-negative integer");let l=c,u=cc(a.selection,`${o}.selection`),d=cc(a.heldOut,
146
- `${o}.heldOut`);(u.n!==Math.ceil(l/2)||d.n!==Math.floor(l/2))&&s(`the two halves hold ${u.n} and ${d.n} labels, but ${l} labels split by arrival order give ${Math.ceil(l/2)} and ${Math.floor(l/2)}`);let p=Pf(
146
+ `${o}.heldOut`);(u.n!==Math.ceil(l/2)||d.n!==Math.floor(l/2))&&s(`the two halves hold ${u.n} and ${d.n} labels, but ${l} labels split by arrival order give ${Math.ceil(l/2)} and ${Math.floor(l/2)}`);let p=If(
147
147
  i.primeraMirada,l);a.looks!==p&&s(`\`looks\` is ${String(a.looks)}, but ${l} labels have already spent ${p} tests of the confidence budget; a state cannot start that spending over`);let h=a.previousCandidate;
148
148
  h!==null&&!yi(h)&&s("`previousCandidate` must be null or a grid index");let f=a.certified,m=null;if(f!==null){(f===void 0||typeof f!="object"||Array.isArray(f))&&s("`certified` must be null or an obje\
149
149
  ct");let g=f;yi(g.floorIndex)||s("`certified.floorIndex` must be a grid index"),(!On(g.heldOut)||!On(g.wrong))&&s("`certified.heldOut` and `certified.wrong` must be non-negative integers"),m={indice:g.
@@ -155,35 +155,35 @@ i.candidatoPrevio=h,i.certificado=m,i}anotar(e,n){let r=Mn(e);r<0||((this.etique
155
155
  this.mirar());}mirar(){let e=Tr(this.alfa,this.miradas);this.miradas++;let n=xi(this.seleccion,this.delta,e),r=this.candidatoPrevio==null?n:[...n,this.candidatoPrevio],o=wi(this.retenida,r,this.delta,e);
156
156
  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.
157
157
  retenida.n,retenidasEnSuelo:this.certificado?.retenidas??0,erroneasEnSuelo:this.certificado?.erroneas??0,miradas:this.miradas,minimasParaLaSiguiente:Pr(this.delta,Tr(this.alfa,this.miradas)),etiquetasParaLaSiguiente:this.
158
- etiquetasDeLaMirada(this.miradas)}}},_e=class extends Error{constructor(e){super(`[bvsala] ${e}`),this.name="CalibrationStateError";}},lc="bvsala.semantic-calibration",Rr=1,uc=["single_shot","agentic"];
158
+ etiquetasDeLaMirada(this.miradas)}}},Ie=class extends Error{constructor(e){super(`[bvsala] ${e}`),this.name="CalibrationStateError";}},lc="bvsala.semantic-calibration",Rr=1,uc=["single_shot","agentic"];
159
159
  function dc(t,e){let n={};for(let r of uc){let o=e.get(r);o&&(n[r]=o.exportar());}return {format:lc,version:Rr,embedder:t.embedder,verifier:t.verifier,judge:t.judge,config:{maxErrorRate:t.maxErrorRate,confidence:t.
160
- confidence,similarityThreshold:t.similarityThreshold,grid:1e3},segments:n}}function pc(t,e){let n=u=>{throw new _e(`importCalibration: ${u}`)};(t===null||typeof t!="object"||Array.isArray(t))&&n("the \
160
+ confidence,similarityThreshold:t.similarityThreshold,grid:1e3},segments:n}}function pc(t,e){let n=u=>{throw new Ie(`importCalibration: ${u}`)};(t===null||typeof t!="object"||Array.isArray(t))&&n("the \
161
161
  state must be an object");let r=t;r.format!==lc&&n(`not a semantic calibration state (format ${JSON.stringify(r.format)})`);let o=r.version;typeof o=="number"&&o>Rr&&n(`this state was exported by a ne\
162
162
  wer SDK (version ${o}); this one reads version ${Rr}`),o!==Rr&&n(`unknown state version ${JSON.stringify(o)}`);let i=r.config??{},s=[],a=(u,d,p)=>{d!==p&&s.push(`${u}: ${JSON.stringify(d)} in the stat\
163
163
  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,
164
164
  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\
165
165
  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 l=new Map;for(let[
166
166
  u,d]of Object.entries(c))uc.includes(u)||n(`unknown segment ${JSON.stringify(u)}`),l.set(u,Ln.restaurar(e.maxErrorRate,1-e.confidence,d,`segments.${u}`));return l}function vi(t,e){return Math.ceil(t*1.5**
167
- e)}function Pf(t,e){let n=0;for(;vi(t,n)<=e;)n++;return n}function On(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=4294967295}function yi(t){return typeof t=="number"&&Number.isInteger(
168
- t)&&t>=0&&t<=1e3}function ac(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 cc(t,e){let n=i=>{throw new _e(`importCalibration: ${e}: ${i}`)};Array.
167
+ e)}function If(t,e){let n=0;for(;vi(t,n)<=e;)n++;return n}function On(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=4294967295}function yi(t){return typeof t=="number"&&Number.isInteger(
168
+ t)&&t>=0&&t<=1e3}function ac(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 cc(t,e){let n=i=>{throw new Ie(`importCalibration: ${e}: ${i}`)};Array.
169
169
  isArray(t)||n("must be an array of [gridIndex, labels, wrong]");let r=new ct,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;(!yi(
170
170
  s)||s<=o)&&n("grid indices must be increasing integers in [0, 1000]"),(!On(a)||a===0)&&n("label counts must be positive integers"),(!On(c)||c>a)&&n("wrong counts must be integers between 0 and the lab\
171
- 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 Ir(t){let{maxErrorRate:e}=t,n=t.confidence??.95,r=t.auditRate??.05;if(!(e>0&&e<=.5))throw new RangeError(
171
+ 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 _r(t){let{maxErrorRate:e}=t,n=t.confidence??.95,r=t.auditRate??.05;if(!(e>0&&e<=.5))throw new RangeError(
172
172
  `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\
173
173
  .auditRate must be in [0, 1); got ${r}`);return {maxErrorRate:e,confidence:n,auditRate:r}}function fc(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>>>
174
- 7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function Nn(t,e){let n=o=>o!==null&&typeof o=="object";if(n(t.data)&&n(e.data))return _r(t.data)===_r(e.data);let r=o=>o.trim().replace(/\s+/g," ");return r(t.text)===r(e.text)}function _r(t){if(Array.
175
- isArray(t))return `[${t.map(_r).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)}:${_r(e[n])}`).join(",")}}`}return JSON.
176
- stringify(t)??"null"}function Mk(t,e){let{maxErrorRate:n,confidence:r}=Ir(e),o=1-r,i=new ct,s=new ct,a=fc(1592642065),c=0;for(let u of t){let d=Mn(u.score),p=a()<.5;d<0||((p?i:s).anotar(d,u.correct),c++);}
174
+ 7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function Nn(t,e){let n=o=>o!==null&&typeof o=="object";if(n(t.data)&&n(e.data))return Ir(t.data)===Ir(e.data);let r=o=>o.trim().replace(/\s+/g," ");return r(t.text)===r(e.text)}function Ir(t){if(Array.
175
+ isArray(t))return `[${t.map(Ir).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)}:${Ir(e[n])}`).join(",")}}`}return JSON.
176
+ stringify(t)??"null"}function Bk(t,e){let{maxErrorRate:n,confidence:r}=_r(e),o=1-r,i=new ct,s=new ct,a=fc(1592642065),c=0;for(let u of t){let d=Mn(u.score),p=a()<.5;d<0||((p?i:s).anotar(d,u.correct),c++);}
177
177
  let l=wi(s,xi(i,n,o),n,o);return {maxErrorRate:n,confidence:r,floor:l?$n(l.indice):null,labeled:c,heldOut:s.n,heldOutAtFloor:l?.retenidas??0,wrongHeldOutAtFloor:l?.erroneas??0,minHeldOutToCertify:Pr(n,
178
- o)}}var Si=new Map;function N(t,e){for(let n of t.split(/\s+/).filter(Boolean))Si.set(n,e);}var If=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen",
179
- "fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];If.forEach((t,e)=>N(t,{k:"unidad",v:e}));["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"].forEach((t,e)=>N(t,{k:"\
180
- decena",v:20+10*e}));N("hundred hundreds",{k:"cien"});N("thousand thousands",{k:"escala",v:1e3});N("million millions",{k:"escala",v:1e6});N("billion billions",{k:"escala",v:1e9});var _f=["","first","s\
181
- econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];_f.forEach((t,e)=>{
178
+ o)}}var Si=new Map;function N(t,e){for(let n of t.split(/\s+/).filter(Boolean))Si.set(n,e);}var Df=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen",
179
+ "fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"];Df.forEach((t,e)=>N(t,{k:"unidad",v:e}));["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"].forEach((t,e)=>N(t,{k:"\
180
+ decena",v:20+10*e}));N("hundred hundreds",{k:"cien"});N("thousand thousands",{k:"escala",v:1e3});N("million millions",{k:"escala",v:1e6});N("billion billions",{k:"escala",v:1e9});var Af=["","first","s\
181
+ econd","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth","thirteenth","fourteenth","fifteenth","sixteenth","seventeenth","eighteenth","nineteenth"];Af.forEach((t,e)=>{
182
182
  t&&(N(t,{k:"ordinal",v:e}),e>=3&&N(`${t}s`,{k:"ordinal",v:e}));});["twentieth","thirtieth","fortieth","fiftieth","sixtieth","seventieth","eightieth","ninetieth"].forEach((t,e)=>{N(t,{k:"ordinal",v:20+10*
183
183
  e}),N(`${t}s`,{k:"ordinal",v:20+10*e});});N("hundredth hundredths",{k:"ordinal",v:100});N("thousandth thousandths",{k:"ordinal",v:1e3});N("millionth millionths",{k:"ordinal",v:1e6});N("half halves",{k:"\
184
184
  token",t:"f:1/2"});N("quarter quarters",{k:"token",t:"f:1/4"});N("once single",{k:"token",t:"m:1"});N("twice double doubled doubles doubling",{k:"token",t:"m:2"});N("thrice triple tripled triples trip\
185
185
  ling",{k:"token",t:"m:3"});N("quadruple quadrupled quadruples quadrupling",{k:"token",t:"m:4"});N("dozen dozens",{k:"token",t:"c:12"});N("pair pairs",{k:"token",t:"c:2"});N("times time",{k:"veces"});N(
186
- "and",{k:"conector"});var Df=["cero","uno","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","","doce","trece","catorce","quince","dieciseis","diecisiete","dieciocho","diecinueve"];Df.
186
+ "and",{k:"conector"});var Of=["cero","uno","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","","doce","trece","catorce","quince","dieciseis","diecisiete","dieciocho","diecinueve"];Of.
187
187
  forEach((t,e)=>t&&N(t,{k:"unidad",v:e}));N("veinte",{k:"decena",v:20});["veintiuno","veintidos","veintitres","veinticuatro","veinticinco","veintiseis","veintisiete","veintiocho","veintinueve"].forEach(
188
188
  (t,e)=>N(t,{k:"unidad",v:21+e}));["treinta","cuarenta","cincuenta","sesenta","setenta","ochenta","noventa"].forEach((t,e)=>N(t,{k:"decena",v:30+10*e}));N("cien ciento",{k:"centena",v:100});[["doscient\
189
189
  os doscientas",200],["trescientos trescientas",300],["cuatrocientos cuatrocientas",400],["quinientos quinientas",500],["seiscientos seiscientas",600],["setecientos setecientas",700],["ochocientos ocho\
@@ -196,33 +196,33 @@ forEach(([t,e])=>N(t,{k:"ordinal",v:e}));N("mitad mitades medio media medios med
196
196
  uanta","seixanta","setanta","vuitanta","noranta"].forEach((t,e)=>N(t,{k:"decena",v:20+10*e}));N("cent",{k:"centena",v:100});N("cents centes",{k:"cien"});N("milio milions",{k:"escala",v:1e6});[["segon \
197
197
  segona segons segones",2],["terc tercos",3],["quart quarta quarts quartes",4],["cinque cinquena",5],["sise sisena",6],["sete setena",7],["vuite vuitena",8],["nove novena",9],["dese desena",10]].forEach(
198
198
  ([t,e])=>N(t,{k:"ordinal",v:e}));N("meitat meitats mig mitja",{k:"token",t:"f:1/2"});N("dotzena dotzenes",{k:"token",t:"c:12"});N("parell parells",{k:"token",t:"c:2"});N("vegades vegada",{k:"veces"});
199
- N("i",{k:"conector"});var Af=/\p{M}+/gu;function Of(t){return t.toLowerCase().normalize("NFD").replace(Af,"").split(/[^\p{L}]+/u).filter(Boolean)}function Ei(t){let e=[],n=Of(t),r=false,o=0,i=0,s=null,a=1/0,
199
+ N("i",{k:"conector"});var Lf=/\p{M}+/gu;function Mf(t){return t.toLowerCase().normalize("NFD").replace(Lf,"").split(/[^\p{L}]+/u).filter(Boolean)}function Ei(t){let e=[],n=Mf(t),r=false,o=0,i=0,s=null,a=1/0,
200
200
  c=(u="n")=>{r&&e.push(`${u}:${o+i}`),r=false,o=0,i=0,s=null,a=1/0;},l=(u,d)=>{c(),r=true,i=u,s=d;};for(let u=0;u<n.length;u++){let d=Si.get(n[u]);if(!d){c();continue}switch(d.k){case "unidad":{r&&(s==="decena"&&
201
201
  d.v<10&&i%10===0||(s==="cien"||s==="centena")&&i%100===0||s==="escala")?(i+=d.v,s="unidad"):l(d.v,"unidad");break}case "decena":{r&&((s==="cien"||s==="centena")&&i%100===0||s==="escala")?(i+=d.v,s="dec\
202
202
  ena"):l(d.v,"decena");break}case "centena":{r&&s==="escala"?(i+=d.v,s="centena"):l(d.v,"centena");break}case "cien":{r&&(s==="unidad"||s==="decena")&&i>0&&i<100?(i*=100,s="cien"):l(100,"cien");break}case "\
203
203
  escala":{r&&s!=="escala"&&d.v<a?(o+=(i||1)*d.v,i=0,s="escala",a=d.v):(l(0,"escala"),o=d.v,a=d.v);break}case "ordinal":{if(r&&s==="decena"&&d.v<10&&i%10===0){let p=o+i+d.v;r=false,c(),e.push(`o:${p}`);}else
204
204
  c(),e.push(`o:${d.v}`);break}case "veces":{r&&c("m");break}case "conector":{let p=Si.get(n[u+1]??"");r&&(s==="decena"||s==="cien"||s==="centena"||s==="escala")&&p!=null&&(p.k==="unidad"||p.k==="decena")||
205
- c();break}case "token":{c(),e.push(d.t);break}}}return c(),e}function Lf(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 Mf(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(
206
- Boolean)}function mc(t){let e=new Array(256).fill(0),n=Mf(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+
207
- 1]}`;r.set(a,(r.get(a)??0)+1);}}for(let[i,s]of r){let a=Lf(i),c=a%256,l=a>>>31===1?-1:1;e[c]+=l*(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++)
208
- e[i]/=o;return e}function jk(t){return mc(t)}function hc(t){return mc(t)}var $f=.72,gc=$f;function Ci(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 Nf=new Set(
205
+ c();break}case "token":{c(),e.push(d.t);break}}}return c(),e}function $f(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 Nf(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(
206
+ Boolean)}function mc(t){let e=new Array(256).fill(0),n=Nf(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+
207
+ 1]}`;r.set(a,(r.get(a)??0)+1);}}for(let[i,s]of r){let a=$f(i),c=a%256,l=a>>>31===1?-1:1;e[c]+=l*(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++)
208
+ e[i]/=o;return e}function qk(t){return mc(t)}function hc(t){return mc(t)}var jf=.72,gc=jf;function Ci(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 Bf=new Set(
209
209
  ["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\
210
- \xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),jf=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what",
210
+ \xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),zf=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what",
211
211
  "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",
212
212
  "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\
213
213
  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",
214
214
  "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",
215
- "aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function _t(t){return (t.
215
+ "aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function It(t){return (t.
216
216
  match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function jn(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)
217
- return false;n.set(r,o-1);}return true}function Dt(t){return t.split(/\s+/).filter(Boolean)}function At(t){return t.filter(e=>Nf.has(e.replace(/'/g,""))||e.endsWith("n't")).length}var Bf=/^(system|user|assistant|tool):/;
217
+ return false;n.set(r,o-1);}return true}function Dt(t){return t.split(/\s+/).filter(Boolean)}function At(t){return t.filter(e=>Bf.has(e.replace(/'/g,""))||e.endsWith("n't")).length}var Ff=/^(system|user|assistant|tool):/;
218
218
  function bc(t){return t.split(`
219
- `).map(e=>{let n=Bf.exec(e);return n?{rol:n[1],texto:e.slice(n[0].length)}:{rol:"",texto:e}})}function Ti(t,e){let n=bc(t),r=bc(e);if(n.length!==r.length)return false;for(let o=0;o<n.length;o++)if(n[o].rol!==
220
- r[o].rol||!zf(n[o].texto,r[o].texto))return false;return true}function zf(t,e){let n=[..._t(t),...Ei(t)],r=[..._t(e),...Ei(e)];if(!jn(n,r))return false;let o=Dt(t),i=Dt(e);if(At(o)!==At(i))return false;let s=d=>d.length>
221
- 1&&!jf.has(d)&&!/^\d/.test(d),a=new Set(o.filter(s)),c=new Set(i.filter(s));if(a.size===0&&c.size===0)return true;let l=0;for(let d of a)c.has(d)&&l++;let u=a.size+c.size-l;return u===0?true:l/u>=.75}var Ff="\
222
- lexical-256-v1",qf="same-answer-v1",vc=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;embebedorPropio;calibracion;estados=new Map;nombres;pendientes=new Set;aceptacionExplicita;constructor(e={}){
219
+ `).map(e=>{let n=Ff.exec(e);return n?{rol:n[1],texto:e.slice(n[0].length)}:{rol:"",texto:e}})}function Ti(t,e){let n=bc(t),r=bc(e);if(n.length!==r.length)return false;for(let o=0;o<n.length;o++)if(n[o].rol!==
220
+ r[o].rol||!qf(n[o].texto,r[o].texto))return false;return true}function qf(t,e){let n=[...It(t),...Ei(t)],r=[...It(e),...Ei(e)];if(!jn(n,r))return false;let o=Dt(t),i=Dt(e);if(At(o)!==At(i))return false;let s=d=>d.length>
221
+ 1&&!zf.has(d)&&!/^\d/.test(d),a=new Set(o.filter(s)),c=new Set(i.filter(s));if(a.size===0&&c.size===0)return true;let l=0;for(let d of a)c.has(d)&&l++;let u=a.size+c.size-l;return u===0?true:l/u>=.75}var Uf="\
222
+ lexical-256-v1",Vf="same-answer-v1",vc=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;embebedorPropio;calibracion;estados=new Map;nombres;pendientes=new Set;aceptacionExplicita;constructor(e={}){
223
223
  let n=e.embed==null;if(this.embebedorPropio=n,this.embed=e.embed??hc,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??(n?gc:.9),this.acceptThreshold=e.acceptThreshold??.85,this.aceptacionExplicita=
224
224
  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}:{}},
225
- this.ttlMs=e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now()),e.calibration){let r=Ir(e.calibration);this.calibracion={...r,judge:e.calibration.judge??Nn,perRecordFloors:e.calibration.
225
+ this.ttlMs=e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now()),e.calibration){let r=_r(e.calibration);this.calibracion={...r,judge:e.calibration.judge??Nn,perRecordFloors:e.calibration.
226
226
  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){
227
227
  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!==
228
228
  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||
@@ -239,11 +239,11 @@ if(!r)return null;let o;try{o=await r.judge(e.record.answer,n)===!0;}catch{retur
239
239
  failedAtScore??-1/0,e.score)),o}async settled(){for(;this.pendientes.size>0;)await Promise.allSettled([...this.pendientes]);}calibrationStatus(e="single_shot"){let n=this.calibracion;if(!n)return null;
240
240
  let r=this.estadoDe(e).resumen();return {maxErrorRate:n.maxErrorRate,confidence:n.confidence,floor:r.suelo==null?null:$n(r.suelo),labeled:r.etiquetas,heldOut:r.retenidas,heldOutAtFloor:r.retenidasEnSuelo,
241
241
  wrongHeldOutAtFloor:r.erroneasEnSuelo,minHeldOutToCertify:r.minimasParaLaSiguiente,nextTestAt:r.etiquetasParaLaSiguiente}}exportCalibration(){return dc(this.identidad("exportCalibration"),this.estados)}importCalibration(e){
242
- let n=this.identidad("importCalibration"),r=e;if(typeof e=="string")try{r=JSON.parse(e);}catch{throw new _e("importCalibration: the state is a string but not JSON")}let o=pc(r,n);for(let[i]of o){let s=this.
243
- estados.get(i);if(s&&s.resumen().etiquetas>0)throw new _e(`importCalibration: this cache has already recorded ${s.resumen().etiquetas} labels in the ${i} segment; import right after constructing it`)}
244
- for(let[i,s]of o)this.estados.set(i,s);}identidad(e){let n=this.calibracion;if(!n)throw new _e(`${e}: this cache runs without \`calibration\``);let r=(a,c)=>{throw new _e(`${e}: pass \`${a}\` naming you\
245
- r ${c}, so that a saved calibration is only ever restored under the same one`)},o=this.embebedorPropio?`built_in:${Ff}`:`custom:${this.nombres.embedder??r("embedderId","embed function")}`,i=this.verify==
246
- null?null:`custom:${this.nombres.verifier??r("verifierId","verifier")}`,s=n.judge===Nn?`built_in:${qf}`:`custom:${this.nombres.judge??r("calibration.judgeId","judge")}`;return {embedder:o,verifier:i,judge:s,
242
+ let n=this.identidad("importCalibration"),r=e;if(typeof e=="string")try{r=JSON.parse(e);}catch{throw new Ie("importCalibration: the state is a string but not JSON")}let o=pc(r,n);for(let[i]of o){let s=this.
243
+ estados.get(i);if(s&&s.resumen().etiquetas>0)throw new Ie(`importCalibration: this cache has already recorded ${s.resumen().etiquetas} labels in the ${i} segment; import right after constructing it`)}
244
+ for(let[i,s]of o)this.estados.set(i,s);}identidad(e){let n=this.calibracion;if(!n)throw new Ie(`${e}: this cache runs without \`calibration\``);let r=(a,c)=>{throw new Ie(`${e}: pass \`${a}\` naming you\
245
+ r ${c}, so that a saved calibration is only ever restored under the same one`)},o=this.embebedorPropio?`built_in:${Uf}`:`custom:${this.nombres.embedder??r("embedderId","embed function")}`,i=this.verify==
246
+ null?null:`custom:${this.nombres.verifier??r("verifierId","verifier")}`,s=n.judge===Nn?`built_in:${Vf}`:`custom:${this.nombres.judge??r("calibration.judgeId","judge")}`;return {embedder:o,verifier:i,judge:s,
247
247
  maxErrorRate:n.maxErrorRate,confidence:n.confidence,similarityThreshold:this.similarityThreshold}}estadoDe(e){let n=this.estados.get(e);if(!n){let r=this.calibracion;n=new Ln(r.maxErrorRate,1-r.confidence),
248
248
  this.estados.set(e,n);}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,
249
249
  answer:n,tenantId:e.tenantId,authorizationScope:e.authorizationScope,principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.
@@ -252,42 +252,42 @@ temperature,seed:e.seed,...e.reasoningEffort!==void 0?{reasoningEffort:e.reasoni
252
252
  knowledgeEpoch===e&&(this.records.splice(r,1),n++);return n}get size(){return this.records.length}};var yc=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()>
253
253
  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(
254
254
  o);}this.entradas.set(e,{valor:n,vence:this.now()+r});}get size(){return this.entradas.size}};var Ri=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}},
255
- Uf={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]??Vf(t.normalizedText))?.trim();if(!n)return null;
256
- let r=Pi(n);return r===null||!Number.isFinite(r)?null:{text:Hf(r),data:{value:r},resolver:"arithmetic"}}};function Vf(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function Hf(t){
255
+ Hf={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]??Wf(t.normalizedText))?.trim();if(!n)return null;
256
+ let r=Pi(n);return r===null||!Number.isFinite(r)?null:{text:Gf(r),data:{value:r},resolver:"arithmetic"}}};function Wf(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function Gf(t){
257
257
  return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function Pi(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],r=[],o={"+":1,"-":1,
258
258
  "*":2,"/":2,"%":2},i=a=>{let c=n.pop(),l=n.pop();if(l===void 0||c===void 0)return false;switch(a){case "+":return n.push(l+c),true;case "-":return n.push(l-c),true;case "*":return n.push(l*c),true;case "/":return c===
259
259
  0?false:(n.push(l/c),true);case "%":return c===0?false:(n.push(l%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&&
260
260
  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),
261
- s=true;}for(;r.length;){let a=r.pop();if(a==="("||!i(a))return null}return n.length===1?n[0]:null}function kc(){return new Ri().register(Uf)}var Wf=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,xc=/\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,
262
- Gf=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,Dr=class{classifier;maxRounds;constructor(e={}){this.
261
+ s=true;}for(;r.length;){let a=r.pop();if(a==="("||!i(a))return null}return n.length===1?n[0]:null}function kc(){return new Ri().register(Hf)}var Kf=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,xc=/\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,
262
+ Jf=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,Dr=class{classifier;maxRounds;constructor(e={}){this.
263
263
  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.
264
- test(r))return He("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return He("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(Gf.test(r)&&!xc.test(r))return He("NO_RETRIEVAL",
265
- .8,"self-contained transformation",0);let i=this.classifier?.classify(r);return i&&i.confidence>=.75?He(i.executionClass,i.confidence,"local classifier",Kf(i.executionClass,this.maxRounds)):n==="singl\
266
- e"?He("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?He("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):Wf.test(r)?He("MULTI_HOP_RETRIEVAL",.7,"comparison/compoun\
267
- d question",Math.min(this.maxRounds,2)):xc.test(r)?He("SINGLE_RETRIEVAL",.65,"single factual lookup",1):He("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function Kf(t,e){return t===
268
- "SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function He(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var Jf=["claude-fable-5-1","claude-mythos-5-1","claude-fable-5","claude-mythos-5","claude-opus-5-5","claude-opus-5","claude-sonnet-5-5","claude-opus-4-8","claude-opus-4-7","claude-opus-4-6","claude-so\
269
- nnet-4-6","claude-opus-4-5-20251101","claude-sonnet-4-5-20250929","claude-haiku-4-5-20251001"],Ar={herramientas:10,tokensDeEsquemas:1e4},wc=5,Yf={regex:200,bm25:500},Sc=1e4,Or={bm25:{type:"tool_search\
270
- _tool_bm25_20251119",name:"tool_search_tool_bm25"},regex:{type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"}},Zf="bvsala_contract";function Ec(t){let e=t.lastIndexOf("/");return (e>=
271
- 0?t.slice(e+1):t).toLowerCase()}function Ii(t){let e=r=>r.replace(/-\d{8}$/,""),n=e(Ec(t));return Jf.some(r=>e(r)===n)}function _i(t){let e={modo:"off",siempreCargadas:[],variante:"bm25"};if(t===void 0)
264
+ test(r))return He("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return He("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(Jf.test(r)&&!xc.test(r))return He("NO_RETRIEVAL",
265
+ .8,"self-contained transformation",0);let i=this.classifier?.classify(r);return i&&i.confidence>=.75?He(i.executionClass,i.confidence,"local classifier",Yf(i.executionClass,this.maxRounds)):n==="singl\
266
+ e"?He("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?He("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):Kf.test(r)?He("MULTI_HOP_RETRIEVAL",.7,"comparison/compoun\
267
+ d question",Math.min(this.maxRounds,2)):xc.test(r)?He("SINGLE_RETRIEVAL",.65,"single factual lookup",1):He("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function Yf(t,e){return t===
268
+ "SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function He(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var Zf=["claude-fable-5-1","claude-mythos-5-1","claude-fable-5","claude-mythos-5","claude-opus-5-5","claude-opus-5","claude-sonnet-5-5","claude-opus-4-8","claude-opus-4-7","claude-opus-4-6","claude-so\
269
+ nnet-4-6","claude-opus-4-5-20251101","claude-sonnet-4-5-20250929","claude-haiku-4-5-20251001"],Ar={herramientas:10,tokensDeEsquemas:1e4},wc=5,Xf={regex:200,bm25:500},Sc=1e4,Or={bm25:{type:"tool_search\
270
+ _tool_bm25_20251119",name:"tool_search_tool_bm25"},regex:{type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"}},Qf="bvsala_contract";function Ec(t){let e=t.lastIndexOf("/");return (e>=
271
+ 0?t.slice(e+1):t).toLowerCase()}function _i(t){let e=r=>r.replace(/-\d{8}$/,""),n=e(Ec(t));return Zf.some(r=>e(r)===n)}function Ii(t){let e={modo:"off",siempreCargadas:[],variante:"bm25"};if(t===void 0)
272
272
  return e;let n=r=>r==="off"||r==="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)?
273
273
  [...new Set(t.alwaysLoaded.filter(r=>typeof r=="string"))]:[],variante:t.variant==="regex"?"regex":"bm25"}}function Di(t){return !t.some(e=>Array.isArray(e.intents)&&e.intents.length>0)&&!t.some(e=>typeof e.
274
274
  risk=="string")}function Ai(t){let{opciones:e}=t,n=e.variante,r=(v,x={})=>({aplicar:false,razon:v,variante:n,siempreCargadas:[],diferidas:0,tokensDiferidos:0,...x});if(e.modo==="off")return r("toolSearch\
275
275
  is off");if(t.herramientas.length===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; \
276
- OpenAI documents tool search for its Responses and Agents APIs, not for Chat Completions, which is what the OpenAI-compatible adapter speaks");if(!Ii(t.modelo))return r(`${Ec(t.modelo)} is not in the \
276
+ OpenAI documents tool search for its Responses and Agents APIs, not for Chat Completions, which is what the OpenAI-compatible adapter speaks");if(!_i(t.modelo))return r(`${Ec(t.modelo)} is not in the \
277
277
  provider's tool search model compatibility 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\
278
278
  is not documented, so the selector keeps 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=Or[n];
279
- if(t.herramientas.some(v=>v.id===o.name))return r(`one of your tools is already named \`${o.name}\``);let i=new Set(t.herramientas.map(v=>v.id)),s=e.siempreCargadas.filter(v=>i.has(v)&&v!==Zf),a=new Set(
279
+ if(t.herramientas.some(v=>v.id===o.name))return r(`one of your tools is already named \`${o.name}\``);let i=new Set(t.herramientas.map(v=>v.id)),s=e.siempreCargadas.filter(v=>i.has(v)&&v!==Qf),a=new Set(
280
280
  s),c=t.herramientas.filter(v=>!a.has(v.id)),l=c.reduce((v,x)=>v+x.tokens,0),u={siempreCargadas:s,diferidas:c.length,tokensDiferidos:l};if(c.length===0)return r("every tool is in `alwaysLoaded`: nothin\
281
281
  g to defer",u);if(c.length>Sc)return r(`${c.length} tools to defer, over the provider's limit of ${Sc}`,u);if(e.modo==="always")return {aplicar:true,variante:n,...u,razon:`toolSearch "always": ${c.length}\
282
282
  tool(s) deferred behind the provider'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\
283
283
  own API host; a proxy may not forward the search blocks. Use toolSearch "always" if yours does`,u);let d=t.herramientas.reduce((v,x)=>v+x.tokens,0);if(t.herramientas.length<Ar.herramientas&&d<=Ar.tokensDeEsquemas)
284
284
  return r(`${t.herramientas.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 b\
285
- etter`,u);let p=t.precio.inputPer1k/1e3,h=t.precio.outputPer1k/1e3,f=Math.min(1,Math.max(0,t.lecturaDeCache)),m=c.map(v=>v.tokens).sort((v,x)=>x-v).slice(0,wc).reduce((v,x)=>v+x,0),g=f*p*l,b=p*m+h*Yf[n],
285
+ etter`,u);let p=t.precio.inputPer1k/1e3,h=t.precio.outputPer1k/1e3,f=Math.min(1,Math.max(0,t.lecturaDeCache)),m=c.map(v=>v.tokens).sort((v,x)=>x-v).slice(0,wc).reduce((v,x)=>v+x,0),g=f*p*l,b=p*m+h*Xf[n],
286
286
  y={ahorroDelPrefijo:g,costeDeUnaBusqueda:b};return g<b?r(`deferring ${l} tokens of definitions saves ${g.toFixed(6)} per request even with a warm prompt cache, less than one worst-case search costs (${b.
287
287
  toFixed(6)}: the ${wc} largest definitions uncached plus the longest query); the selector keeps this request`,{...u,...y}):{aplicar:true,variante:n,...u,...y,razon:`${c.length} tool(s) deferred behind t\
288
288
  he provider's ${n} search (${l} tokens of definitions out of the cached prefix): it pays even if every request searches once with a warm cache (${g.toFixed(6)} saved vs ${b.toFixed(6)} worst-case sear\
289
289
  ch). The provider's counter measures it; the layer credits nothing for it`}}function Cc(t,e,n){return n||Di(t)?[...t]:t.filter(r=>e||r.risk==="read")}var Oi=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});}},Lr=class{maxTools;scoreIntentMatch;learningTurns;freezer;constructor(e={}){
290
- this.maxTools=e.maxTools,this.scoreIntentMatch=e.scoreIntentMatch??Xf,this.learningTurns=e.learningTurns??16,this.freezer=e.freezer??new Oi;}passthrough(e){return !e||e.length===0?{tools:[],droppedIds:[],
290
+ this.maxTools=e.maxTools,this.scoreIntentMatch=e.scoreIntentMatch??em,this.learningTurns=e.learningTurns??16,this.freezer=e.freezer??new Oi;}passthrough(e){return !e||e.length===0?{tools:[],droppedIds:[],
291
291
  reason:"no tools provided",setIsStable:true}:{tools:[...e],droppedIds:[],reason:`router off: caller tools passed through whole (${e.length}/${e.length}; risk gating is the caller's responsibility while \
292
292
  routing is off)`,setIsStable:true}}select(e,n,r,o){if(!n||n.length===0)return {tools:[],droppedIds:[],reason:"no tools provided",setIsStable:true};if(Di(n)){let b=this.passthrough(n);return {...b,reason:`ca\
293
293
  talogue declares no \`intents\` and no \`risk\`: nothing to select on, passed through whole (${b.tools.length}/${n.length}). Declare ToolDescriptor.intents/risk to enable pruning`}}let i=r==="TOOL_ACT\
@@ -298,107 +298,107 @@ b)})).filter(b=>b.score>0).sort((b,y)=>y.score-b.score).map(b=>b.tool),f=[...d.s
298
298
  if(o!==void 0){let b=this.freezer.read(o),y=(b?.turns??0)+1;if(b&&y>this.learningTurns){let x=new Set(b.ids),E=n.filter(C=>x.has(C.id));this.freezer.record(o,b.ids,y);let S=new Set(E.map(C=>C.id));return {
299
299
  tools:E,droppedIds:n.filter(C=>!S.has(C.id)).map(C=>C.id),reason:`frozen tool set after ${this.learningTurns} turns (${E.length}/${n.length}): it no longer depends on this request's text, so the prefi\
300
300
  x cache survives`,setIsStable:true}}let v=[...new Set([...b?.ids??[],...f.map(x=>x.id)])].sort().slice(0,u);this.freezer.record(o,v,y);}let m=new Set(f.map(b=>b.id)),g=n.filter(b=>!m.has(b.id)).map(b=>b.
301
- id);return {tools:f,droppedIds:g,reason:`selected ${f.length}/${n.length} by intent match (writes ${i?"allowed":"blocked"})`,setIsStable:g.length===0}}};function Xf(t,e){let n=tn(t),r=0;for(let o of Array.
302
- isArray(e.intents)?e.intents:[]){let i=tn(o);i&&(n.includes(i)?r+=2:i.split(/\s+/).some(s=>s.length>3&&n.includes(s))&&(r+=1));}return r}function Li(t){let e=new Set,n=[];for(let r of t){let o=r.hash??Qf(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function Mi(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((s,a)=>(a.score??
301
+ id);return {tools:f,droppedIds:g,reason:`selected ${f.length}/${n.length} by intent match (writes ${i?"allowed":"blocked"})`,setIsStable:g.length===0}}};function em(t,e){let n=tn(t),r=0;for(let o of Array.
302
+ isArray(e.intents)?e.intents:[]){let i=tn(o);i&&(n.includes(i)?r+=2:i.split(/\s+/).some(s=>s.length>3&&n.includes(s))&&(r+=1));}return r}function Li(t){let e=new Set,n=[];for(let r of t){let o=r.hash??tm(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function Mi(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((s,a)=>(a.score??
303
303
  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(
304
304
  s);else break}return i}async function Mr(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};
305
305
  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=Li(r),e.reranker&&
306
- (r=await e.reranker.rerank(t.query,r));let i=Mi(r,{maxDocuments:t.maxDocuments});return {docs:i,rounds:n,retrievedCount:o,keptCount:i.length}}function Qf(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function fx(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function mx(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{
307
- ...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&rm(o)?Object.assign(n.userPreferences,
308
- o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let i=tm(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],
309
- nm(n,r);return n}function Tc(t){let e=t.rawTurns??3,n=[],r=em(t.state);r&&n.push({role:"system",content:`Conversation state:
310
- ${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function em(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`fa\
306
+ (r=await e.reranker.rerank(t.query,r));let i=Mi(r,{maxDocuments:t.maxDocuments});return {docs:i,rounds:n,retrievedCount:o,keptCount:i.length}}function tm(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function bx(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function vx(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{
307
+ ...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&im(o)?Object.assign(n.userPreferences,
308
+ o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let i=rm(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],
309
+ om(n,r);return n}function Tc(t){let e=t.rawTurns??3,n=[],r=nm(t.state);r&&n.push({role:"system",content:`Conversation state:
310
+ ${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function nm(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`fa\
311
311
  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(
312
312
  "; ")}`),t.openItems.length&&e.push(`open: ${t.openItems.join("; ")}`),e.join(`
313
- `)}function tm(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 nm(t,e){
314
- for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function rm(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Rc={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function Pc(t,e={}){let n=e.delimiter??",",r=e.indent??" ",i=t.split(`
315
- `).filter(c=>c.trim().length>0).map(c=>({indent:om(c,r),content:c.slice(Ic(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 u=on(
313
+ `)}function rm(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 om(t,e){
314
+ for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function im(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Rc={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function Pc(t,e={}){let n=e.delimiter??",",r=e.indent??" ",i=t.split(`
315
+ `).filter(c=>c.trim().length>0).map(c=>({indent:sm(c,r),content:c.slice(_c(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 u=on(
316
316
  c[2],n),d=Number(c[1]),p=[];for(let h=0,f=1;h<d&&f<i.length;h++,f++){let m=i[f];if(m.indent!==1)break;let g=on(m.content,n),b={};u.forEach((y,v)=>{b[y]=Bn(g[v]??"null");}),p.push(b);}return p}let l=s.content.
317
- match(/^\[(\d+)\]:\s*(.*)$/);if(l){let u=l[2];return Number(l[1])===0||u.trim()===""?[]:on(u,n).map(Bn)}}let[a]=_c(i,0,0,n);return a}function Ic(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}
318
- function om(t,e){return Ic(t,e)/e.length}function _c(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=im(s.content,r);if(!a){i++;continue}let{key:c,
317
+ match(/^\[(\d+)\]:\s*(.*)$/);if(l){let u=l[2];return Number(l[1])===0||u.trim()===""?[]:on(u,n).map(Bn)}}let[a]=Ic(i,0,0,n);return a}function _c(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}
318
+ function sm(t,e){return _c(t,e)/e.length}function Ic(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=am(s.content,r);if(!a){i++;continue}let{key:c,
319
319
  kind:l}=a;if(l.type==="scalar")o[c]=l.value,i++;else if(l.type==="inlineArray")o[c]=l.values,i++;else if(l.type==="emptyArray")o[c]=[],i++;else if(l.type==="table"){let u=[];i++;for(let d=0;d<l.count&&
320
- i<t.length;d++,i++){let p=t[i];if(p.indent!==n+1)break;let h=on(p.content,r),f={};l.columns.forEach((m,g)=>{f[m]=Bn(h[g]??"null");}),u.push(f);}o[c]=u;}else {let[u,d]=_c(t,i+1,n+1,r);o[c]=u,i=d;}}return [o,
321
- i]}function im(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:$r(n[1]),kind:{type:"table",count:Number(n[2]),columns:on(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){
320
+ i<t.length;d++,i++){let p=t[i];if(p.indent!==n+1)break;let h=on(p.content,r),f={};l.columns.forEach((m,g)=>{f[m]=Bn(h[g]??"null");}),u.push(f);}o[c]=u;}else {let[u,d]=Ic(t,i+1,n+1,r);o[c]=u,i=d;}}return [o,
321
+ i]}function am(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:$r(n[1]),kind:{type:"table",count:Number(n[2]),columns:on(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){
322
322
  let i=Number(r[2]),s=r[3];return i===0||s.trim()===""?{key:$r(r[1]),kind:{type:"emptyArray"}}:{key:$r(r[1]),kind:{type:"inlineArray",values:on(s,e).map(Bn)}}}let o=t.match(/^([^:]+):\s*(.*)$/);if(o){let i=$r(
323
323
  o[1]),s=o[2];return s===""?{key:i,kind:{type:"object"}}:{key:i,kind:{type:"scalar",value:Bn(s)}}}return null}function on(t,e){let n=[],r="",o=false;for(let i=0;i<t.length;i++){let s=t[i];o?s==='"'?t[i+1]===
324
324
  '"'?(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 Bn(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,
325
325
  '"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function $r(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,
326
- '"'):e}function sm(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return ji(null,t,0,o,n,r),o.join(`
327
- `)}function ji(t,e,n,r,o,i){let s=i.repeat(n),a=t===null?"":`${cm(t)}`;if(Array.isArray(e)){am(a,e,n,r,o,i);return}if(Ni(e)){t!==null&&r.push(`${s}${a}:`);let c=t===null?n:n+1;for(let[l,u]of Object.entries(
328
- e))ji(l,u,c,r,o,i);return}r.push(`${s}${a}: ${Nr(e,o)}`);}function am(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($i)){let d=e.map(p=>Nr(p,o)).
326
+ '"'):e}function cm(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return ji(null,t,0,o,n,r),o.join(`
327
+ `)}function ji(t,e,n,r,o,i){let s=i.repeat(n),a=t===null?"":`${um(t)}`;if(Array.isArray(e)){lm(a,e,n,r,o,i);return}if(Ni(e)){t!==null&&r.push(`${s}${a}:`);let c=t===null?n:n+1;for(let[l,u]of Object.entries(
328
+ e))ji(l,u,c,r,o,i);return}r.push(`${s}${a}: ${Nr(e,o)}`);}function lm(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($i)){let d=e.map(p=>Nr(p,o)).
329
329
  join(o);r.push(`${s}${a}[${e.length}]: ${d}`);return}let c=sn(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(f=>Nr(p[f],o)).join(o);r.push(`${d}${h}`);}
330
330
  return}r.push(`${s}${a}[${e.length}]:`);let l=n+1,u=i.repeat(l);for(let d of e)if($i(d))r.push(`${u}- ${Nr(d,o)}`);else {let p=[];ji(null,d,0,p,o,i);let[h,...f]=p;r.push(`${u}- ${h??""}`);for(let m of f)
331
331
  r.push(`${u}${i}${m}`);}}function sn(t){if(t.length===0)return null;let e=t[0];if(!Ni(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(!Ni(
332
- o))return null;let i=Object.keys(o);if(i.slice().sort().join("\0")!==r)return null;for(let s of i)if(!$i(o[s]))return null}return n}function cm(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:Dc(t)}function Nr(t,e){
332
+ o))return null;let i=Object.keys(o);if(i.slice().sort().join("\0")!==r)return null;for(let s of i)if(!$i(o[s]))return null}return n}function um(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:Dc(t)}function Nr(t,e){
333
333
  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(`
334
334
  `)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?Dc(n):n}function Dc(t){return `"${t.replace(/"/g,'""')}"`}function $i(t){return t===null||typeof t=="string"||typeof t==
335
- "number"||typeof t=="boolean"}function Ni(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var lm="Data is the compact encoder: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; ea\
336
- 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 um(t={}){return {format:"compact-rows",supports(){return true},
337
- encode(e){return sm(e,t)},instruction(){return lm},decode(e){return Pc(e,t)}}}var Ac=um();var Lc={format:"csv",supports(t){return Array.isArray(t)&&sn(t)!==null},encode(t){let e=t,n=sn(e),r=n.map(Oc).join(","),o=e.map(i=>n.map(s=>Oc(i[s])).join(","));return [r,...o].join(`
335
+ "number"||typeof t=="boolean"}function Ni(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var dm="Data is the compact encoder: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; ea\
336
+ 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 pm(t={}){return {format:"compact-rows",supports(){return true},
337
+ encode(e){return cm(e,t)},instruction(){return dm},decode(e){return Pc(e,t)}}}var Ac=pm();var Lc={format:"csv",supports(t){return Array.isArray(t)&&sn(t)!==null},encode(t){let e=t,n=sn(e),r=n.map(Oc).join(","),o=e.map(i=>n.map(s=>Oc(i[s])).join(","));return [r,...o].join(`
338
338
  `)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function Oc(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,
339
339
  '""')}"`:e}var jr=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[Rc,Ac,Lc],this.minSavingsTokens=e.minimumSavingsTokens??
340
340
  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 l of this.serializers){if(!l.supports(
341
- e))continue;let u=l.encode(e);if(l.format!=="json-compact"&&!dm(l,u,e))continue;let d=l.instruction(e),p=this.tokenizer.count(u,r),h=d?this.tokenizer.count(d,r):0,f=this.qualityPenalty(n.model??"",l.format);
341
+ e))continue;let u=l.encode(e);if(l.format!=="json-compact"&&!fm(l,u,e))continue;let d=l.instruction(e),p=this.tokenizer.count(u,r),h=d?this.tokenizer.count(d,r):0,f=this.qualityPenalty(n.model??"",l.format);
342
342
  o.push({format:l.format,encoded:u,instruction:d,payloadTokens:p,instructionTokens:h,penalty:f,total:p+h+f});}let i=o.find(l=>l.format==="json-compact"),s={};for(let l of o)s[l.format]=l.total;if(!i){let l=o[0];
343
343
  return l?Mc(l,s,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:s,instructionOverheadTokens:0,reason:"no serializer supported payload; defa\
344
344
  ulted to JSON"}}let a=i,c="json baseline (no challenger cleared thresholds)";for(let l of o){if(l.format==="json-compact")continue;let u=i.total-l.total,d=i.total===0?0:u/i.total;u>=this.minSavingsTokens&&
345
- d>=this.minSavingsRatio&&l.total<a.total&&(a=l,c=`${l.format} saved ${u} tokens (${(d*100).toFixed(1)}%) vs json`);}return Mc(a,s,c)}};function dm(t,e,n){if(!t.decode)return false;try{return Bi(t.decode(e),
345
+ d>=this.minSavingsRatio&&l.total<a.total&&(a=l,c=`${l.format} saved ${u} tokens (${(d*100).toFixed(1)}%) vs json`);}return Mc(a,s,c)}};function fm(t,e,n){if(!t.decode)return false;try{return Bi(t.decode(e),
346
346
  n)}catch{return false}}function Bi(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.
347
347
  length)return false;for(let s=0;s<t.length;s++)if(!Bi(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.
348
- call(e,s)||!Bi(t[s],e[s]))return false;return true}function Mc(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function be(t,e,n="$"){let r=[];return zi(t,e,n,r),{valid:r.length===0,errors:r}}function pm(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
349
- string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function zi(t,e,n,r){switch(e.enum&&!e.enum.some(i=>bm(i,t))&&r.push({path:n,message:"value not in enum"}),
350
- e.type??pm(t)){case "object":fm(t,e,n,r);break;case "array":mm(t,e,n,r);break;case "string":hm(t,e,n,r);break;case "number":case "integer":gm(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,
351
- message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function fm(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,
348
+ call(e,s)||!Bi(t[s],e[s]))return false;return true}function Mc(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function be(t,e,n="$"){let r=[];return zi(t,e,n,r),{valid:r.length===0,errors:r}}function mm(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
349
+ string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function zi(t,e,n,r){switch(e.enum&&!e.enum.some(i=>ym(i,t))&&r.push({path:n,message:"value not in enum"}),
350
+ e.type??mm(t)){case "object":hm(t,e,n,r);break;case "array":gm(t,e,n,r);break;case "string":bm(t,e,n,r);break;case "number":case "integer":vm(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,
351
+ message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function hm(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,
352
352
  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(
353
353
  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&&
354
- zi(o[i],s,`${n}.${i}`,r);}function mm(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\
355
- 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)=>zi(o,e.items,`${n}[${i}]`,r));}function hm(t,e,n,r){if(typeof t!=
354
+ zi(o[i],s,`${n}.${i}`,r);}function gm(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\
355
+ 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)=>zi(o,e.items,`${n}[${i}]`,r));}function bm(t,e,n,r){if(typeof t!=
356
356
  "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.
357
357
  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\
358
- sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function gm(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}
358
+ sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function vm(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}
359
359
  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.
360
- minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function bm(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var Br=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 Fi(
360
+ minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function ym(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var Br=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 Fi(
361
361
  e,n,r),r}};function Fi(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??{}))Fi(o,`${e}\
362
362
  .${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&Fi(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: s\
363
363
  tring should set maxLength or use an enum`);}function zr(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\
364
- ate + repair"}}function Nx(t=()=>true){return {id:"provider-native",supports:t}}function zn(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;
364
+ ate + repair"}}function Fx(t=()=>true){return {id:"provider-native",supports:t}}function zn(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;
365
365
  return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function $c(t){return {async compress(e){let n=e.protectedSpans??[],r=e.text,o=[];n.forEach((c,l)=>{
366
366
  let u=`\0PROTECT_${l}\0`;o.push({token:u,span:c}),r=r.split(c.text).join(u);});let i=await t.compress({text:r,...e.targetRatio!=null?{targetRatio:e.targetRatio}:{}}),s=i.compressed,a=true;for(let{token:c,
367
367
  span:l}of o){if(!s.includes(c)){a=false;break}s=s.split(c).join(l.text);}return a?{...i,compressed:s,protectedSpans:n.length,fidelityPassed:true}:{compressed:e.text,originalTokens:i.originalTokens,compressedTokens:i.
368
- originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var Vx={async compress(t){return {compressed:t.text,originalTokens:0,
368
+ originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var Kx={async compress(t){return {compressed:t.text,originalTokens:0,
369
369
  compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function Nc(t,e){let n=s=>s.toLowerCase().replace(/[.,;:!¡?¿()[\]{}"«»…]/g,
370
370
  " ").replace(/\s+/g," ").trim(),o=n((s=>{let a=new Set,c=[];for(let l of s.split(`
371
371
  `)){let u=l.trim();u&&a.has(u)||(u&&a.add(u),c.push(l));}return c.join(`
372
- `)})(t)),i=n(e);return !(!jn(_t(o),_t(i))||At(Dt(o))!==At(Dt(i)))}var qi=["ansi","carriage-return","json","repeated-lines"],vm=256,ym=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|[ -/]+[0-~]|[@-_])/g;function km(t){if(!t.includes("\x1B"))return null;
373
- let e=t.replace(ym,"");return e.length<t.length?e:null}function xm(t){let e="";for(let n of t.split("\r"))e=n+e.slice(n.length);return e}function wm(t){if(!t.includes("\r")||t.includes(`\r
372
+ `)})(t)),i=n(e);return !(!jn(It(o),It(i))||At(Dt(o))!==At(Dt(i)))}var qi=["ansi","carriage-return","json","repeated-lines"],km=256,xm=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|[ -/]+[0-~]|[@-_])/g;function wm(t){if(!t.includes("\x1B"))return null;
373
+ let e=t.replace(xm,"");return e.length<t.length?e:null}function Sm(t){let e="";for(let n of t.split("\r"))e=n+e.slice(n.length);return e}function Em(t){if(!t.includes("\r")||t.includes(`\r
374
374
  `))return null;let e=t.split(`
375
- `).map(n=>n.includes("\r")?xm(n):n).join(`
376
- `);return e.length<t.length?e:null}var Sm=t=>t===32||t===9||t===10||t===13;function Em(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=[],
377
- i=0,s=false;for(let c=0;c<e.length;c++){let l=e.charCodeAt(c);if(s){l===92?c+=1:l===34&&(s=false);continue}if(l===34){s=true;continue}Sm(l)&&(c>i&&o.push(e.slice(i,c)),i=c+1);}i<e.length&&o.push(e.slice(i));let a=o.
378
- 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 zc=/^\[previous line repeated (\d+) more times\]$/,Cm=t=>`\
379
- [previous line repeated ${t} more times]`,jc=3;function Tm(t){let e=[];for(let n of t.split(`
375
+ `).map(n=>n.includes("\r")?Sm(n):n).join(`
376
+ `);return e.length<t.length?e:null}var Cm=t=>t===32||t===9||t===10||t===13;function Tm(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=[],
377
+ i=0,s=false;for(let c=0;c<e.length;c++){let l=e.charCodeAt(c);if(s){l===92?c+=1:l===34&&(s=false);continue}if(l===34){s=true;continue}Cm(l)&&(c>i&&o.push(e.slice(i,c)),i=c+1);}i<e.length&&o.push(e.slice(i));let a=o.
378
+ 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 zc=/^\[previous line repeated (\d+) more times\]$/,Rm=t=>`\
379
+ [previous line repeated ${t} more times]`,jc=3;function Pm(t){let e=[];for(let n of t.split(`
380
380
  `)){let r=zc.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(`
381
- `)}function Rm(t){let e=t.split(`
382
- `);if(e.length<jc||e.some(i=>zc.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,l=Cm(c);if(c+1>=jc&&c*(s.length+1)>l.length+1)n.push(
381
+ `)}function _m(t){let e=t.split(`
382
+ `);if(e.length<jc||e.some(i=>zc.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,l=Rm(c);if(c+1>=jc&&c*(s.length+1)>l.length+1)n.push(
383
383
  s,l),r+=c;else for(let u=i;u<a;u++)n.push(e[u]);i=a;}if(r===0)return null;let o=n.join(`
384
- `);return Tm(o)!==t?null:o.length<t.length?o:null}var Pm={ansi:km,"carriage-return":wm,json:Em,"repeated-lines":Rm};function Fc(t,e={}){let n=new Set(e.transforms??qi),r=Math.max(1,e.minSavedChars??256),
385
- o=t,i=[];for(let a of qi){if(!n.has(a))continue;let c=Pm[a](o);c!=null&&c.length<o.length&&(o=c,i.push(a));}let s=t.length-o.length;return i.length===0?Bc(t,"nothing to compact"):s<r?Bc(t,`compaction w\
384
+ `);return Pm(o)!==t?null:o.length<t.length?o:null}var Im={ansi:wm,"carriage-return":Em,json:Tm,"repeated-lines":_m};function Fc(t,e={}){let n=new Set(e.transforms??qi),r=Math.max(1,e.minSavedChars??256),
385
+ o=t,i=[];for(let a of qi){if(!n.has(a))continue;let c=Im[a](o);c!=null&&c.length<o.length&&(o=c,i.push(a));}let s=t.length-o.length;return i.length===0?Bc(t,"nothing to compact"):s<r?Bc(t,`compaction w\
386
386
  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 Bc(t,e){return {text:t,changed:false,
387
- applied:[],originalChars:t.length,compactChars:t.length,reason:e}}var Im=new Set(["path","paths","file","files","filepath","filename","absolutepath","relativepath","targetfile","notebookpath"]);function _m(t){
388
- 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=>Im.has(n.toLowerCase().replace(/[_-]/g,"")))}function qc(t,e={}){let n=new Map,
387
+ applied:[],originalChars:t.length,compactChars:t.length,reason:e}}var Dm=new Set(["path","paths","file","files","filepath","filename","absolutepath","relativepath","targetfile","notebookpath"]);function Am(t){
388
+ 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=>Dm.has(n.toLowerCase().replace(/[_-]/g,"")))}function qc(t,e={}){let n=new Map,
389
389
  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,
390
- exceptuados:0};return t.forEach((s,a)=>{if(s.role!=="tool")return;let c=s.toolCallId?n.get(s.toolCallId):void 0,l=c?.nombre??s.name;if(l&&o.has(l)){i.exceptuados+=1;return}if(!e.compactFileViews&&_m(c?.
390
+ exceptuados:0};return t.forEach((s,a)=>{if(s.role!=="tool")return;let c=s.toolCallId?n.get(s.toolCallId):void 0,l=c?.nombre??s.name;if(l&&o.has(l)){i.exceptuados+=1;return}if(!e.compactFileViews&&Am(c?.
391
391
  argumentos)){i.vistasDeFichero+=1;return}let u=Fc(s.content,e);u.changed&&i.compactados.push({indice:a,texto:u.text,aplicadas:u.applied,enLaCola:a>r});}),i}var Uc=new WeakSet;function Vc(t){Uc.add(t);}function Ui(t){return typeof t=="object"&&t!==null&&Uc.has(t)}var Vi=class{id="mock";options;constructor(e={}){this.options=e,Vc(this);}async generate(e,n){let r=e.messages.map(c=>c.content).join(`
392
392
  `),o=en.count(r);if(e.tools&&e.tools.length>0){let c=JSON.stringify(e.tools.map(l=>({name:l.id,description:l.description,parameters:l.parameters??{}})));o+=en.count(c);}let i,s=false;if(e.schema){let c=this.
393
393
  options.data??Fr(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,en.count(i));return {text:i,usage:{
394
394
  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.
395
395
  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 Fr(t){if(t.enum&&t.enum.length>0)return t.
396
396
  enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?Fr(r):null;}for(let[n,r]of Object.entries(t.properties??{}))n in e||(e[n]=Fr(r));return e}case "\
397
- array":return t.items?[Fr(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 Qx(t){return new Vi(
397
+ array":return t.items?[Fr(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 rw(t){return new Vi(
398
398
  t)}function Hi(t){let e=t.toLowerCase(),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e}function Hc(t){let e=/^gpt-(\d+)(?:\.(\d+))?(?![\d.])/.exec(t);if(!e)return false;let n=Number(e[1]),r=e[2]===void 0?0:
399
399
  Number(e[2]);return n>5||n===5&&r>=6}function Ne(t){let e=Hi(t);return e.startsWith("gpt-")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?Hc(e)?1.25:1:e.startsWith("gemini")?1:1.25}function Fn(t){
400
- return Hc(Hi(t))?1.25:1}function qn(t){let e=t.toLowerCase();return e.startsWith("claude")||e.startsWith("anthropic/")||Hi(e).startsWith("claude")?2:Ne(t)}var Dm="https://developers.openai.com/api/docs/pricing",Am="https://ai.google.dev/gemini-api/docs/pricing",Wi="2026-09-27",z=t=>({...t,fuente:Dm,consultado:Wi}),je=t=>({...t,fuente:Am,consultado:Wi}),
401
- Om="https://platform.claude.com/docs/en/about-claude/pricing",oe=t=>({...t,fuente:Om,consultado:Wi}),Lm={openai:{flex:{"gpt-5":z({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
400
+ return Hc(Hi(t))?1.25:1}function qn(t){let e=t.toLowerCase();return e.startsWith("claude")||e.startsWith("anthropic/")||Hi(e).startsWith("claude")?2:Ne(t)}var Om="https://developers.openai.com/api/docs/pricing",Lm="https://ai.google.dev/gemini-api/docs/pricing",Wi="2026-09-27",z=t=>({...t,fuente:Om,consultado:Wi}),je=t=>({...t,fuente:Lm,consultado:Wi}),
401
+ Mm="https://platform.claude.com/docs/en/about-claude/pricing",oe=t=>({...t,fuente:Mm,consultado:Wi}),$m={openai:{flex:{"gpt-5":z({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
402
402
  ni":z({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":z({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":z({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),
403
403
  "gpt-5.4":z({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),
404
404
  "gpt-5.4-mini":z({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),"gpt-5.4-nano":z({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":z({inputPer1k:.0025,cachedInputPer1k:25e-5,
@@ -443,8 +443,8 @@ sh":je({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-
443
443
  {inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":je({inputPer1k:125e-6,outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-pre\
444
444
  view":je({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}};function lt(t){let e=t.lastIndexOf("/");return e>=0?t.slice(e+1):t}function Ot(t){let e=t.toLowerCase(),n=e.indexOf("/"),r=n>0?e.
445
445
  slice(0,n):"",o=lt(e);return r==="openai"||r==="azure-openai"?"openai":r==="google"||r==="google-vertex"?"google":r==="anthropic"?"anthropic":/^(gpt-|o[1-9](-|$))/.test(o)?"openai":o.startsWith("gemin\
446
- i")?"google":o.startsWith("claude-")?"anthropic":null}function Mm(t){return Date.parse(`${t}T23:59:59.999Z`)}function Un(t,e,n,r=Date.now()){if(st(n)===void 0)return;let o=Qt(n);if(o===void 0)return;let i=Lm[t]?.[e],
447
- s=i?i[o]:void 0;if(s&&!(s.vigenteHasta&&r>Mm(s.vigenteHasta)))return s}function qr(t){let e=st(t);if(e)return {...e,cacheWritePer1k:e.inputPer1k*Ne(lt(t))}}var Wc={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},Gc=Math.min(...Object.values(Wc).filter(t=>t<1)),We="flex";function Gi(t){if(t==null||t==="")return null;let e=Wc[t];return e==
446
+ i")?"google":o.startsWith("claude-")?"anthropic":null}function Nm(t){return Date.parse(`${t}T23:59:59.999Z`)}function Un(t,e,n,r=Date.now()){if(st(n)===void 0)return;let o=Qt(n);if(o===void 0)return;let i=$m[t]?.[e],
447
+ s=i?i[o]:void 0;if(s&&!(s.vigenteHasta&&r>Nm(s.vigenteHasta)))return s}function qr(t){let e=st(t);if(e)return {...e,cacheWritePer1k:e.inputPer1k*Ne(lt(t))}}var Wc={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},Gc=Math.min(...Object.values(Wc).filter(t=>t<1)),We="flex";function Gi(t){if(t==null||t==="")return null;let e=Wc[t];return e==
448
448
  null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}var Ur=1e10;function Ki(t){let e=Math.floor(t*Ur)/Ur;return e>t&&(e=(Math.floor(t*Ur)-1)/Ur),e<=0?0:e}var Vr=t=>typeof t==
449
449
  "number"&&Number.isFinite(t);function Hr(t){let e=Gi(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:"\
450
450
  standard-rate-tier"};let n=t.uso;if(n.complete===false||!Vr(n.inputTokens)||!Vr(n.outputTokens)||n.cachedInputTokens!=null&&!Vr(n.cachedInputTokens)||n.cacheWriteInputTokens!=null&&!Vr(n.cacheWriteInputTokens))
@@ -463,25 +463,25 @@ t the difference between the two published rate cards":"")),b){let D=[...c?[]:["
463
463
  its prompt cache, so those tokens are priced at the smallest per-token difference they could have had`);}E.size>0&&$.push(`the provider publishes no ${[...E].join(" or ")} price for this tier, so thos\
464
464
  e tokens add nothing`);let O=$.length===0;return {ok:true,importe:P,basis:O?"measured":"estimated",costeEstandar:T,costeAplicado:R,factorEfectivo:R/T,motivoBasis:O?`the provider's own usage for this call\
465
465
  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\
466
- led at the batch rate card)":""):`estimated: ${$.join("; ")}`,consultado:i.consultado}}function Kc(t,e,n){let r=e??Ot(t);return r!==null&&Un(r,"batch",t,n)!==void 0}var $m="slower and variable: OpenAI\
466
+ led at the batch rate card)":""):`estimated: ${$.join("; ")}`,consultado:i.consultado}}function Kc(t,e,n){let r=e??Ot(t);return r!==null&&Un(r,"batch",t,n)!==void 0}var jm="slower and variable: OpenAI\
467
467
  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\
468
- short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",Nm='slower and variable: Google targets minutes for the Flex tier ("Minutes (1\u201315 min target)\
468
+ short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",Bm='slower and variable: Google targets minutes for the Flex tier ("Minutes (1\u201315 min target)\
469
469
  ", 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\
470
- he server side. Do not put a deferrable request on a user-facing path.',jm="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\
470
+ he server side. Do not put a deferrable request on a user-facing path.',zm="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\
471
471
  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\
472
- n a user-facing path.",Bm="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.",Jc="this provider\
472
+ n a user-facing path.",Fm="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.",Jc="this provider\
473
473
  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 \
474
- request/response call (with the built-in Anthropic and OpenAI providers, layer.batches.submit() sends such requests there)";function Yc(t,e=null){return t==null||t===""?Bm:t===We?e==="openai"?$m:e==="\
475
- google"?Nm:jm:`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\
474
+ request/response call (with the built-in Anthropic and OpenAI providers, layer.batches.submit() sends such requests there)";function Yc(t,e=null){return t==null||t===""?Fm:t===We?e==="openai"?jm:e==="\
475
+ google"?Bm:zm:`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\
476
476
  st on a user-facing path.`}var Zc=1024;function Lt(t,e){return e==="openai"&&Ot(lt(t))==="openai"&&Ne(lt(t))>1}function Ji(t){let e=st(t);if(!e||!(e.inputPer1k>0))return null;let n=(e.cachedInputPer1k??e.inputPer1k)/e.inputPer1k;
477
- return {minimumCacheTokens:Zc,cacheReadMultiplier:n,cacheWriteMultiplier:Ne(lt(t))}}function Xc(t){let e=t.consultado??_n,n=Math.max(0,t.uso.inputTokens),r=Math.min(Math.max(0,t.uso.cachedInputTokens??
477
+ return {minimumCacheTokens:Zc,cacheReadMultiplier:n,cacheWriteMultiplier:Ne(lt(t))}}function Xc(t){let e=t.consultado??In,n=Math.max(0,t.uso.inputTokens),r=Math.min(Math.max(0,t.uso.cachedInputTokens??
478
478
  0),n),o=Math.min(Math.max(0,t.uso.cacheWriteInputTokens??0),n-r),i=n-r-o;if(n<Zc||i<=0)return {importe:0,costeEstandar:0,costeAplicado:0,tokensOrdinarios:Math.max(0,i),consultado:e};let s=i/1e3*t.fila.
479
- cacheWritePer1k,a=i/1e3*t.fila.inputPer1k;return {importe:Ki(s-a),costeEstandar:s,costeAplicado:a,tokensOrdinarios:i,consultado:e}}var Yi=new Set;function Ee(t,e){Yi.has(t)||(Yi.add(t),console.warn(e));}function Qc(t){return Yi.has(t)}var zm="BVSALA_SILENCE_DEPRECATIONS";function el(){let t=typeof process<"u"?process.env?.[zm]?.trim():void 0;return t!==void 0&&t!==""&&t!=="0"}var Fm={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function ut(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.protocol!==
480
- "https:"||e.port!==""?null:Fm[e.hostname.toLowerCase()]??null}catch{return null}}function an(t){return ut(t)!==null?"oficial":"no-oficial"}var tl=Symbol.for("@bivelio/savings-layer:provider-origin");function Mt(t){return {esquemaEnFormatoNativo:false,esquemaEstricto:false,esquemaPorPrompt:false,piezasDelAdaptador:t}}var qm=2;function cn(t){return qm*(t??[]).filter(e=>e.parameters==null).length}var Wr=new WeakMap;
479
+ cacheWritePer1k,a=i/1e3*t.fila.inputPer1k;return {importe:Ki(s-a),costeEstandar:s,costeAplicado:a,tokensOrdinarios:i,consultado:e}}var Yi=new Set;function Ee(t,e){Yi.has(t)||(Yi.add(t),console.warn(e));}function Qc(t){return Yi.has(t)}var qm="BVSALA_SILENCE_DEPRECATIONS";function el(){let t=typeof process<"u"?process.env?.[qm]?.trim():void 0;return t!==void 0&&t!==""&&t!=="0"}var Um={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function ut(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.protocol!==
480
+ "https:"||e.port!==""?null:Um[e.hostname.toLowerCase()]??null}catch{return null}}function an(t){return ut(t)!==null?"oficial":"no-oficial"}var tl=Symbol.for("@bivelio/savings-layer:provider-origin");function Mt(t){return {esquemaEnFormatoNativo:false,esquemaEstricto:false,esquemaPorPrompt:false,piezasDelAdaptador:t}}var Vm=2;function cn(t){return Vm*(t??[]).filter(e=>e.parameters==null).length}var Wr=new WeakMap;
481
481
  function dt(t,e){return Wr.set(t,e),t}function Gr(t){return typeof t=="object"&&t!==null?Wr.get(t):void 0}var nl=new WeakMap;function Kr(t,e){nl.set(t,e);}function $t(t){return typeof t=="object"&&t!==
482
482
  null?nl.get(t):void 0}var rl=new WeakMap;function ln(t,e){rl.set(t,e);}function ol(t){if(typeof t!="object"||t===null)return;let e=rl.get(t);if(e!==void 0)return e;try{let n=t[tl];if(typeof n!="functio\
483
483
  n")return;let r=n.call(t);return r==="oficial"||r==="no-oficial"?r:void 0}catch{return}}function il(t,e){let n=Wr.get(t);return n&&Wr.set(e,n),e}var sl=new WeakMap;function al(t,e){sl.set(t,e);}function Jr(t){
484
- return typeof t=="object"&&t!==null?sl.get(t):void 0}var cl=new WeakSet;function ll(t){typeof t=="object"&&t!==null&&cl.add(t);}function Um(t){return cl.has(t)}function Ce(t,e,n){Um(t)||Ee(e,n);}var ul=new WeakMap;function Yr(t,e){ul.set(t,e);}function dl(t){return typeof t=="object"&&t!==null?ul.get(t):void 0}function Zr(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.
484
+ return typeof t=="object"&&t!==null?sl.get(t):void 0}var cl=new WeakSet;function ll(t){typeof t=="object"&&t!==null&&cl.add(t);}function Hm(t){return cl.has(t)}function Ce(t,e,n){Hm(t)||Ee(e,n);}var ul=new WeakMap;function Yr(t,e){ul.set(t,e);}function dl(t){return typeof t=="object"&&t!==null?ul.get(t):void 0}function Zr(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.
485
485
  hash="",e.toString().replace(/\/+$/,"")}catch{return t.replace(/\/+$/,"")}}function Xr(t){if(!t.startsWith("/")||t.startsWith("//")||/^\/*[a-z][a-z0-9+.-]*:/i.test(t))throw new Error(`[bvsala] interna\
486
486
  l: a batch request path must be relative to the provider base (got "${t}")`);return t}var pl=/^content_filter(?:\s*:\s*(.*?))?\s*$/;function fl(t){return typeof t=="string"&&pl.test(t)}function Zi(t){if(typeof t!="string")return {};let e=pl.exec(t);if(e===null)return {parada:t};let n=e[1];
487
487
  return typeof n=="string"&&n!==""?{parada:"content_filter",detalle:n}:{parada:"content_filter"}}function Xi(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function ml(t){if(!t)return 0;let{prompt_tokens:e,completion_tokens:n,total_tokens:r}=t;return !Xi(e)||!Xi(n)||!Xi(r)?0:Math.max(0,r-
@@ -493,25 +493,25 @@ crPendiente=true),o++,i=o;}return this.resto+=r.slice(i),n}linea(e,n){if(e==="")
493
493
  i=e.slice(r+1),i.charCodeAt(0)===32&&(i=i.slice(1))),o){case "data":this.datos+=i+`
494
494
  `;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":
495
495
  this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};async function*un(t){let e=new Qi;if(typeof t=="string"){yield*e.push(t),yield*e.
496
- 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 Vm(t,e){return e==="max_tokens"?/\bmax_tokens\b/i.test(t)&&/max_completion_tokens/i.test(t)&&/unsupported|not supported|unrecognized|unknown parameter|use 'max_completion_tokens'/i.test(t):/max_completion_tokens/i.
496
+ 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 Wm(t,e){return e==="max_tokens"?/\bmax_tokens\b/i.test(t)&&/max_completion_tokens/i.test(t)&&/unsupported|not supported|unrecognized|unknown parameter|use 'max_completion_tokens'/i.test(t):/max_completion_tokens/i.
497
497
  test(t)&&/unsupported|not supported|unrecognized|unknown (parameter|field|argument)|extra (inputs|fields) (are )?not permitted|not permitted/i.test(t)}var to=["prompt_cache_key","service_tier","seed",
498
- "reasoning_effort"];function Hm(t,e){if(!/unknown name|cannot find field|unknown (parameter|field|argument)|unrecognized|extra (inputs|fields) (are )?not permitted|not permitted|not supported|unsupported/i.
498
+ "reasoning_effort"];function Gm(t,e){if(!/unknown name|cannot find field|unknown (parameter|field|argument)|unrecognized|extra (inputs|fields) (are )?not permitted|not permitted|not supported|unsupported/i.
499
499
  test(t))return null;for(let n of to)if(e.has(n)&&new RegExp(`\\b${n}\\b`).test(t))return n;return null}function Be(t){if(t==null||typeof t!="object")return true;let e=t,n=e.properties;if(n&&typeof n=="ob\
500
500
  ject"){if(e.additionalProperties!==false)return false;let o=Object.keys(n),i=Array.isArray(e.required)?e.required.map(String):[];if(o.some(s=>!i.includes(s)))return false;for(let s of Object.values(n))if(!Be(s))
501
501
  return false}if(e.items!==void 0&&!Be(e.items))return false;for(let o of ["anyOf","oneOf","allOf"]){let i=e[o];if(Array.isArray(i)&&i.some(s=>!Be(s)))return false}let r=e.$defs??e.definitions;return !(r&&typeof r==
502
- "object"&&Object.values(r).some(o=>!Be(o)))}function Wm(t){return !/response_format/i.test(t)||/invalid schema/i.test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.
503
- test(t)}function Gm(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:
504
- `+JSON.stringify(t)}var Km=/(^|\.)api\.openai\.com$|\.openai\.azure\.com$/i;function es(t,e,n){return e??Ym(n)?t.replace(/^[^/]+\//,""):t}function Jm(t){let e=ut(t);return e==="openai"||e==="google"?e:
502
+ "object"&&Object.values(r).some(o=>!Be(o)))}function Km(t){return !/response_format/i.test(t)||/invalid schema/i.test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.
503
+ test(t)}function Jm(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:
504
+ `+JSON.stringify(t)}var Ym=/(^|\.)api\.openai\.com$|\.openai\.azure\.com$/i;function es(t,e,n){return e??Xm(n)?t.replace(/^[^/]+\//,""):t}function Zm(t){let e=ut(t);return e==="openai"||e==="google"?e:
505
505
  null}var hl="x-gemini-service-tier";function gl(t,e){try{let n=t.headers?.get?.(e);return typeof n=="string"&&n.trim()!==""?n.trim():void 0}catch{return}}function ts(t,e,n){if(e.explicitCacheWrites!==
506
506
  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\
507
- ser"||o.role==="tool")&&typeof o.content=="string"&&o.content!==""?{puntos:1,indice:r-1}:{puntos:0,indice:-1}}function Ym(t){if(ut(t)==="google")return true;try{return Km.test(new URL(t).hostname)}catch{
507
+ ser"||o.role==="tool")&&typeof o.content=="string"&&o.content!==""?{puntos:1,indice:r-1}:{puntos:0,indice:-1}}function Xm(t){if(ut(t)==="google")return true;try{return Ym.test(new URL(t).hostname)}catch{
508
508
  return false}}var bl=class{id;opts;fetchImpl;sinResponseFormat=new Set;streamOptionsRejected=false;campoDeTopeAprendido=new Map;camposRechazados=new Map;origen;constructor(e){this.opts=e,this.id=`openai-comp\
509
- atible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch,this.origen=Jm(e.baseUrl),Kr(this,this.origen),ln(this,an(e.baseUrl));let n=(o,i)=>o.schema!=null&&!this.sinResponseFormat.has(i),r=o=>es(o,this.
509
+ atible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch,this.origen=Zm(e.baseUrl),Kr(this,this.origen),ln(this,an(e.baseUrl));let n=(o,i)=>o.schema!=null&&!this.sinResponseFormat.has(i),r=o=>es(o,this.
510
510
  opts.stripProviderPrefix,this.opts.baseUrl);Yr(this,{protocolo:"openai",origen:this.origen,endpoint:Zr(e.baseUrl),cuerpo:o=>{let i=r(o.model);return this.construirCuerpo(i,o,n(o,i))},leer:(o,i)=>{let s=r(
511
511
  i.model);return this.leerJson(o,void 0,i,n(i,s),s,false)},solicitar:(o,i)=>this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}${Xr(o)}`,{method:i.method,headers:{...i.json!==void 0?{"content-type":"ap\
512
512
  plication/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.form}:{},...i.signal?{signal:i.
513
513
  signal}:{}})});}async generate(e,n){let r=es(e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n?.signal,i=e.schema!=null&&!this.sinResponseFormat.has(r),s=await this.enviar(r,e,i,void 0,o);for(let a=0;a<
514
- 2+to.length&&!s.ok&&!(s.status!==400&&s.status!==422);a++){let c=await eo(s);if(!this.corregirCampoOpcional(r,e,s.status,c,i)){if(s.status===400&&i&&Wm(c))this.sinResponseFormat.add(r),Ce(this,`sin-re\
514
+ 2+to.length&&!s.ok&&!(s.status!==400&&s.status!==422);a++){let c=await eo(s);if(!this.corregirCampoOpcional(r,e,s.status,c,i)){if(s.status===400&&i&&Km(c))this.sinResponseFormat.add(r),Ce(this,`sin-re\
515
515
  sponse-format:${r}`,`[bvsala] 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\
516
516
  the following requests go straight 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.backe\
517
517
  nd: "none"\`. To recover the native guarantee, use a model with structured outputs (gpt-4o or later).`),i=false;else if(!this.corregirCampoDeTope(r,e,s.status,c))throw new Error(`provider ${s.status}: ${c}`)}
@@ -535,11 +535,11 @@ C=yl(f),A={inputTokens:f?.prompt_tokens??0,outputTokens:E.salida,...f?.prompt_to
535
535
  extra}:{}})).filter(w=>w.name!==""),R=m?"cuerpo":void 0;!m&&this.origen==="google"&&(m=gl(c,hl),m&&(R="cabecera"));let M=ts(r,e,this.origen);yield {type:"done",response:dt({text:d,...T.length>0?{toolCalls:T}:
536
536
  {},finishReason:y.parada??h,...y.detalle!==void 0?{finishReasonDetail:y.detalle}:{},...b!==""?{refusal:b}:{},...m?{servedServiceTier:m}:{},usage:A,structuredNatively:false,raw:f??null},{...Mt(cn(e.tools)),
537
537
  origen:this.origen,...R?{tierLeidoDe:R}:{},...M?{cacheExplicita:{puntos:M.puntos}}:{}})};}campoDeTope(e){return this.opts.maxTokensParam??this.campoDeTopeAprendido.get(e)??(this.origen==="openai"?"max_\
538
- completion_tokens":"max_tokens")}corregirCampoDeTope(e,n,r,o){if(this.opts.maxTokensParam!==void 0||n.maxOutputTokens==null||this.campoDeTopeAprendido.has(e))return false;let i=this.campoDeTope(e);if(!Vm(
538
+ completion_tokens":"max_tokens")}corregirCampoDeTope(e,n,r,o){if(this.opts.maxTokensParam!==void 0||n.maxOutputTokens==null||this.campoDeTopeAprendido.has(e))return false;let i=this.campoDeTope(e);if(!Wm(
539
539
  o,i))return false;let s=i==="max_tokens"?"max_completion_tokens":"max_tokens";return this.campoDeTopeAprendido.set(e,s),Ce(this,`campo-de-tope:${this.opts.baseUrl}:${e}`,`[bvsala] This endpoint rejects \`${i}\
540
540
  \` for model "${e}" with a ${r}, so the output cap is sent as \`${s}\` instead (the rejected request was not billed; the model is noted and the following requests go straight there). To choose the fiel\
541
541
  d yourself, set \`maxTokensParam\` on OpenAICompatibleProvider.`),true}corregirCampoOpcional(e,n,r,o,i,s){let a=this.construirCuerpo(e,n,i,s===void 0?void 0:{includeUsage:s}),c=new Set(to.filter(d=>d in
542
- a)),l=Hm(o,c);if(l===null||l==="reasoning_effort"&&this.origen==="openai")return false;let u=this.camposRechazados.get(e)??new Set;return u.add(l),this.camposRechazados.set(e,u),Ce(this,`campo-opcional:${this.
542
+ a)),l=Gm(o,c);if(l===null||l==="reasoning_effort"&&this.origen==="openai")return false;let u=this.camposRechazados.get(e)??new Set;return u.add(l),this.camposRechazados.set(e,u),Ce(this,`campo-opcional:${this.
543
543
  opts.baseUrl}:${e}:${l}`,`[bvsala] This endpoint rejects \`${l}\` for model "${e}" with a ${r}, so it is no longer sent (the rejected request was not billed; the model is noted and the following reque\
544
544
  sts go without it).`+(l==="service_tier"?" The request is served on the endpoint's default tier, and no tier discount is credited.":l==="prompt_cache_key"?" The prefix cache keeps working without the \
545
545
  routing hint; only its hit rate may drop.":l==="reasoning_effort"?" The model reasons at the endpoint's default effort.":"")),true}campoAdmitido(e,n){return this.camposRechazados.get(e)?.has(n)!==true}async enviar(e,n,r,o,i){
@@ -548,7 +548,7 @@ let s=this.construirCuerpo(e,n,r,o);return await this.fetchImpl(`${this.opts.bas
548
548
  "tool"?{role:"tool",content:c.content,tool_call_id:c.toolCallId??c.metadata?.tool_call_id,...c.name?{name:c.name}:{}}:c.role==="assistant"&&c.toolCalls&&c.toolCalls.length>0?{role:"assistant",content:c.
549
549
  content||null,tool_calls:c.toolCalls.map((l,u)=>({id:l.id??`call_${u}`,type:"function",function:{name:l.name,arguments:l.arguments},...l.extraContent!==void 0&&this.origen!=="openai"?{extra_content:l.
550
550
  extraContent}:{}}))}:{role:c.role,content:c.content}),s=ts(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"}}];}n.schema&&
551
- !r&&i.push({role:"system",content:Gm(n.schema)});let a={model:e,messages:i};if(n.maxOutputTokens!=null&&(a[this.campoDeTope(e)]=n.maxOutputTokens),n.temperature!=null&&(a.temperature=n.temperature),n.
551
+ !r&&i.push({role:"system",content:Jm(n.schema)});let a={model:e,messages:i};if(n.maxOutputTokens!=null&&(a[this.campoDeTope(e)]=n.maxOutputTokens),n.temperature!=null&&(a.temperature=n.temperature),n.
552
552
  seed!=null&&this.campoAdmitido(e,"seed")&&(a.seed=n.seed),n.reasoningEffort!=null&&this.campoAdmitido(e,"reasoning_effort")&&(a.reasoning_effort=n.reasoningEffort),n.promptCacheKey!=null&&(this.opts.sendPromptCacheKey??
553
553
  this.origen==="openai")&&this.campoAdmitido(e,"prompt_cache_key")&&(a.prompt_cache_key=n.promptCacheKey),n.deferrable===true&&this.campoAdmitido(e,"service_tier")&&(a.service_tier=We),s&&(a.prompt_cache_options=
554
554
  {mode:"explicit"}),n.schema&&r){let c=Be(n.schema);c||Ce(this,"strict-incompatible","[bvsala] The response contract does not meet OpenAI's `strict` mode (in strict, `required` must list ALL the keys i\
@@ -563,32 +563,32 @@ service_tier=="string"&&e.service_tier!==""?e.service_tier:void 0,x=v?"cuerpo":v
563
563
  {text:c,...u.length>0?{toolCalls:u}:{},...b?{finishReason:b}:{},...y!==void 0?{finishReasonDetail:y}:{},...l!==void 0?{refusal:l}:{},...v?{servedServiceTier:v}:{},...r.deferrable===true&&this.campoAdmitido(
564
564
  i,"service_tier")?{requestedServiceTier:We}:{},usage:{inputTokens:p,outputTokens:f,...d.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:d.prompt_tokens_details.cached_tokens}:{},...E!==void 0?
565
565
  {cacheWriteInputTokens:E}:{},...C!==void 0?{reasoningTokens:C}:{},...m||g?{complete:false}:{}},structuredNatively:r.schema!=null&&o,raw:e},{esquemaEnFormatoNativo:r.schema!=null&&o,esquemaEstricto:r.schema!=
566
- null&&o&&Be(r.schema),esquemaPorPrompt:r.schema!=null&&!o,piezasDelAdaptador:cn(r.tools),origen:this.origen,...x?{tierLeidoDe:x}:{},...S?{cacheExplicita:{puntos:S.puntos}}:{}})}};function Zm(t,e){let n=t?.
567
- completion_tokens_details?.reasoning_tokens;if(!(typeof n!="number"||!Number.isInteger(n)||n<0)&&!(n===0&&e))return n}function vl(t,e,n){let r=t?.completion_tokens??0,o=Zm(t,n),i=e==="openai"?0:ml(t);
566
+ null&&o&&Be(r.schema),esquemaPorPrompt:r.schema!=null&&!o,piezasDelAdaptador:cn(r.tools),origen:this.origen,...x?{tierLeidoDe:x}:{},...S?{cacheExplicita:{puntos:S.puntos}}:{}})}};function Qm(t,e){let n=t?.
567
+ completion_tokens_details?.reasoning_tokens;if(!(typeof n!="number"||!Number.isInteger(n)||n<0)&&!(n===0&&e))return n}function vl(t,e,n){let r=t?.completion_tokens??0,o=Qm(t,n),i=e==="openai"?0:ml(t);
568
568
  return i===0?{salida:r,razonamiento:o}:{salida:r+i,razonamiento:Math.max(i,o??0)}}function yl(t){let e=t?.prompt_tokens_details?.cache_write_tokens;return typeof e=="number"&&Number.isInteger(e)&&e>=0?
569
569
  e:void 0}function kl(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Qr(t){return typeof t=="string"&&t!==""}function xl(t,e){return `provider returned incomplete usage (pro\
570
570
  mpt=${t??"absent"}, completion=${e??"absent"}); cannot measure cost. For gateways/streaming, ensure usage reporting is enabled.`}async function eo(t){try{return (await t.text()).slice(0,500)}catch{return "\
571
571
  <no body>"}}function wl(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:
572
- `+JSON.stringify(t)}var Xm=["claude-opus-5-5","claude-sonnet-5-5","claude-fable-5-1","claude-mythos-5-1"],Qm=["claude-opus-4-7","claude-opus-4-8","claude-opus-5","claude-sonnet-5","claude-fable-5","claude-mythos-5"];function eh(t){return /claude-[a-z]+-\d[a-z0-9-]*/.exec(t.toLowerCase())?.[0]}function Sl(t,e){let n=eh(t);return n===void 0?false:e.some(r=>n===r||n.startsWith(`${r}-`))}function El(t){return Sl(t,Xm)}function Cl(t){
573
- return Sl(t,Qm)}function Tl(t){return /tool_choice/i.test(t)&&/not supported|unsupported|not available/i.test(t)}function Rl(t){return /\b(temperature|top_p|top_k)\b/i.test(t)&&/deprecated|not supported|unsupported|non-default|not allowed/i.
572
+ `+JSON.stringify(t)}var eh=["claude-opus-5-5","claude-sonnet-5-5","claude-fable-5-1","claude-mythos-5-1"],th=["claude-opus-4-7","claude-opus-4-8","claude-opus-5","claude-sonnet-5","claude-fable-5","claude-mythos-5"];function nh(t){return /claude-[a-z]+-\d[a-z0-9-]*/.exec(t.toLowerCase())?.[0]}function Sl(t,e){let n=nh(t);return n===void 0?false:e.some(r=>n===r||n.startsWith(`${r}-`))}function El(t){return Sl(t,eh)}function Cl(t){
573
+ return Sl(t,th)}function Tl(t){return /tool_choice/i.test(t)&&/not supported|unsupported|not available/i.test(t)}function Rl(t){return /\b(temperature|top_p|top_k)\b/i.test(t)&&/deprecated|not supported|unsupported|non-default|not allowed/i.
574
574
  test(t)}function Pl(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(l=>l.
575
575
  type==="tool_search_tool_result"&&l.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=[],
576
- c=true;for(let l of s.tool_references){if(typeof l?.tool_name!="string"){c=false;break}a.includes(l.tool_name)||a.push(l.tool_name);}c&&e.push({busqueda:o,id:r,uso:n,resultado:i,herramientas:a});}return e}var th={
577
- bytes:4*1024*1024,porEntrada:64*1024,claves:4096},no=class{constructor(e=th){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(
576
+ c=true;for(let l of s.tool_references){if(typeof l?.tool_name!="string"){c=false;break}a.includes(l.tool_name)||a.push(l.tool_name);}c&&e.push({busqueda:o,id:r,uso:n,resultado:i,herramientas:a});}return e}var rh={
577
+ bytes:4*1024*1024,porEntrada:64*1024,claves:4096},no=class{constructor(e=rh){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(
578
578
  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>
579
579
  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.
580
- 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 dn=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:0;function Il(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){
580
+ 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 dn=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:0;function _l(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){
581
581
  if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;e.iteraciones++,e.input+=dn(r.input_tokens),e.output+=dn(r.output_tokens),e.cacheRead+=dn(r.cache_read_input_tokens);
582
582
  let o=r.cache_creation,i=dn(o?.ephemeral_5m_input_tokens),s=dn(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?dn(r.cache_creation_input_tokens):i+s;e.cacheWrite+=a,e.cacheWrite1h+=
583
- Math.min(s,a);}return e.iteraciones>0?e:null}function ns(t,e,n){let r=t??{},o=Il(r.iterations),i=_l(r.cache_read_input_tokens,o?.cacheRead),s=_l(r.cache_creation_input_tokens,o?.cacheWrite),a=r.cache_creation?.ephemeral_1h_input_tokens,c=typeof a==
583
+ Math.min(s,a);}return e.iteraciones>0?e:null}function ns(t,e,n){let r=t??{},o=_l(r.iterations),i=Il(r.cache_read_input_tokens,o?.cacheRead),s=Il(r.cache_creation_input_tokens,o?.cacheWrite),a=r.cache_creation?.ephemeral_1h_input_tokens,c=typeof a==
584
584
  "number"||(o?.cacheWrite1h??0)>0?Math.min(Math.max(0,(typeof a=="number"?a:0)+(o?.cacheWrite1h??0)),s??0):void 0,l=(r.input_tokens??0)+(o?.input??0)+(s??0)+(i??0),u=(e??0)+(o?.output??0),d=typeof r.input_tokens!=
585
585
  "number",p=typeof e!="number";return {usage:{inputTokens:l,outputTokens:u,...i!=null?{cachedInputTokens:i}:{},...s!=null?{cacheWriteInputTokens:s}:{},...c!==void 0?{cacheWrite1hInputTokens:c}:{},...n||
586
- p||o?{}:{reasoningTokens:0},...d||p?{complete:false}:{}},entradaAusente:d,salidaAusente:p}}function _l(t,e){return e?(t??0)+e:t}function rs(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
586
+ p||o?{}:{reasoningTokens:0},...d||p?{complete:false}:{}},entradaAusente:d,salidaAusente:p}}function Il(t,e){return e?(t??0)+e:t}function rs(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
587
587
  function os(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??
588
588
  {},...n,...r?{cache_creation:r}:{}}}function is(t){return t==="thinking"||t==="redacted_thinking"}function ss(t){switch(t){case "end_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "\
589
- tool_calls";case "refusal":return "content_filter";default:return t}}var nh=new Set([null,"cyber","general_harms"]);function as(t){if(t.stopReason!=="refusal")return false;let e=t.stopDetails;if(e===null||typeof e!=
590
- "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"||!nh.has(r)||t.bloques!==0||t.outputTokens!==0||Array.
591
- isArray(t.iterations)&&t.iterations.length>1)}function Vn(t,e){if(t!=="refusal"||e===null||typeof e!="object"||Array.isArray(e))return;let n=e.category;return typeof n=="string"&&n!==""?n:void 0}var ro=4,Ge="bvsala_contract",oh={"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\
589
+ tool_calls";case "refusal":return "content_filter";default:return t}}var oh=new Set([null,"cyber","general_harms"]);function as(t){if(t.stopReason!=="refusal")return false;let e=t.stopDetails;if(e===null||typeof e!=
590
+ "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"||!oh.has(r)||t.bloques!==0||t.outputTokens!==0||Array.
591
+ isArray(t.iterations)&&t.iterations.length>1)}function Vn(t,e){if(t!=="refusal"||e===null||typeof e!="object"||Array.isArray(e))return;let n=e.category;return typeof n=="string"&&n!==""?n:void 0}var ro=4,Ge="bvsala_contract",sh={"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\
592
592
  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\
593
593
  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\
594
594
  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\
@@ -598,7 +598,7 @@ t does not make available to the model: it is missing from `tools` (not passed,
598
598
  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\
599
599
  urn of the conversation to keep the native tool loop."},Dl=class{id;opts;fetchImpl;busquedas=new no;sinToolChoiceForzado=new Set;sinMuestreo=new Set;constructor(e={}){this.opts=e,this.id=`anthropic:${e.
600
600
  baseUrl??"https://api.anthropic.com/v1"}`,this.fetchImpl=e.fetchImpl??fetch,al(this,oo(e.baseUrl)?"oficial":"compatible"),ln(this,an(e.baseUrl??"https://api.anthropic.com/v1"));let n=this.opts.baseUrl??
601
- "https://api.anthropic.com/v1";Yr(this,{protocolo:"anthropic",origen:dh(n),endpoint:Zr(n),cuerpo:r=>this.construirCuerpo(r).body,leer:(r,o)=>this.leerMensaje(r,o,false,false,false,false),solicitar:(r,o)=>{let i=`${n.
601
+ "https://api.anthropic.com/v1";Yr(this,{protocolo:"anthropic",origen:fh(n),endpoint:Zr(n),cuerpo:r=>this.construirCuerpo(r).body,leer:(r,o)=>this.leerMensaje(r,o,false,false,false,false),solicitar:(r,o)=>{let i=`${n.
602
602
  replace(/\/$/,"")}${Xr(r)}`;return this.fetchImpl(i,{method:o.method,headers:{...o.json!==void 0?{"content-type":"application/json"}:{},"anthropic-version":this.opts.apiVersion??"2023-06-01",...this.opts.
603
603
  apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},...o.json!==void 0?{body:JSON.stringify(o.json)}:{},...o.signal?{signal:o.signal}:{}})}});}modeloEnElCable(e){return this.opts.stripProviderPrefix??
604
604
  oo(this.opts.baseUrl)?e.replace(/^[^/]+\//,""):e}async generate(e,n){let{cuerpo:r,response:o}=await this.enviarConCorrecciones(e,false,n?.signal);return this.leer(o,e,r.contratoNativo,r.turnoAnadido,r.esquemaPorPrompt,
@@ -613,9 +613,9 @@ text",delta:w.text};else if(w?.type==="input_json_delta"&&typeof w.partial_json=
613
613
  d=true,h=R.delta?.stop_reason??h,R.delta&&"stop_details"in R.delta&&(f=R.delta.stop_details),R.usage&&(u=os(u,R.usage));else if(M==="message_stop"){p=true;break}else if(M==="error")throw new Error(`provid\
614
614
  er stream error: ${R.error?.type}: ${R.error?.message}`)}if(!p&&!d)throw new Error("provider stream ended before completion (no message_delta)");let v=os(l,u),E=(d?ns(v,u?.output_tokens,g):void 0)?.usage??
615
615
  {inputTokens:0,outputTokens:0,complete:false};if(this.opts.requireUsage&&E.complete===false)throw new Error(Ll(d?v.input_tokens:void 0,d?u?.output_tokens:void 0));let S=[...c.entries()].sort((T,R)=>T[0]-R[0]).
616
- map(([,T])=>T).filter(T=>T.tipo==="tool_use"&&T.name!==Ge).map(T=>({...T.id?{id:T.id}:{},name:T.name??"",arguments:uh(T.json)})).filter(T=>T.name!==""),C=rs(v),A=e.toolSearch?Ol([...c.entries()].sort(
616
+ map(([,T])=>T).filter(T=>T.tipo==="tool_use"&&T.name!==Ge).map(T=>({...T.id?{id:T.id}:{},name:T.name??"",arguments:ph(T.json)})).filter(T=>T.name!==""),C=rs(v),A=e.toolSearch?Ol([...c.entries()].sort(
617
617
  (T,R)=>T[0]-R[0]).map(([,T])=>({type:T.tipo,name:T.name,content:T.content})),r.reenviadas):void 0;if(e.toolSearch){let T=[];for(let[,R]of [...c.entries()].sort((M,w)=>M[0]-w[0]))if(R.tipo==="tool_use")
618
- T.push({type:"tool_use",id:R.id,name:R.name});else if(R.tipo==="tool_search_tool_result"&&R.crudo)T.push(R.crudo);else if(R.tipo==="server_tool_use"&&R.crudo){let M=R.json===""?R.crudo.input??{}:lh(R.
618
+ T.push({type:"tool_use",id:R.id,name:R.name});else if(R.tipo==="tool_search_tool_result"&&R.crudo)T.push(R.crudo);else if(R.tipo==="server_tool_use"&&R.crudo){let M=R.json===""?R.crudo.input??{}:dh(R.
619
619
  json);M!==void 0&&T.push({...R.crudo,input:M});}this.recordarBusquedas(T);}yield {type:"done",response:dt({text:a,...S.length>0?{toolCalls:S}:{},...h?{finishReason:ss(h)}:{},...Vn(h,f)!==void 0?{finishReasonDetail:Vn(
620
620
  h,f)}:{},...d&&as({stopReason:h,stopDetails:f,bloques:m,outputTokens:u?.output_tokens,iterations:v.iterations})?{unbilledRefusal:true}:{},...C?{servedServiceTier:C}:{},...A?{toolSearch:A}:{},...b?{providerMessageId:b}:
621
621
  {},...this.diagnosticoDe(e,y),usage:E,structuredNatively:false,raw:{usage:v,stop_reason:h}},Mt((r.turnoAnadido?1:0)+cn(e.tools)))};}async enviarConCorrecciones(e,n,r){let o=this.modeloEnElCable(e.model),i=this.
@@ -624,7 +624,7 @@ sinToolChoiceForzado.has(o)&&Tl(c))this.sinToolChoiceForzado.add(o);else if(i.bo
624
624
  : ${c}`);i=this.construirCuerpo(e),n&&(i.body.stream=true),s=await this.enviar(i.body,r);}if(!s.ok)throw new Error(`provider ${s.status}: ${await Ml(s)}`);return {cuerpo:i,response:s}}async enviar(e,n){let r=(this.
625
625
  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??
626
626
  "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,
627
- finDelPrefijo:i,prefijoEnSystem:s,turnoAnadido:a}=ih(e,n?.anteponer,v=>this.avisar(`anthropic-herramientas-${v}`,oh[v]));if(o.length===0)throw new Error("anthropic: the request has no user/assistant m\
627
+ finDelPrefijo:i,prefijoEnSystem:s,turnoAnadido:a}=ah(e,n?.anteponer,v=>this.avisar(`anthropic-herramientas-${v}`,sh[v]));if(o.length===0)throw new Error("anthropic: the request has no user/assistant m\
628
628
  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(v=>({name:v.id,...v.description?{description:v.description}:
629
629
  {},input_schema:v.parameters??{type:"object",properties:{}}})),l=e.toolSearch?-1:c.length-1,u=this.modeloEnElCable(e.model),d=El(u)||this.sinToolChoiceForzado.has(u),p=Cl(u)||this.sinMuestreo.has(u);if(e.
630
630
  toolSearch&&c.length>0){let v=new Set(e.toolSearch.alwaysLoaded);for(let x of c)v.has(x.name)||(x.defer_loading=true);c.unshift({...Or[e.toolSearch.variant]});}let h=false,f=false,m=false,g;if(e.schema){let v=c.length>
@@ -672,46 +672,46 @@ e"&&x.name===Ge),h=p?JSON.stringify(p.input??{}):u,f=e.usage,{usage:m,entradaAus
672
672
  f),v=n.toolSearch?Ol(c,a):void 0;return n.toolSearch&&this.recordarBusquedas(c),dt({text:h,...d.length>0?{toolCalls:d}:{},...e.stop_reason?{finishReason:ss(e.stop_reason)}:{},...Vn(e.stop_reason,e.stop_details)!==
673
673
  void 0?{finishReasonDetail:Vn(e.stop_reason,e.stop_details)}:{},...as({stopReason:e.stop_reason,stopDetails:e.stop_details,bloques:Array.isArray(e.content)?e.content.length:0,outputTokens:f?.output_tokens,
674
674
  iterations:f?.iterations})?{unbilledRefusal:true}:{},...y?{servedServiceTier:y}:{},usage:m,structuredNatively:n.schema!=null&&r,...v?{toolSearch:v}:{},...typeof e.id=="string"&&e.id!==""?{providerMessageId:e.
675
- id}:{},...this.diagnosticoDe(n,e.diagnostics),raw:e},{...Mt((o?1:0)+cn(n.tools)),esquemaPorPrompt:i})}};function ih(t,e,n){let r=[],o=[],i=t.stablePrefixMessages??0,s,a=0,c=true,l=ch(t),u=new Set,d=t.messages,
675
+ id}:{},...this.diagnosticoDe(n,e.diagnostics),raw:e},{...Mt((o?1:0)+cn(n.tools)),esquemaPorPrompt:i})}};function ah(t,e,n){let r=[],o=[],i=t.stablePrefixMessages??0,s,a=0,c=true,l=uh(t),u=new Set,d=t.messages,
676
676
  p=m=>{if(m>=i)return;let g=o.length-1;s={mensaje:g,bloque:o[g].content.length-1};},h=(m,g)=>{m.content!==""&&(o.push({role:m.role==="assistant"?"assistant":"user",content:[{type:"text",text:m.content}]}),
677
677
  p(g));};for(let m=0;m<d.length;m++){let g=d[m];if(g.role==="system"&&c){r.push({type:"text",text:g.content}),m<i&&(a=r.length);continue}if(c=false,g.role!=="assistant"){g.role==="tool"&&n(g.toolCallId?"si\
678
678
  n-pareja":"sin-ids"),h(g,m);continue}let b=e?e(g):void 0;b&&l.cargar(b);let y=g.content!==""?[{type:"text",text:g.content}]:[],v=g.toolCalls??[],x=m+1;if(v.length>0){for(;x<d.length&&d[x].role==="tool";)
679
- x+=1;let S=sh(v,d.slice(m+1,x),l,u);if("llamadas"in S){o.push({role:"assistant",content:[...b??[],...y,...S.llamadas]}),p(m);let C={role:"user",content:[]};o.push(C),S.resultados.forEach((A,T)=>{C.content.
679
+ x+=1;let S=ch(v,d.slice(m+1,x),l,u);if("llamadas"in S){o.push({role:"assistant",content:[...b??[],...y,...S.llamadas]}),p(m);let C={role:"user",content:[]};o.push(C),S.resultados.forEach((A,T)=>{C.content.
680
680
  push(A),p(m+1+T);}),m=x-1;continue}n(S.motivo);}let E=b?[...b,...y]:y;E.length>0&&(o.push({role:"assistant",content:E}),p(m));for(let S=m+1;S<x;S++)h(d[S],S);m=x-1;}let f=false;return o.length>0&&o[0].role===
681
681
  "assistant"&&(o.unshift({role:"user",content:[{type:"text",text:"(continue)"}]}),s&&(s={mensaje:s.mensaje+1,bloque:s.bloque}),f=true),{system:r,messages:o,finDelPrefijo:s,prefijoEnSystem:a,turnoAnadido:f}}
682
- function sh(t,e,n,r){if(t.some(c=>!c.id)||e.some(c=>!c.toolCallId))return {motivo:"sin-ids"};let o=t.map(c=>Al(c.id)),i=new Set(o);if(i.size!==o.length||o.some(c=>r.has(c)))return {motivo:"sin-pareja"};
683
- let s=e.map(c=>Al(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=>ah(c.arguments));if(a.some(c=>c===void 0))return {motivo:"\
682
+ function ch(t,e,n,r){if(t.some(c=>!c.id)||e.some(c=>!c.toolCallId))return {motivo:"sin-ids"};let o=t.map(c=>Al(c.id)),i=new Set(o);if(i.size!==o.length||o.some(c=>r.has(c)))return {motivo:"sin-pareja"};
683
+ let s=e.map(c=>Al(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=>lh(c.arguments));if(a.some(c=>c===void 0))return {motivo:"\
684
684
  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,l)=>({type:"tool_use",id:o[l],name:c.name,input:a[l]})),resultados:e.map((c,l)=>({
685
- type:"tool_result",tool_use_id:s[l],...c.content!==""?{content:c.content}:{},...c.isError===true?{is_error:true}:{}}))}}function Al(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}function ah(t){let e=n=>typeof n==
686
- "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 ch(t){let e=new Set((t.tools??
685
+ type:"tool_result",tool_use_id:s[l],...c.content!==""?{content:c.content}:{},...c.isError===true?{is_error:true}:{}}))}}function Al(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}function lh(t){let e=n=>typeof n==
686
+ "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 uh(t){let e=new Set((t.tools??
687
687
  []).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!=="\
688
688
  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 oo(t){try{return /(^|\.)api\.anthropic\.com$/i.
689
689
  test(new URL(t??"https://api.anthropic.com/v1").hostname)}catch{return false}}function Ol(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\
690
690
  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)
691
- 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 lh(t){
692
- try{return JSON.parse(t)}catch{return}}function uh(t){try{return JSON.stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function Ll(t,e){return `provider returned incomplete usage (input=${t??"absen\
693
- t"}, output=${e??"absent"}); cannot measure cost.`}async function Ml(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function dh(t){return ut(t)==="anthropic"?"anthropic":null}var Nl="https://generativelanguage.googleapis.com/v1beta",jl="x-gemini-service-tier",ph=new Set(["SAFETY","RECITATION","LANGUAGE","OTHER","BLOCKLIST","PROHIBITED_CONTENT","SPII","IMAGE_SAFETY","IMAGE_\
694
- PROHIBITED_CONTENT","IMAGE_RECITATION","IMAGE_OTHER","ESCALATION"]),fh=new Set(["MALFORMED_FUNCTION_CALL","UNEXPECTED_TOOL_CALL","TOO_MANY_TOOL_CALLS","MISSING_THOUGHT_SIGNATURE","MALFORMED_RESPONSE",
691
+ 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 dh(t){
692
+ try{return JSON.parse(t)}catch{return}}function ph(t){try{return JSON.stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function Ll(t,e){return `provider returned incomplete usage (input=${t??"absen\
693
+ t"}, output=${e??"absent"}); cannot measure cost.`}async function Ml(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function fh(t){return ut(t)==="anthropic"?"anthropic":null}var Nl="https://generativelanguage.googleapis.com/v1beta",jl="x-gemini-service-tier",mh=new Set(["SAFETY","RECITATION","LANGUAGE","OTHER","BLOCKLIST","PROHIBITED_CONTENT","SPII","IMAGE_SAFETY","IMAGE_\
694
+ PROHIBITED_CONTENT","IMAGE_RECITATION","IMAGE_OTHER","ESCALATION"]),hh=new Set(["MALFORMED_FUNCTION_CALL","UNEXPECTED_TOOL_CALL","TOO_MANY_TOOL_CALLS","MISSING_THOUGHT_SIGNATURE","MALFORMED_RESPONSE",
695
695
  "NO_IMAGE"]);function Bl(t,e,n){return e!==void 0&&e!==""&&e!=="BLOCK_REASON_UNSPECIFIED"?{parada:"content_filter",detalle:e,reproducible:true}:t===void 0||t===""||t==="FINISH_REASON_UNSPECIFIED"?{reproducible:true}:
696
- t==="STOP"?{parada:n?"tool_calls":"stop",reproducible:true}:t==="MAX_TOKENS"?{parada:"length",reproducible:true}:ph.has(t)?{parada:"content_filter",detalle:t,reproducible:true}:{parada:t,reproducible:!fh.has(
697
- t)}}function mh(t){return /(^|\/)gemini-2\.5/.test(t)}function $l(t){return /-pro\b/.test(t)}function zl(t,e){let n=e.toLowerCase();if(mh(t)){let o={minimal:1024,low:1024,medium:8192,high:24576,xhigh:24576};
696
+ t==="STOP"?{parada:n?"tool_calls":"stop",reproducible:true}:t==="MAX_TOKENS"?{parada:"length",reproducible:true}:mh.has(t)?{parada:"content_filter",detalle:t,reproducible:true}:{parada:t,reproducible:!hh.has(
697
+ t)}}function gh(t){return /(^|\/)gemini-2\.5/.test(t)}function $l(t){return /-pro\b/.test(t)}function zl(t,e){let n=e.toLowerCase();if(gh(t)){let o={minimal:1024,low:1024,medium:8192,high:24576,xhigh:24576};
698
698
  if(n==="none")return $l(t)?null:{config:{thinkingBudget:0},noSeApaga:false};let i=o[n];return i===void 0?null:{config:{thinkingBudget:i},noSeApaga:false}}let r=$l(t)?"LOW":"MINIMAL";switch(n){case "none":return {
699
699
  config:{thinkingLevel:r},noSeApaga:true};case "minimal":return {config:{thinkingLevel:r},noSeApaga:false};case "low":return {config:{thinkingLevel:"LOW"},noSeApaga:false};case "medium":return {config:{thinkingLevel:"\
700
700
  MEDIUM"},noSeApaga:false};case "high":case "xhigh":return {config:{thinkingLevel:"HIGH"},noSeApaga:false};default:return {config:{thinkingLevel:e.toUpperCase()},noSeApaga:false}}}function Fl(t){let e=/thinking level (\w+) is not supported/i.
701
- exec(t);return e?e[1].toUpperCase():null}function hh(t){return typeof t=="string"&&t!==""?{google:{thought_signature:t}}:void 0}function gh(t){let e=t?.google;if(e===null||typeof e!="object")return;let n=e.
702
- thought_signature;return typeof n=="string"&&n!==""?n:void 0}function bh(t){try{let e=JSON.parse(t===""?"{}":t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return {}}}function vh(t){
701
+ exec(t);return e?e[1].toUpperCase():null}function bh(t){return typeof t=="string"&&t!==""?{google:{thought_signature:t}}:void 0}function vh(t){let e=t?.google;if(e===null||typeof e!="object")return;let n=e.
702
+ thought_signature;return typeof n=="string"&&n!==""?n:void 0}function yh(t){try{let e=JSON.parse(t===""?"{}":t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return {}}}function kh(t){
703
703
  if(t.isError===true)return {error:t.content};try{let e=JSON.parse(t.content);if(e!==null&&typeof e=="object"&&!Array.isArray(e))return e}catch{}return {result:t.content}}function ql(t){let e=[],n=[],r=true,
704
704
  o=[],i=0,s=(a,c)=>{if(c.length===0)return;let l=n[n.length-1];l&&l.role===a?l.parts.push(...c):n.push({role:a,parts:c});};for(let a of t){if(a.role==="system"&&r){a.content!==""&&e.push({text:a.content});
705
705
  continue}if(r=false,a.role==="tool"){let c=a.toolCallId?o.find(d=>d.id===a.toolCallId):void 0,l=c??o[i],u=a.name??l?.name;if(i+=1,!u){s("user",a.content!==""?[{text:a.content}]:[]);continue}s("user",[{functionResponse:{
706
- ...c?.id?{id:c.id}:{},name:u,response:vh(a)}}]);continue}if(a.role==="assistant"){let c=a.content!==""?[{text:a.content}]:[],l=a.toolCalls??[];for(let u of l){let d=gh(u.extraContent);c.push({functionCall:{
707
- ...u.id?{id:u.id}:{},name:u.name,args:bh(u.arguments)},...d!==void 0?{thoughtSignature:d}:{}});}o=l,i=0,s("model",c);continue}s("user",a.content!==""?[{text:a.content}]:[]);}return {...e.length>0?{systemInstruction:{
706
+ ...c?.id?{id:c.id}:{},name:u,response:kh(a)}}]);continue}if(a.role==="assistant"){let c=a.content!==""?[{text:a.content}]:[],l=a.toolCalls??[];for(let u of l){let d=vh(u.extraContent);c.push({functionCall:{
707
+ ...u.id?{id:u.id}:{},name:u.name,args:yh(u.arguments)},...d!==void 0?{thoughtSignature:d}:{}});}o=l,i=0,s("model",c);continue}s("user",a.content!==""?[{text:a.content}]:[]);}return {...e.length>0?{systemInstruction:{
708
708
  parts:e}}:{},contents:n}}function ve(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function Ul(t,e){let n=t?.promptTokenCount,r=t?.candidatesTokenCount,o=t?.thoughtsTokenCount,i=t?.toolUsePromptTokenCount,
709
709
  s=t?.totalTokenCount,a=(ve(n)?n:0)+(ve(i)?i:0),c=ve(r)?r:0,l=ve(o)?o:0,u=ve(s)&&ve(n)?Math.max(0,s-n-c-l-(ve(i)?i:0)):0,d;(ve(o)||ve(s))&&(d=l+u),d===0&&e&&(d=void 0);let p=ve(r)||ve(s)&&ve(n),h=ve(n)&&
710
710
  p;return {inputTokens:a,outputTokens:c+l+u,...ve(t?.cachedContentTokenCount)?{cachedInputTokens:t.cachedContentTokenCount}:{},...d!==void 0?{reasoningTokens:d}:{},...h?{}:{complete:false}}}var Hn=class{texto="";llamadas=[];paradaNativa;bloqueo;uso;huboPensamiento=false;idDeRespuesta;ultimo;sumar(e){
711
711
  if(this.ultimo=e,e.error!=null){let i=e.error,s=typeof i.message=="string"?i.message:JSON.stringify(e.error);throw new Error(`provider stream error: ${s}`)}e.usageMetadata!=null&&typeof e.usageMetadata==
712
712
  "object"&&(this.uso=e.usageMetadata),typeof e.responseId=="string"&&e.responseId!==""&&(this.idDeRespuesta??=e.responseId);let n=e.promptFeedback?.blockReason;typeof n=="string"&&n!==""&&(this.bloqueo=
713
713
  n);let r="",o=e.candidates?.[0];for(let i of o?.content?.parts??[]){if(i.thought===true){this.huboPensamiento=true;continue}if(i.functionCall&&typeof i.functionCall.name=="string"&&i.functionCall.name!==""){
714
- let s=hh(i.thoughtSignature);this.llamadas.push({...typeof i.functionCall.id=="string"&&i.functionCall.id!==""?{id:i.functionCall.id}:{},name:i.functionCall.name,arguments:JSON.stringify(i.functionCall.
714
+ let s=bh(i.thoughtSignature);this.llamadas.push({...typeof i.functionCall.id=="string"&&i.functionCall.id!==""?{id:i.functionCall.id}:{},name:i.functionCall.name,arguments:JSON.stringify(i.functionCall.
715
715
  args??{}),...s!==void 0?{extraContent:s}:{}});continue}typeof i.text=="string"&&i.text!==""&&(r+=i.text);}return this.texto+=r,typeof o?.finishReason=="string"&&o.finishReason!==""&&(this.paradaNativa=
716
716
  o.finishReason),r}terminado(){return this.paradaNativa!==void 0||this.bloqueo!==void 0}};function cs(t){let e=t.replace(/^models\//,"");return e.includes("/")?e.replace(/^[^/]+\//,"").replace(/^models\//,
717
717
  ""):e}function Vl(t,e){try{let n=t.headers?.get?.(e);return typeof n=="string"&&n.trim()!==""?n.trim():void 0}catch{return}}async function ls(t){try{return (await t.text()).slice(0,500)}catch{return "<n\
@@ -746,8 +746,8 @@ now()-this.start}all(){return this.events}};var Ke=class extends Error{status;co
746
746
  `"${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 De(t,e,n=""){
747
747
  let r=us(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}`,l=s+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):
748
748
  new TypeError(l)}return t}function ds(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 Gl(t,e){De(t,void 0,"digestInt\
749
- o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function Wn(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function so(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Kl=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",yh=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ao(t){if(De(t),Kl)return t.toHex();
750
- let e="";for(let n=0;n<t.length;n++)e+=yh[t[n]];return e}var Je={_0:48,_9:57,A:65,F:70,a:97,f:102};function Wl(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&&
749
+ o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function Wn(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function so(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Kl=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",xh=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ao(t){if(De(t),Kl)return t.toHex();
750
+ let e="";for(let n=0;n<t.length;n++)e+=xh[t[n]];return e}var Je={_0:48,_9:57,A:65,F:70,a:97,f:102};function Wl(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&&
751
751
  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(Kl)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?
752
752
  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=Wl(t.charCodeAt(
753
753
  i)),a=Wl(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 ps(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];De(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 Jl(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 Yl(t=32){
@@ -758,8 +758,8 @@ o)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,
758
758
  Gl(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,Wn(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(
759
759
  o-8,BigInt(this.length*8),i),this.process(r,0);let a=so(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_s\
760
760
  ha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[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.
761
- 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 ae=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var lo=BigInt(4294967295),Xl=BigInt(32);function kh(t,e=false){return e?{h:Number(t&lo),l:Number(t>>Xl&lo)}:{h:Number(t>>Xl&lo)|0,l:Number(t&lo)|0}}function Ql(t,e=false){let n=t.length,r=new Uint32Array(n),
762
- o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=kh(t[i],e);[r[i],o[i]]=[s,a];}return [r,o]}var fs=(t,e,n)=>t>>>n,ms=(t,e,n)=>t<<32-n|e>>>n,Nt=(t,e,n)=>t>>>n|e<<32-n,jt=(t,e,n)=>t<<32-n|e>>>n,Kn=(t,e,n)=>t<<64-n|e>>>n-32,Jn=(t,e,n)=>t>>>n-32|e<<64-n;function ze(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var eu=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),tu=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,nu=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),ru=(t,e,n,r,o)=>e+
761
+ 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 ae=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var lo=BigInt(4294967295),Xl=BigInt(32);function wh(t,e=false){return e?{h:Number(t&lo),l:Number(t>>Xl&lo)}:{h:Number(t>>Xl&lo)|0,l:Number(t&lo)|0}}function Ql(t,e=false){let n=t.length,r=new Uint32Array(n),
762
+ o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=wh(t[i],e);[r[i],o[i]]=[s,a];}return [r,o]}var fs=(t,e,n)=>t>>>n,ms=(t,e,n)=>t<<32-n|e>>>n,Nt=(t,e,n)=>t>>>n|e<<32-n,jt=(t,e,n)=>t<<32-n|e>>>n,Kn=(t,e,n)=>t<<64-n|e>>>n-32,Jn=(t,e,n)=>t>>>n-32|e<<64-n;function ze(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var eu=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),tu=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,nu=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),ru=(t,e,n,r,o)=>e+
763
763
  n+r+o+(t/2**32|0)|0,ou=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),iu=(t,e,n,r,o,i)=>e+n+r+o+i+(t/2**32|0)|0;var su=Ql(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
764
764
  "0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
765
765
  8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
@@ -768,77 +768,77 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
768
768
  x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
769
769
  efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
770
770
  eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
771
- 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),wh=su[0],Sh=su[1],ft=new Uint32Array(80),mt=new Uint32Array(80),hs=class extends co{constructor(e){
771
+ 00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Eh=su[0],Ch=su[1],ft=new Uint32Array(80),mt=new Uint32Array(80),hs=class extends co{constructor(e){
772
772
  super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:p,Gh:h,Gl:f,Hh:m,Hl:g}=this;return [e,n,r,o,i,s,a,c,l,u,d,p,h,f,m,g]}set(e,n,r,o,i,s,a,c,l,u,d,p,h,f,m,g){this.Ah=
773
773
  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=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=h|0,this.Gl=f|0,this.Hh=m|0,this.Hl=g|0;}process(e,n){for(let v=0;v<
774
774
  16;v++,n+=4)ft[v]=e.getUint32(n),mt[v]=e.getUint32(n+=4);for(let v=16;v<80;v++){let x=ft[v-15]|0,E=mt[v-15]|0,S=Nt(x,E,1)^Nt(x,E,8)^fs(x,E,7),C=jt(x,E,1)^jt(x,E,8)^ms(x,E,7),A=ft[v-2]|0,T=mt[v-2]|0,R=Nt(
775
775
  A,T,19)^Kn(A,T,61)^fs(A,T,6),M=jt(A,T,19)^Jn(A,T,61)^ms(A,T,6),w=nu(C,M,mt[v-7],mt[v-16]),P=ru(w,S,R,ft[v-7],ft[v-16]);ft[v]=P|0,mt[v]=w|0;}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:p,Fh:h,Fl:f,
776
- Gh:m,Gl:g,Hh:b,Hl:y}=this;for(let v=0;v<80;v++){let x=Nt(d,p,14)^Nt(d,p,18)^Kn(d,p,41),E=jt(d,p,14)^jt(d,p,18)^Jn(d,p,41),S=d&h^~d&m,C=p&f^~p&g,A=ou(y,E,C,Sh[v],mt[v]),T=iu(A,b,x,S,wh[v],ft[v]),R=A|0,
776
+ Gh:m,Gl:g,Hh:b,Hl:y}=this;for(let v=0;v<80;v++){let x=Nt(d,p,14)^Nt(d,p,18)^Kn(d,p,41),E=jt(d,p,14)^jt(d,p,18)^Jn(d,p,41),S=d&h^~d&m,C=p&f^~p&g,A=ou(y,E,C,Ch[v],mt[v]),T=iu(A,b,x,S,Eh[v],ft[v]),R=A|0,
777
777
  M=Nt(r,o,28)^Kn(r,o,34)^Kn(r,o,39),w=jt(r,o,28)^Jn(r,o,34)^Jn(r,o,39),P=r&i^r&a^i&a,$=o&s^o&c^s&c;b=m|0,y=g|0,m=h|0,g=f|0,h=d|0,f=p|0,{h:d,l:p}=ze(l|0,u|0,T|0,R|0),l=a|0,u=c|0,a=i|0,c=s|0,i=r|0,s=o|0;
778
778
  let O=eu(R,w,$);r=tu(O,T,M,P),o=O|0;}(({h:r,l:o}=ze(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=ze(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=ze(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ze(this.Dh|0,this.Dl|0,l|0,
779
779
  u|0),{h:d,l:p}=ze(this.Eh|0,this.El|0,d|0,p|0),{h,l:f}=ze(this.Fh|0,this.Fl|0,h|0,f|0),{h:m,l:g}=ze(this.Gh|0,this.Gl|0,m|0,g|0),{h:b,l:y}=ze(this.Hh|0,this.Hl|0,b|0,y|0),this.set(r,o,i,s,a,c,l,u,d,p,
780
780
  h,f,m,g,b,y);}roundClean(){Wn(ft,mt);}destroy(){this.destroyed=true,Wn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},gs=class extends hs{Ah=ae[0]|0;Al=ae[1]|0;Bh=ae[2]|0;Bl=ae[3]|0;Ch=ae[4]|0;Cl=ae[5]|
781
781
  0;Dh=ae[6]|0;Dl=ae[7]|0;Eh=ae[8]|0;El=ae[9]|0;Fh=ae[10]|0;Fl=ae[11]|0;Gh=ae[12]|0;Gl=ae[13]|0;Hh=ae[14]|0;Hl=ae[15]|0;constructor(){super(64);}};var uo=Jl(()=>new gs,Zl(3));var ne=(t,e,n)=>De(t,e,n),vs=io,ys=ao,Fe=(...t)=>ps(...t),au=t=>Gn(t),mo=us,cu=t=>Yl(t),fo=BigInt(0),bs=BigInt(1);function pn(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"\
782
- expected boolean, got type="+typeof t)}return t}function Eh(t){if(typeof t=="bigint"){if(!po(t))throw new RangeError("positive bigint expected, got "+t)}else vs(t);return t}function Ye(t,e=""){if(typeof t!=
782
+ expected boolean, got type="+typeof t)}return t}function Th(t){if(typeof t=="bigint"){if(!po(t))throw new RangeError("positive bigint expected, got "+t)}else vs(t);return t}function Ye(t,e=""){if(typeof t!=
783
783
  "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 lu(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?fo:BigInt("0x"+t)}function ks(t){return lu(ao(t))}function Ze(t){return lu(ao(Yn(De(t)).reverse()))}
784
- function xs(t,e){if(io(e),e===0)throw new RangeError("zero length");t=Eh(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 uu(t,e){
785
- return xs(t,e).reverse()}function du(t,e){if(t=ne(t),e=ne(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(ne(t))}var po=t=>typeof t=="bigint"&&fo<=t;function Ch(t,e,n){return po(t)&&po(e)&&po(n)&&e<=t&&t<n}function ws(t,e,n,r){if(!Ch(e,n,r))throw new RangeError(
784
+ function xs(t,e){if(io(e),e===0)throw new RangeError("zero length");t=Th(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 uu(t,e){
785
+ return xs(t,e).reverse()}function du(t,e){if(t=ne(t),e=ne(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(ne(t))}var po=t=>typeof t=="bigint"&&fo<=t;function Rh(t,e,n){return po(t)&&po(e)&&po(n)&&e<=t&&t<n}function ws(t,e,n,r){if(!Rh(e,n,r))throw new RangeError(
786
786
  "expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Ss(t){if(t<fo)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>fo;t>>=bs,e+=1);return e}var pu=t=>(bs<<BigInt(t))-bs;function Bt(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(
787
787
  `param "${i}" is invalid: expected own property`);let c=t[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new TypeError(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.
788
- entries(i).forEach(([a,c])=>r(a,c,s));o(e,false),o(n,true);}var Es=()=>{throw new Error("not implemented")};var ce=BigInt(0),ie=BigInt(1),zt=BigInt(2),gu=BigInt(3),bu=BigInt(4),vu=BigInt(5),Th=BigInt(7),yu=BigInt(8),Rh=BigInt(9),ku=BigInt(16);function Q(t,e){if(e<=ce)throw new Error("mod: expected positive \
788
+ entries(i).forEach(([a,c])=>r(a,c,s));o(e,false),o(n,true);}var Es=()=>{throw new Error("not implemented")};var ce=BigInt(0),ie=BigInt(1),zt=BigInt(2),gu=BigInt(3),bu=BigInt(4),vu=BigInt(5),Ph=BigInt(7),yu=BigInt(8),_h=BigInt(9),ku=BigInt(16);function Q(t,e){if(e<=ce)throw new Error("mod: expected positive \
789
789
  modulus, got "+e);let n=t%e;return n>=ce?n:e+n}function Ae(t,e,n){if(e<ce)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >ce;)r*=r,r%=n;return r}function fu(t,e){if(t===ce)throw new Error("invert: expected non-zer\
790
790
  o number");if(e<=ce)throw new Error("invert: expected positive modulus, got "+e);let n=Q(t,e),r=e,o=ce,s=ie;for(;n!==ce;){let l=r/n,u=r-n*l,d=o-s*l;r=n,n=u,o=s,s=d;}if(r!==ie)
791
791
  throw new Error("invert: does not exist");return Q(o,e)}function Cs(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function xu(t,e){let n=t,r=(n.ORDER+ie)/bu,o=n.pow(e,
792
- r);return Cs(n,o,e),o}function Ph(t,e){let n=t,r=(n.ORDER-vu)/yu,o=n.mul(e,zt),i=n.pow(o,r),s=n.mul(e,i),a=n.mul(n.mul(s,zt),i),c=n.mul(s,n.sub(a,n.ONE));return Cs(n,c,e),c}function Ih(t){let e=vo(t),
793
- n=wu(t),r=n(e,e.neg(e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+Th)/ku;return((a,c)=>{let l=a,u=l.pow(c,s),d=l.mul(u,r),p=l.mul(u,o),h=l.mul(u,i),f=l.eql(l.sqr(d),c),m=l.eql(l.sqr(p),c);u=l.cmov(u,d,f),d=l.
792
+ r);return Cs(n,o,e),o}function Ih(t,e){let n=t,r=(n.ORDER-vu)/yu,o=n.mul(e,zt),i=n.pow(o,r),s=n.mul(e,i),a=n.mul(n.mul(s,zt),i),c=n.mul(s,n.sub(a,n.ONE));return Cs(n,c,e),c}function Dh(t){let e=vo(t),
793
+ n=wu(t),r=n(e,e.neg(e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+Ph)/ku;return((a,c)=>{let l=a,u=l.pow(c,s),d=l.mul(u,r),p=l.mul(u,o),h=l.mul(u,i),f=l.eql(l.sqr(d),c),m=l.eql(l.sqr(p),c);u=l.cmov(u,d,f),d=l.
794
794
  cmov(h,p,m);let g=l.eql(l.sqr(d),c),b=l.cmov(u,d,g);return Cs(l,b,c),b})}function wu(t){if(t<gu)throw new Error("sqrt is not defined for small field");let e=t-ie,n=0;for(;e%zt===ce;)e/=zt,n++;let r=zt,
795
795
  o=vo(t);for(;mu(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return xu;let i=o.pow(r,e),s=(e+ie)/zt;return function(c,l){let u=c;if(u.is0(l))return l;
796
796
  if(mu(u,l)!==1)throw new Error("Cannot find square root");let d=n,p=u.mul(u.ONE,i),h=u.pow(l,e),f=u.pow(l,s);for(;!u.eql(h,u.ONE);){if(u.is0(h))return u.ZERO;let m=1,g=u.sqr(h);for(;!u.eql(g,u.ONE);)if(m++,
797
- g=u.sqr(g),m===d)throw new Error("Cannot find square root");let b=ie<<BigInt(d-m-1),y=u.pow(p,b);d=m,p=u.sqr(y),h=u.mul(h,p),f=u.mul(f,y);}return f}}function _h(t){return t%bu===gu?xu:t%yu===vu?Ph:t%ku===
798
- Rh?Ih(t):wu(t)}var Xe=(t,e)=>(Q(t,e)&ie)===ie,Dh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Su(t){let e={ORDER:"bigint",
799
- BYTES:"number",BITS:"number"},n=Dh.reduce((r,o)=>(r[o]="function",r),e);if(Bt(t,n),Ye(t.BYTES,"BYTES"),Ye(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.
800
- ORDER<=ie)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Ah(t,e,n){let r=t;if(n<ce)throw new Error("invalid exponent, negatives unsupported");if(n===ce)return r.ONE;
797
+ g=u.sqr(g),m===d)throw new Error("Cannot find square root");let b=ie<<BigInt(d-m-1),y=u.pow(p,b);d=m,p=u.sqr(y),h=u.mul(h,p),f=u.mul(f,y);}return f}}function Ah(t){return t%bu===gu?xu:t%yu===vu?Ih:t%ku===
798
+ _h?Dh(t):wu(t)}var Xe=(t,e)=>(Q(t,e)&ie)===ie,Oh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Su(t){let e={ORDER:"bigint",
799
+ BYTES:"number",BITS:"number"},n=Oh.reduce((r,o)=>(r[o]="function",r),e);if(Bt(t,n),Ye(t.BYTES,"BYTES"),Ye(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.
800
+ ORDER<=ie)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Lh(t,e,n){let r=t;if(n<ce)throw new Error("invalid exponent, negatives unsupported");if(n===ce)return r.ONE;
801
801
  if(n===ie)return e;let o=r.ONE,i=e;for(;n>ce;)n&ie&&(o=r.mul(o,i)),i=r.sqr(i),n>>=ie;return o}function bo(t,e,n=false){let r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),i=e.reduce((a,c,l)=>r.is0(c)?a:(o[l]=
802
- a,r.mul(a,c)),r.ONE),s=r.inv(i);return e.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function mu(t,e){let n=t,r=(n.ORDER-ie)/zt,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 Oh(t,e){if(e!==void 0&&vs(e),t<=ce)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);
802
+ a,r.mul(a,c)),r.ONE),s=r.inv(i);return e.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function mu(t,e){let n=t,r=(n.ORDER-ie)/zt,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 Mh(t,e){if(e!==void 0&&vs(e),t<=ce)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);
803
803
  let n=Ss(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 hu=new WeakMap,
804
804
  go=class{ORDER;BITS;BYTES;isLE;ZERO=ce;ONE=ie;_lengths;_mod;constructor(e,n={}){if(e<=ie)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
805
805
  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.
806
- freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=Oh(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
806
+ freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=Mh(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
807
807
  048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,Object.freeze(this);}create(e){return Q(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got\
808
808
  "+typeof e);return ce<=e&&e<this.ORDER}is0(e){return e===ce}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&ie)===ie}neg(e){return Q(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return Q(
809
- e*e,this.ORDER)}add(e,n){return Q(e+n,this.ORDER)}sub(e,n){return Q(e-n,this.ORDER)}mul(e,n){return Q(e*n,this.ORDER)}pow(e,n){return Ah(this,e,n)}div(e,n){return Q(e*fu(n,this.ORDER),this.ORDER)}sqrN(e){
810
- return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return fu(e,this.ORDER)}sqrt(e){let n=hu.get(this);return n||hu.set(this,n=_h(this.ORDER)),n(this,e)}toBytes(e){return this.
809
+ e*e,this.ORDER)}add(e,n){return Q(e+n,this.ORDER)}sub(e,n){return Q(e-n,this.ORDER)}mul(e,n){return Q(e*n,this.ORDER)}pow(e,n){return Lh(this,e,n)}div(e,n){return Q(e*fu(n,this.ORDER),this.ORDER)}sqrN(e){
810
+ return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return fu(e,this.ORDER)}sqrt(e){let n=hu.get(this);return n||hu.set(this,n=Ah(this.ORDER)),n(this,e)}toBytes(e){return this.
811
811
  isLE?uu(e,this.BYTES):xs(e,this.BYTES)}fromBytes(e,n=false){ne(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.fromByte\
812
812
  s: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,i?0:l.length-e.length),e=l;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?Ze(e):
813
813
  ks(e);if(a&&(c=Q(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return bo(this,e)}cmov(e,n,r){return pn(r,"condition"),r?n:e}};Object.
814
- freeze(go.prototype);function vo(t,e={}){return new go(t,e)}var yo=BigInt(0),Is=BigInt(1);function Eu(t,e){let n=e.negate();return t?n:e}function xo(t,e){let n=bo(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function Pu(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
814
+ freeze(go.prototype);function vo(t,e={}){return new go(t,e)}var yo=BigInt(0),_s=BigInt(1);function Eu(t,e){let n=e.negate();return t?n:e}function xo(t,e){let n=bo(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function Pu(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
815
815
  throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ts(t,e){Pu(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=pu(t),s=BigInt(t);return {windows:n,windowSize:r,mask:i,maxNumber:o,
816
- shiftBy:s}}function Cu(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+=Is);let l=e*r,u=l+Math.abs(a)-1,d=a===0,p=a<0,h=e%2!==0;return {nextN:c,offset:u,isZero:d,
817
- isNeg:p,isNegF:h,offsetF:l}}var Rs=new WeakMap,Iu=new WeakMap;function Ps(t){return Iu.get(t)||1}function Tu(t){if(t!==yo)throw new Error("invalid wNAF")}var ko=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
818
- e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>yo;)n&Is&&(r=r.add(o)),o=o.double(),n>>=Is;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Ts(n,this.bits),i=[],
816
+ shiftBy:s}}function Cu(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+=_s);let l=e*r,u=l+Math.abs(a)-1,d=a===0,p=a<0,h=e%2!==0;return {nextN:c,offset:u,isZero:d,
817
+ isNeg:p,isNegF:h,offsetF:l}}var Rs=new WeakMap,_u=new WeakMap;function Ps(t){return _u.get(t)||1}function Tu(t){if(t!==yo)throw new Error("invalid wNAF")}var ko=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
818
+ e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>yo;)n&_s&&(r=r.add(o)),o=o.double(),n>>=_s;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Ts(n,this.bits),i=[],
819
819
  s=e,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)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,
820
820
  s=Ts(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:p,offsetF:h}=Cu(r,a,s);r=c,u?i=i.add(Eu(p,n[h])):o=o.add(Eu(d,n[l]));}return Tu(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.
821
821
  ZERO){let i=Ts(e,this.bits);for(let s=0;s<i.windows&&r!==yo;s++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Cu(r,s,i);if(r=a,!l){let d=n[c];o=o.add(u?d.negate():d);}}return Tu(r),o}getPrecomputes(e,n,r){let o=Rs.
822
822
  get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Rs.set(n,o))),o}cached(e,n,r){let o=Ps(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Ps(
823
- e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){Pu(n,this.bits),Iu.set(e,n),Rs.delete(e);}hasCache(e){return Ps(e)!==1}};function Ru(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Su(e),e}else return vo(t,{isLE:n})}function _u(t,e,n={},r){if(r===void 0&&(r=t==="edwar\
823
+ e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){Pu(n,this.bits),_u.set(e,n),Rs.delete(e);}hasCache(e){return Ps(e)!==1}};function Ru(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Su(e),e}else return vo(t,{isLE:n})}function Iu(t,e,n={},r){if(r===void 0&&(r=t==="edwar\
824
824
  ds"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of ["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>yo))throw new Error(`CURVE.${c} must be positive bigint`)}
825
825
  let o=Ru(e.p,n.Fp,r),i=Ru(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.
826
- freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function Du(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var ht=BigInt(0),se=BigInt(1),_s=BigInt(2),Lh=BigInt(8);function Mh(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={}){
827
- let n=e,r=_u("edwards",t,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;Bt(n,{},{uvRatio:"function"});let c=_s<<BigInt(i.BYTES*8)-se,l=m=>o.create(m),u=n.uvRatio===void 0?(m,g)=>{try{return {isValid:!0,value:o.
828
- sqrt(o.div(m,g))}}catch{return {isValid:false,value:ht}}}:n.uvRatio;if(!Mh(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(m,g,b=false){let y=b?se:ht;return ws("coordinate "+m,
826
+ freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function Du(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var ht=BigInt(0),se=BigInt(1),Is=BigInt(2),$h=BigInt(8);function Nh(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={}){
827
+ let n=e,r=Iu("edwards",t,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;Bt(n,{},{uvRatio:"function"});let c=Is<<BigInt(i.BYTES*8)-se,l=m=>o.create(m),u=n.uvRatio===void 0?(m,g)=>{try{return {isValid:!0,value:o.
828
+ sqrt(o.div(m,g))}}catch{return {isValid:false,value:ht}}}:n.uvRatio;if(!Nh(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(m,g,b=false){let y=b?se:ht;return ws("coordinate "+m,
829
829
  g,y,c),g}function p(m){if(!(m instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,se,l(s.Gx*s.Gy));static ZERO=new h(ht,se,se,ht);static Fp=o;static Fn=i;X;Y;Z;T;constructor(g,b,y,v){
830
830
  this.X=d("x",g),this.Y=d("y",b),this.Z=d("z",y,true),this.T=d("t",v),Object.freeze(this);}static CURVE(){return s}static fromAffine(g){if(g instanceof h)throw new Error("extended point not allowed");let{
831
831
  x:b,y}=g||{};return d("x",b),d("y",y),new h(b,y,se,l(b*y))}static fromBytes(g,b=false){let y=o.BYTES,{a:v,d:x}=s;g=Yn(ne(g,y,"point")),pn(b,"zip215");let E=Yn(g),S=g[y-1];E[y-1]=S&-129;let C=Ze(E),A=b?c:
832
832
  o.ORDER;ws("point.y",C,ht,A);let T=l(C*C),R=l(T-se),M=l(x*T-v),{isValid:w,value:P}=u(R,M);if(!w)throw new Error("bad point: invalid y coordinate");let $=(P&se)===se,O=(S&128)!==0;if(!b&&P===ht&&O)throw new Error(
833
833
  "bad point: x=0 and x_0=1");return O!==$&&(P=l(-P)),h.fromAffine({x:P,y:C})}static fromHex(g,b=false){return h.fromBytes(au(g),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,b=true){
834
- return f.createCache(this,g),b||this.multiply(_s),this}assertValidity(){let g=this,{a:b,d:y}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:v,Y:x,Z:E,T:S}=g,C=l(v*v),A=l(x*x),T=l(E*E),R=l(T*T),
834
+ return f.createCache(this,g),b||this.multiply(Is),this}assertValidity(){let g=this,{a:b,d:y}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:v,Y:x,Z:E,T:S}=g,C=l(v*v),A=l(x*x),T=l(E*E),R=l(T*T),
835
835
  M=l(C*b),w=l(T*l(M+A)),P=l(R+l(y*l(C*A)));if(w!==P)throw new Error("bad point: equation left != right (1)");let $=l(v*x),O=l(E*S);if($!==O)throw new Error("bad point: equation left != right (2)")}equals(g){
836
836
  p(g);let{X:b,Y:y,Z:v}=this,{X:x,Y:E,Z:S}=g,C=l(b*S),A=l(x*v),T=l(y*S),R=l(E*v);return C===A&&T===R}is0(){return this.equals(h.ZERO)}negate(){return new h(l(-this.X),this.Y,this.Z,l(-this.T))}double(){
837
- let{a:g}=s,{X:b,Y:y,Z:v}=this,x=l(b*b),E=l(y*y),S=l(_s*l(v*v)),C=l(g*x),A=b+y,T=l(l(A*A)-x-E),R=C+E,M=R-S,w=C-E,P=l(T*M),$=l(R*w),O=l(T*w),D=l(M*R);return new h(P,$,D,O)}add(g){p(g);let{a:b,d:y}=s,{X:v,
837
+ let{a:g}=s,{X:b,Y:y,Z:v}=this,x=l(b*b),E=l(y*y),S=l(Is*l(v*v)),C=l(g*x),A=b+y,T=l(l(A*A)-x-E),R=C+E,M=R-S,w=C-E,P=l(T*M),$=l(R*w),O=l(T*w),D=l(M*R);return new h(P,$,D,O)}add(g){p(g);let{a:b,d:y}=s,{X:v,
838
838
  Y:x,Z:E,T:S}=this,{X:C,Y:A,Z:T,T:R}=g,M=l(v*C),w=l(x*A),P=l(S*y*R),$=l(E*T),O=l((v+x)*(C+A)-M-w),D=$-P,F=$+P,j=l(w-b*M),q=l(O*D),J=l(F*j),Y=l(O*j),B=l(D*F);return new h(q,J,B,Y)}subtract(g){return p(g),
839
839
  this.add(g.negate())}multiply(g){if(!i.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:y}=f.cached(this,g,v=>xo(h,v));return xo(h,[b,y])[0]}multiplyUnsafe(g){
840
840
  if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===ht?h.ZERO:this.is0()||g===se?this:f.unsafe(this,g,b=>xo(h,b))}isSmallOrder(){return this.clearCofactor().
841
- is0()}isTorsionFree(){return f.unsafe(this,s.n).is0()}toAffine(g){let b=this,y=g,{X:v,Y:x,Z:E}=b,S=b.is0();y==null&&(y=S?Lh:o.inv(E));let C=l(v*y),A=l(x*y),T=o.mul(E,y);if(S)return {x:ht,y:se};if(T!==se)
841
+ is0()}isTorsionFree(){return f.unsafe(this,s.n).is0()}toAffine(g){let b=this,y=g,{X:v,Y:x,Z:E}=b,S=b.is0();y==null&&(y=S?$h:o.inv(E));let C=l(v*y),A=l(x*y),T=o.mul(E,y);if(S)return {x:ht,y:se};if(T!==se)
842
842
  throw new Error("invZ was invalid");return {x:C,y:A}}clearCofactor(){return a===se?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:b}=this.toAffine(),y=o.toBytes(b);return y[y.length-1]|=g&se?128:0,y}toHex(){
843
843
  return ys(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let f=new ko(h,i.BITS);return i.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var wo=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){
844
844
  this.ep=e;}static fromBytes(e){Es();}static fromHex(e){Es();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){
@@ -857,64 +857,64 @@ B,Re,ee;try{B=t.fromBytes($,F),Re=t.fromBytes(J,F),ee=s.multiplyUnsafe(Y);}catch
857
857
  is0()}let S=a.BYTES,C={secretKey:S,publicKey:S,signature:2*S,seed:S};function A(w){return w=w===void 0?d(C.seed):w,ne(w,C.seed,"seed")}function T(w){return mo(w)&&w.length===C.secretKey}function R(w,P){
858
858
  try{return !!t.fromBytes(w,P===void 0?x.zip215:P)}catch{return false}}let M={getExtendedPublicKey:g,randomSecretKey:A,isValidSecretKey:T,isValidPublicKey:R,toMontgomery(w){let{y:P}=t.fromBytes(w),$=C.publicKey,
859
859
  O=$===32;if(!O&&$!==57)throw new Error("only defined for 25519 and 448");let D=O?a.div(se+P,se-P):a.div(P-se,P+se);return a.toBytes(D)},toMontgomerySecret(w){let P=C.secretKey;ne(w,P);let $=r(w.subarray(
860
- 0,P));return p($).subarray(0,P)}};return Object.freeze(C),Object.freeze(M),Object.freeze({keygen:Du(A,b),getPublicKey:b,sign:v,verify:E,utils:M,Point:t,lengths:C})}var jh=BigInt(0),Qe=BigInt(1),Mu=BigInt(2);var Bh=BigInt(5),zh=BigInt(8),fn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ms={p:fn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:zh,
860
+ 0,P));return p($).subarray(0,P)}};return Object.freeze(C),Object.freeze(M),Object.freeze({keygen:Du(A,b),getPublicKey:b,sign:v,verify:E,utils:M,Point:t,lengths:C})}var zh=BigInt(0),Qe=BigInt(1),Mu=BigInt(2);var Fh=BigInt(5),qh=BigInt(8),fn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ms={p:fn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:qh,
861
861
  a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
862
- c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Fh(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=fn,a=t*t%
863
- i*t%i,c=Ae(a,Mu,i)*a%i,l=Ae(c,Qe,i)*t%i,u=Ae(l,Bh,i)*l%i,d=Ae(u,e,i)*u%i,p=Ae(d,n,i)*d%i,h=Ae(p,r,i)*p%i,f=Ae(h,o,i)*h%i,m=Ae(f,o,i)*h%i,g=Ae(m,e,i)*u%i;return {pow_p_5_8:Ae(g,Mu,i)*t%i,b2:a}}function qh(t){
864
- return t[0]&=248,t[31]&=127,t[31]|=64,t}var As=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function $s(t,e){let n=fn,r=Q(e*e*e,n),o=Q(r*r*e,n),i=Fh(t*o).pow_p_5_8,
865
- s=Q(t*r*i,n),a=Q(e*s*s,n),c=s,l=Q(s*As,n),u=a===t,d=a===Q(-t,n),p=a===Q(-t*As,n);return u&&(s=c),(d||p)&&(s=l),Xe(s,n)&&(s=Q(-s,n)),{isValid:u||d,value:s}}var bt=Au(Ms,{uvRatio:$s}),gt=bt.Fp,ju=bt.Fn;function Uh(t){return Ou(bt,uo,Object.assign({adjustScalarBytes:qh,zip215:true},t))}var Bu=Uh({});var Os=As;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Hh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
866
- "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var $u=t=>$s(Qe,t),Kh=BigInt("0x7\
867
- fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ls=t=>gt.create(Ze(t)&Kh);var vt=class t extends wo{static BASE=new t(
862
+ c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Uh(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=fn,a=t*t%
863
+ i*t%i,c=Ae(a,Mu,i)*a%i,l=Ae(c,Qe,i)*t%i,u=Ae(l,Fh,i)*l%i,d=Ae(u,e,i)*u%i,p=Ae(d,n,i)*d%i,h=Ae(p,r,i)*p%i,f=Ae(h,o,i)*h%i,m=Ae(f,o,i)*h%i,g=Ae(m,e,i)*u%i;return {pow_p_5_8:Ae(g,Mu,i)*t%i,b2:a}}function Vh(t){
864
+ return t[0]&=248,t[31]&=127,t[31]|=64,t}var As=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function $s(t,e){let n=fn,r=Q(e*e*e,n),o=Q(r*r*e,n),i=Uh(t*o).pow_p_5_8,
865
+ s=Q(t*r*i,n),a=Q(e*s*s,n),c=s,l=Q(s*As,n),u=a===t,d=a===Q(-t,n),p=a===Q(-t*As,n);return u&&(s=c),(d||p)&&(s=l),Xe(s,n)&&(s=Q(-s,n)),{isValid:u||d,value:s}}var bt=Au(Ms,{uvRatio:$s}),gt=bt.Fp,ju=bt.Fn;function Hh(t){return Ou(bt,uo,Object.assign({adjustScalarBytes:Vh,zip215:true},t))}var Bu=Hh({});var Os=As;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Gh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
866
+ "1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var $u=t=>$s(Qe,t),Yh=BigInt("0x7\
867
+ fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ls=t=>gt.create(Ze(t)&Yh);var vt=class t extends wo{static BASE=new t(
868
868
  bt.BASE);static ZERO=new t(bt.ZERO);static Fp=gt;static Fn=ju;constructor(e){super(e);}static fromAffine(e){return new t(bt.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoP\
869
869
  oint expected")}init(e){return new t(e)}static fromBytes(e){De(e,32);let{a:n,d:r}=Ms,o=fn,i=x=>gt.create(x),s=Ls(e);if(!du(gt.toBytes(s),e)||Xe(s,o))throw new Error("invalid ristretto255 encoding 1");
870
- let a=i(s*s),c=i(Qe+n*a),l=i(Qe-n*a),u=i(c*c),d=i(l*l),p=i(n*r*u-d),{isValid:h,value:f}=$u(i(p*d)),m=i(f*l),g=i(f*m*p),b=i((s+s)*m);Xe(b,o)&&(b=i(-b));let y=i(c*g),v=i(b*y);if(!h||Xe(v,o)||y===jh)throw new Error(
870
+ let a=i(s*s),c=i(Qe+n*a),l=i(Qe-n*a),u=i(c*c),d=i(l*l),p=i(n*r*u-d),{isValid:h,value:f}=$u(i(p*d)),m=i(f*l),g=i(f*m*p),b=i((s+s)*m);Xe(b,o)&&(b=i(-b));let y=i(c*g),v=i(b*y);if(!h||Xe(v,o)||y===zh)throw new Error(
871
871
  "invalid ristretto255 encoding 2");return new t(new bt(b,y,Qe,v))}static fromHex(e){return t.fromBytes(Gn(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,i=fn,s=g=>gt.create(g),a=s(s(r+n)*s(r-n)),c=s(e*n),
872
- l=s(c*c),{value:u}=$u(s(a*l)),d=s(u*a),p=s(u*c),h=s(d*p*o),f;if(Xe(o*h,i)){let g=s(n*Os),b=s(e*Os);e=g,n=b,f=s(d*Hh);}else f=p;Xe(e*h,i)&&(n=s(-n));let m=s((r-n)*f);return Xe(m,i)&&(m=s(-m)),gt.toBytes(
872
+ l=s(c*c),{value:u}=$u(s(a*l)),d=s(u*a),p=s(u*c),h=s(d*p*o),f;if(Xe(o*h,i)){let g=s(n*Os),b=s(e*Os);e=g,n=b,f=s(d*Gh);}else f=p;Xe(e*h,i)&&(n=s(-n));let m=s((r-n)*f);return Xe(m,i)&&(m=s(-m)),gt.toBytes(
873
873
  m)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:i}=e.ep,s=l=>gt.create(l),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(vt.BASE);Object.freeze(
874
874
  vt.ZERO);Object.freeze(vt.prototype);Object.freeze(vt);function zu(t){if(t.plan!=="measure"||typeof t.measure_expires_at!="number"||!Number.isFinite(t.measure_expires_at))return t;let e=typeof t.measure_grace_days=="number"&&Number.isFinite(t.measure_grace_days)?
875
875
  t.measure_grace_days:0;return {...t,expires_at:t.measure_expires_at,grace_days:Math.max(0,e)}}var So=`-----BEGIN PUBLIC KEY-----
876
876
  MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
877
877
  -----END PUBLIC KEY-----`;function Fu(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 Ns(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.
878
- length%4?"=".repeat(4-e.length%4):"";return Fu(e+n)}function Yh(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Fu(e);return n.subarray(n.length-32)}var Zh=new TextEncoder,qu=new TextDecoder;
879
- function js(t){return typeof t=="object"&&t!==null&&"keys"in t}function yt(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 Xh=/^[A-Za-z0-9_-]+$/;
880
- function Uu(t){let e=t.split(".");return e.length===3&&e.every(n=>Xh.test(n))}function Xn(t){return t===""?"empty":Uu(t)?"token":"malformed"}function Qn(t,e){if(!Uu(t))return {ok:false,reason:"malformed t\
878
+ length%4?"=".repeat(4-e.length%4):"";return Fu(e+n)}function Xh(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Fu(e);return n.subarray(n.length-32)}var Qh=new TextEncoder,qu=new TextDecoder;
879
+ function js(t){return typeof t=="object"&&t!==null&&"keys"in t}function yt(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 eg=/^[A-Za-z0-9_-]+$/;
880
+ function Uu(t){let e=t.split(".");return e.length===3&&e.every(n=>eg.test(n))}function Xn(t){return t===""?"empty":Uu(t)?"token":"malformed"}function Qn(t,e){if(!Uu(t))return {ok:false,reason:"malformed t\
881
881
  oken"};let n=t.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(qu.decode(Ns(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(js(e)){let u=typeof s.kid=="string"?s.kid:e.defaultKid,
882
- d=e.keys[u];if(!d)return {ok:false,reason:`unknown key id "${u}"`};a=d;}else {if(!e)return {ok:false,reason:"no verification key"};a=e;}let c;try{if(c=Yh(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
883
- return {ok:false,reason:"invalid public key"}}let l=false;try{l=Bu.verify(Ns(i),Zh.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:s,payloadBytes:Ns(o)}:
882
+ d=e.keys[u];if(!d)return {ok:false,reason:`unknown key id "${u}"`};a=d;}else {if(!e)return {ok:false,reason:"no verification key"};a=e;}let c;try{if(c=Xh(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
883
+ return {ok:false,reason:"invalid public key"}}let l=false;try{l=Bu.verify(Ns(i),Qh.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:s,payloadBytes:Ns(o)}:
884
884
  {ok:false,reason:"bad signature"}}function kt(t,e){let n=Qn(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{let r=JSON.parse(qu.decode(n.payloadBytes));return {
885
885
  signatureValid:!0,payload:zu(r)}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function er(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=
886
886
  t.expires_at?"active":e<=r?"grace":"expired"}function Vu(t,e,n={}){let r=yt(t);if(Xn(r)==="empty")return {status:"none",reason:"empty"};let i=kt(r,e);if(!i.signatureValid||!i.payload)return {status:"inv\
887
- alid",...i.reason?{reason:i.reason}:{}};let s=i.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),c=er(s,a,n.revoked);return c==="revoked"?{status:c,payload:s,reason:"license revoked"}:{status:c,payload:s}}var Hu="BVSALA-REVOC",Qh=300,eg=new TextDecoder;function Eo(t,e,n={}){let r=l=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:l}),o=Qn(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
888
- if(o.header?.typ!==Hu)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${Hu})`);let i;try{i=JSON.parse(eg.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
887
+ alid",...i.reason?{reason:i.reason}:{}};let s=i.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),c=er(s,a,n.revoked);return c==="revoked"?{status:c,payload:s,reason:"license revoked"}:{status:c,payload:s}}var Hu="BVSALA-REVOC",tg=300,ng=new TextDecoder;function Eo(t,e,n={}){let r=l=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:l}),o=Qn(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
888
+ if(o.header?.typ!==Hu)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${Hu})`);let i;try{i=JSON.parse(ng.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
889
889
  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.
890
- nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??Qh;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 xt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
890
+ nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??tg;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 xt=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
891
891
  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.
892
892
  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&&
893
893
  (this._asOf=e.asOf),r||o}};function mn(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=yt(t),s=Xn(i),a=s==="token"?kt(i,e):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,l=new Set(
894
894
  c?.plan==="measure"?[]:c?.features??[]),u=()=>{if(s==="empty")return "none";if(!c)return "invalid";let p=er(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(p==="active"||p==="grace")){let h=c.
895
895
  expires_at+c.grace_days*86400,f=Math.min(o,h),m=Math.max(n.revocation.lastContactAt,f);if(r()-m>n.maxStalenessSeconds)return "stale"}return p},d=()=>{let p=u();return p==="active"||p==="grace"};return {
896
- isEntitled:p=>d()&&l.has(p),isActive:()=>d(),status:u,reason:()=>c?void 0:a.reason,plan:()=>c&&d()?c.plan:void 0,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}function Co(t,e,n){return mn(t,e,{revocation:new xt,...n?{now:n}:{}})}var hn={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Wu=3,tg=12;function Bs(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
896
+ isEntitled:p=>d()&&l.has(p),isActive:()=>d(),status:u,reason:()=>c?void 0:a.reason,plan:()=>c&&d()?c.plan:void 0,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}function Co(t,e,n){return mn(t,e,{revocation:new xt,...n?{now:n}:{}})}var hn={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Wu=3,rg=12;function Bs(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
897
897
  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:
898
- 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 ng=10,gn=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;lastEtag=null;consecutive304=0;now(){
898
+ 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 og=10,gn=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;lastEtag=null;consecutive304=0;now(){
899
899
  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();
900
900
  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"});
901
901
  return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??hn.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"application/json"};this.lastEtag&&(i["\
902
902
  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?.(
903
- {type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=ng&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.ok)throw new Error(`revocat\
903
+ {type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=og&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.ok)throw new Error(`revocat\
904
904
  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 l=Eo(c.list,this.opts.publicKeyPem,{minSeq:this.
905
905
  opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??hn.maxSkewSeconds});if(!l.ok){let d=l.reason??"rejected";this.opts.onEvent?.({type:"rejected",reason:d}),this.avisar(`r\
906
906
  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}.`);
907
907
  return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let u=this.opts.snapshot.apply(l);this.opts.onEvent?.(u?{type:"applied",seq:l.seq,size:this.opts.snapshot.snapshot().size}:{type:"\
908
908
  unchanged",seq:l.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.
909
909
  silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||Ee(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;let n=this.consecutiveFailures;if(n<Wu||(n-Wu)%
910
- tg!==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\
910
+ rg!==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\
911
911
  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)
912
912
  return;let e=Bs({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??hn.floorSeconds,pollIntervalSeconds:this.
913
913
  opts.pollIntervalSeconds??hn.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??hn.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??hn.jitterRatio,...this.opts.random?{random:this.
914
914
  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.
915
915
  controller?.abort();}};var Ft=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=
916
916
  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){let n=this.now();this.buffer.push({report:e,at:n});
917
- let r=rg(e);r&&this.buffer.push({report:r,at:n}),this.buffer.length>this.maxBuffer&&this.buffer.splice(0,this.buffer.length-this.maxBuffer),this.buffer.length>=this.maxBatch&&this.flush();}start(){this.
917
+ let r=ig(e);r&&this.buffer.push({report:r,at:n}),this.buffer.length>this.maxBuffer&&this.buffer.splice(0,this.buffer.length-this.maxBuffer),this.buffer.length>=this.maxBatch&&this.flush();}start(){this.
918
918
  timer||(this.timer=setInterval(()=>{this.flush();},this.flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async stopAndDrain(e){this.timer&&
919
919
  (clearInterval(this.timer),this.timer=void 0);let n=e??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.
920
920
  length>=i?r+1:0,r>=2)break}}async flush(){if(this.inflight)return this.inflight;if(this.buffer.length!==0){this.inflight=this.hacerFlush();try{await this.inflight;}finally{this.inflight=null;}}}async hacerFlush(){
@@ -930,59 +930,59 @@ buffer],this.buffer.length>this.maxBuffer&&(this.buffer.length=this.maxBuffer);}
930
930
  {},requestId:n.requestId,model:n.model,at:e.at,avoidedLlm:n.calls.avoidedLlm,actualLlm:n.calls.actualLlm,baselineInputTokens:n.tokens.baselineInput,actualInputTokens:n.tokens.actualInput,eliminatedInputTokens:n.
931
931
  tokens.eliminatedInput,compressedInputTokens:n.tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutputTokens:n.tokens.actualOutput,providerCachedInputTokens:n.tokens.providerCachedInput??
932
932
  0,cacheResult:n.cache.result,...n.cost.eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.
933
- cost.eliminatedInputFloorCost}:{},...og(n),baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{},...n.cost.basis==="referen\
933
+ cost.eliminatedInputFloorCost}:{},...sg(n),baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{},...n.cost.basis==="referen\
934
934
  ce"&&n.cache.reference&&/^[A-Za-z0-9._:/-]{1,128}$/.test(n.cache.reference.requestId)&&Number.isInteger(n.cache.reference.at)?{referenceRequestId:n.cache.reference.requestId,referenceAt:n.cache.reference.
935
- at}:{},...n.attribution?.sessionId?{sessionId:n.attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function rg(t){let e=t.measure;if(!e)return null;let n=e.wouldHaveSaved.
935
+ at}:{},...n.attribution?.sessionId?{sessionId:n.attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function ig(t){let e=t.measure;if(!e)return null;let n=e.wouldHaveSaved.
936
936
  usd;if(!(Number.isFinite(n)&&n>0))return null;let r=`${t.requestId}:shadow`;if(!/^[A-Za-z0-9._:/-]{1,128}$/.test(r))return null;let o=Math.max(0,t.cost.actual),i=Math.max(0,o-n),s=o>0?Math.min(1,(o-i)/
937
- o):0,{measure:a,nativeSavings:c,...l}=t;return {...l,requestId:r,cache:{...t.cache,result:"miss"},cost:{baselineEstimate:o,actual:i,netSavings:s,netSavingsRatio:s,netSavingsUsd:o-i,basis:"shadow"}}}function og(t){
937
+ o):0,{measure:a,nativeSavings:c,...l}=t;return {...l,requestId:r,cache:{...t.cache,result:"miss"},cost:{baselineEstimate:o,actual:i,netSavings:s,netSavingsRatio:s,netSavingsUsd:o-i,basis:"shadow"}}}function sg(t){
938
938
  let e=t.nativeSavings;if(!e||e.basis!=="measured")return {};let n=r=>Number.isFinite(r)&&r>=0;return !n(e.readDiscountUsd)||!n(e.writePremiumUsd)?{}:!(e.readDiscountUsd>0)&&!(e.writePremiumUsd>0)?{}:{...e.
939
- readDiscountUsd>0?{nativeCacheReadSavings:e.readDiscountUsd}:{},...e.writePremiumUsd>0?{nativeCacheWritePremium:e.writePremiumUsd}:{}}}function To(){return globalThis.process}function ig(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\
940
- ]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function sg(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??
941
- t.NETLIFY)}async function ag(){if(To()?.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 cg(t,e=ag){
942
- if(t.KUBERNETES_SERVICE_HOST||sg(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||ig(n)))return n}async function lg(){let t=To();if(!t||!t.env)return;let e=t.env,n=await cg(e),r=[t.platform,
943
- 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 ug=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
939
+ readDiscountUsd>0?{nativeCacheReadSavings:e.readDiscountUsd}:{},...e.writePremiumUsd>0?{nativeCacheWritePremium:e.writePremiumUsd}:{}}}function To(){return globalThis.process}function ag(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\
940
+ ]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function cg(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??
941
+ t.NETLIFY)}async function lg(){if(To()?.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 ug(t,e=lg){
942
+ if(t.KUBERNETES_SERVICE_HOST||cg(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||ag(n)))return n}async function dg(){let t=To();if(!t||!t.env)return;let e=t.env,n=await ug(e),r=[t.platform,
943
+ 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 pg=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
944
944
  ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function tr(){let t=To()?.env;if(!t)
945
- return false;for(let e of ug){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function dg(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
945
+ return false;for(let e of pg){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function fg(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
946
946
  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}\
947
- |${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 nr(t){let n=To()?.env?.BVSALA_SEAT_ID;if(n&&pg.test(n))return n;let r=await lg();
948
- if(!r)return;let o=await dg(t,r);if(o)return `m-${o.slice(0,32)}`}var pg=/^[A-Za-z0-9._:/-]{1,128}$/;var Gu={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function Ro(t){return {exactCache:t.exactCache??new Er,semanticCache:t.semanticCacheStore??t.semanticCache,singleflight:t.singleflight??new Cr,resolvers:t.resolvers??kc(),router:t.router??new Dr,toolSelector:t.
947
+ |${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 nr(t){let n=To()?.env?.BVSALA_SEAT_ID;if(n&&mg.test(n))return n;let r=await dg();
948
+ if(!r)return;let o=await fg(t,r);if(o)return `m-${o.slice(0,32)}`}var mg=/^[A-Za-z0-9._:/-]{1,128}$/;var Gu={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function Ro(t){return {exactCache:t.exactCache??new Er,semanticCache:t.semanticCacheStore??t.semanticCache,singleflight:t.singleflight??new Cr,resolvers:t.resolvers??kc(),router:t.router??new Dr,toolSelector:t.
949
949
  toolSelector??new Lr,formatSelector:t.formatSelector??new jr({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new Br,constraintBackends:t.constraintBackends??[]}}function G(t){let e=t.maxOutputTokens,n=t.response?.maxOutputTokens;return e==null?n??void 0:n==null?e:Math.min(e,n)}function zs(t){let e=t.response?.maxOutputTokens??256,n=t.maxOutputTokens;return n==
950
950
  null?e:Math.min(e,n)}function Fs(t){let e=t.maxOutputTokens;if(e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<=0))throw new TypeError(`[bvsala] request.maxOutputTokens must be a positive int\
951
951
  eger (got ${String(e)}).`)}var Te=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\
952
952
  ted before any provider request was sent"),this.name="StreamAbortedError",this.requestSent=e;}},Po=class extends Error{job;notSubmitted;constructor(e,n,r,o){super(e,o),this.name="BatchSubmitError",this.
953
- job=n,this.notSubmitted=r;}};var fg={"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.\
953
+ job=n,this.notSubmitted=r;}};var hg={"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.\
954
954
  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\
955
955
  .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,
956
956
  "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-sonnet-5-5":true,"claude-fable-5":true,"claude-fa\
957
957
  ble-5-1":true,"claude-mythos-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-fla\
958
958
  sh":true,"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},
959
- mg=new Set(["claude-opus-4-7","claude-opus-4-8"]),hg=[/^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($|[-_.])/,
960
- /^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Ku(t){let e=t.lastIndexOf("/"),n=(e>=0?t.slice(e+1):t).toLowerCase();if(hg.some(i=>i.test(n)))return "reasoning-model";let r=Qt(t);if(r===void 0)
961
- return "unclassified-model";let o=fg[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(mg.has(r))return "temperature-ignored"}var qs={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},Ju={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},gg=[["claude-fable-5-1",512],["claude-mytho\
959
+ gg=new Set(["claude-opus-4-7","claude-opus-4-8"]),bg=[/^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($|[-_.])/,
960
+ /^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Ku(t){let e=t.lastIndexOf("/"),n=(e>=0?t.slice(e+1):t).toLowerCase();if(bg.some(i=>i.test(n)))return "reasoning-model";let r=Qt(t);if(r===void 0)
961
+ return "unclassified-model";let o=hg[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(gg.has(r))return "temperature-ignored"}var qs={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},Ju={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},vg=[["claude-fable-5-1",512],["claude-mytho\
962
962
  s-5-1",512],["claude-fable-5",512],["claude-mythos-5",512],["claude-opus-5-5",512],["claude-opus-5",512],["claude-sonnet-5-5",512],["claude-opus-4-7",2048],["claude-opus-4-6",4096],["claude-opus-4-5",
963
- 4096],["claude-haiku-4-5",4096],["claude-3-5-haiku",2048]];function Us(t){for(let[e,n]of gg)if(t===e||t.startsWith(`${e}-`))return {...Ju,minimumCacheTokens:n};return Ju}var Vs={minimumCacheTokens:1024,
964
- cacheReadMultiplier:.1,cacheWriteMultiplier:1};var Yu={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function Io(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,
965
- n)),c=a*i*r.cacheReadMultiplier+(1-a)*i*r.cacheWriteMultiplier;return s+c}function Hs(t){let e=Io(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=Io(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??
963
+ 4096],["claude-haiku-4-5",4096],["claude-3-5-haiku",2048]];function Us(t){for(let[e,n]of vg)if(t===e||t.startsWith(`${e}-`))return {...Ju,minimumCacheTokens:n};return Ju}var Vs={minimumCacheTokens:1024,
964
+ cacheReadMultiplier:.1,cacheWriteMultiplier:1};var Yu={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function _o(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,
965
+ n)),c=a*i*r.cacheReadMultiplier+(1-a)*i*r.cacheWriteMultiplier;return s+c}function Hs(t){let e=_o(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=_o(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??
966
966
  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}\
967
967
  < ${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*
968
968
  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\
969
969
  es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function Zu(t){let e=o=>Hs({...t,prefixHitRate:o}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,
970
- 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 bg(t){let e=Zu({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(Io(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.
971
- totalTokens?null:1)}var _o=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-
972
- 1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=bg(n),o=this.estados.get(e),i=vg(o);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:r,observada:i}:r==null?
970
+ 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 yg(t){let e=Zu({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(_o(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.
971
+ totalTokens?null:1)}var Io=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-
972
+ 1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=yg(n),o=this.estados.get(e),i=kg(o);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:r,observada:i}:r==null?
973
973
  {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 ${bn(i)} did not reach the ${bn(
974
974
  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 \
975
975
  is only observable on requests that were marked`,umbral:r,observada:i}:i!=null&&i>r?{marcar:true,razon:`measured hit rate ${bn(i)} beats the ${bn(r)} break-even`,umbral:r,observada:i}:(o.apagada=true,{marcar:false,
976
976
  razon:`prefix-cache marking OFF: measured hit rate ${bn(i)} did not reach the ${bn(r)} break-even, so marking was costing money`,umbral:r,observada:i})}registrar(e,n){let r=this.estados.get(e)??{marcadas:0,
977
- 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 vg(t){
978
- if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function bn(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var yg={anthropic:"explicit",openai:"automatic",google:"implicit",unknown:"unknown"};function Ws(t){return Math.round(t*1e10)/1e10}function Xu(t,e,n){let r=Math.max(0,n.leidos),o=Math.max(0,n.escritos),
977
+ 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 kg(t){
978
+ if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function bn(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var xg={anthropic:"explicit",openai:"automatic",google:"implicit",unknown:"unknown"};function Ws(t){return Math.round(t*1e10)/1e10}function Xu(t,e,n){let r=Math.max(0,n.leidos),o=Math.max(0,n.escritos),
979
979
  i=Math.min(o,Math.max(0,n.escritos1h));if(r===0&&o===0)return;let a=Ot(t)??"unknown",c=Ne(t),l=qn(t),u=e.cachedInputPer1k,d=n.contadorCompleto&&u!==void 0&&Number.isFinite(u),p=u??e.inputPer1k,h=d?r/1e3*
980
- Math.max(0,e.inputPer1k-p):0,f=d?(o-i)/1e3*e.inputPer1k*Math.max(0,c-1)+i/1e3*e.inputPer1k*Math.max(0,l-1):0;return {provider:a,mechanism:yg[a],...n.marcadoPorLaCapa!==void 0?{layerMarked:n.marcadoPorLaCapa}:
980
+ Math.max(0,e.inputPer1k-p):0,f=d?(o-i)/1e3*e.inputPer1k*Math.max(0,c-1)+i/1e3*e.inputPer1k*Math.max(0,l-1):0;return {provider:a,mechanism:xg[a],...n.marcadoPorLaCapa!==void 0?{layerMarked:n.marcadoPorLaCapa}:
981
981
  {},cacheReadTokens:r,cacheWriteTokens:o,cacheWrite1hTokens:i,inputPer1k:e.inputPer1k,cachedInputPer1k:p,writeMultiplier:c,write1hMultiplier:l,readDiscountUsd:Ws(h),writePremiumUsd:Ws(f),netUsd:Ws(h-f),
982
982
  basis:d?"measured":"unmeasured"}}var vn={"5m":3e5,"30m":18e5,"1h":36e5},Oe=["5m","30m","1h"],td=20;function Qu(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.
983
983
  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 ed(t){
984
- return Qu(t,0).toString(36)+"."+Qu(t,2654435769).toString(36)}function kg(t){let e=t.toolCalls?.length?t.toolCalls.map(r=>`${r.id??""}${r.name}${r.arguments}`).join(""):"",n=t.isError===true?"error":
985
- "";return `${t.role}${t.name??""}${t.toolCallId??""}${e}${t.content}${n}`}function nd(t,e){let n=[ed(`bvsala-prefijo\0${t}`)];for(let r of e)n.push(ed(`${n[n.length-1]}${kg(r)}`));return n}function Ao(t){
984
+ return Qu(t,0).toString(36)+"."+Qu(t,2654435769).toString(36)}function wg(t){let e=t.toolCalls?.length?t.toolCalls.map(r=>`${r.id??""}${r.name}${r.arguments}`).join(""):"",n=t.isError===true?"error":
985
+ "";return `${t.role}${t.name??""}${t.toolCallId??""}${e}${t.content}${n}`}function nd(t,e){let n=[ed(`bvsala-prefijo\0${t}`)];for(let r of e)n.push(ed(`${n[n.length-1]}${wg(r)}`));return n}function Ao(t){
986
986
  let e=0;for(;e<t.length&&t[e].role==="system";)e+=1;return e}function Gs(){return {"5m":0,"30m":0,"1h":0}}function Ks(){return {"5m":{resueltas:0,reutilizadas:0,tardias:0},"30m":{resueltas:0,reutilizadas:0,
987
987
  tardias:0},"1h":{resueltas:0,reutilizadas:0,tardias:0}}}var Do=1,rd=1440*6e4;function Qs(t){return `bvsala:cache-breakpoints:v${Do}:${t}`}var kn=class{clases=new Map;porHuella=new Map;maxPorClase;maxClases;prediccionesMinimas;confirmacionMinima;memoria;constructor(e={}){
988
988
  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??
@@ -1034,20 +1034,20 @@ t.tramo.cacheReadMultiplier),r=t.estadistica.T,o=t.estadistica.H,i=(a,c,l)=>Xs(a
1034
1034
  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:`\
1035
1035
  provider default kept: continued ${r.k30m}/${r.muestras30m} within 30 min, not clearly below the ${yn(n)} break-even`,equilibrio:n};let s=!t.hayHistorial||!i(o.k30m,o.muestras30m,o.pendientes30m);return {
1036
1036
  explicita:true,historial:s,razon:`explicit mode: continued only ${r.k30m}/${r.muestras30m} within 30 min (break-even ${yn(n)}), so the question is not written; breakpoint at the ${s?"end of the stable h\
1037
- istory":"system header"}`,equilibrio:n}}function yn(t){return `${(t*100).toFixed(1)}%`}var sd=.5;function xg(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function wg(t){return 1-t}function Sg(t,e=sd){return e-t}function ad(t,e,n=sd){
1038
- if(!t||!e)return null;let r=xg(t,e);if(r==null||!Number.isFinite(r))return null;let o=wg(r),i=Sg(r,n),s=i>0,a=c=>`${(c*100).toFixed(1)}%`;return {r,equilibrio:o,escaladoMaximo:i,viable:s,razon:s?`the c\
1037
+ istory":"system header"}`,equilibrio:n}}function yn(t){return `${(t*100).toFixed(1)}%`}var sd=.5;function Sg(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function Eg(t){return 1-t}function Cg(t,e=sd){return e-t}function ad(t,e,n=sd){
1038
+ if(!t||!e)return null;let r=Sg(t,e);if(r==null||!Number.isFinite(r))return null;let o=Eg(r),i=Cg(r,n),s=i>0,a=c=>`${(c*100).toFixed(1)}%`;return {r,equilibrio:o,escaladoMaximo:i,viable:s,razon:s?`the c\
1039
1039
  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\
1040
1040
  o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var ea={"gpt-4":"gpt-4o","gpt-4-turbo":"gpt-4o-mini","gpt-4o":"gpt-4o-mini","gpt-4.1":"gpt-4.1-mini","cla\
1041
- ude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-5-sonnet":"claude-3-5-haiku"};function Eg(t){return Object.keys(t).sort((e,n)=>n.length-e.length||e.localeCompare(n))}function cd(t,e=ea){
1042
- 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]??Cg(o,e);return !i||i===o?null:r+i}function Cg(t,e){for(let n of Eg(e))if(t.startsWith(n)&&t.charAt(
1041
+ ude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-5-sonnet":"claude-3-5-haiku"};function Tg(t){return Object.keys(t).sort((e,n)=>n.length-e.length||e.localeCompare(n))}function cd(t,e=ea){
1042
+ 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]??Rg(o,e);return !i||i===o?null:r+i}function Rg(t,e){for(let n of Tg(e))if(t.startsWith(n)&&t.charAt(
1043
1043
  n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var Oo=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(
1044
- e)}decidir(e,n){let r=this.estados.get(e),o=Tg(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\
1044
+ e)}decidir(e,n){let r=this.estados.get(e),o=Pg(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\
1045
1045
  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}\
1046
1046
  ); 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(
1047
1047
  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)}\
1048
1048
  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,
1049
- n&&(r.escaladas+=1),this.estados.set(e,r);}};function Tg(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var Rg=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function Pg(t){return t?ta(t)?"value-constrained":"structural":"none"}function ta(t,e=0){if(e>12)return false;let n=t;
1050
- for(let r of Rg)if(n[r]!==void 0)return true;if(t.properties){for(let r of Object.values(t.properties))if(ta(r,e+1))return true}return !!(t.items&&ta(t.items,e+1))}function ld(t){let e=Pg(t.schema),n=(t.tools??
1049
+ n&&(r.escaladas+=1),this.estados.set(e,r);}};function Pg(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var _g=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function Ig(t){return t?ta(t)?"value-constrained":"structural":"none"}function ta(t,e=0){if(e>12)return false;let n=t;
1050
+ for(let r of _g)if(n[r]!==void 0)return true;if(t.properties){for(let r of Object.values(t.properties))if(ta(r,e+1))return true}return !!(t.items&&ta(t.items,e+1))}function ld(t){let e=Ig(t.schema),n=(t.tools??
1051
1051
  []).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\
1052
1052
  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\
1053
1053
  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 \
@@ -1058,43 +1058,43 @@ Tokens",comprobaciones:e};if(e.push("output-contract"),!t.schema)return {acepta:
1058
1058
  motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=be(n,t.schema);return r.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
1059
1059
  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 ud(t,e){let n,r;try{n=
1060
1060
  JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=Lo(n),i=Lo(r);return o.length===0&&i.length===0?{divergen:false,motivo:"no comparab\
1061
- le facts (free prose only)"}:_g(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 \
1062
- of a false valid \u2014 it is a reason to look, never a verdict"}}var Ig=40;function Lo(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\
1063
- an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=Ig&&n.push(`s:${r.toLowerCase()}`);}else if(Array.isArray(t))for(let r of t)Lo(r,e+1,n);else if(t&&typeof t=="objec\
1064
- t")for(let r of Object.keys(t).sort())Lo(t[r],e+1,n);return n.sort()}function _g(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 dd="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\
1065
- , because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function Dg(t){if(t<=0)return "";let e=dd;for(;e.length<t;)e+=dd;return e.slice(
1066
- 0,t)}function Ag(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 ra(t){if(t.enum&&t.enum.length>0)return {valor:Ag(t.enum)};switch(t.type??(t.properties?
1067
- "object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:Dg(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?
1061
+ le facts (free prose only)"}:Ag(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 \
1062
+ of a false valid \u2014 it is a reason to look, never a verdict"}}var Dg=40;function Lo(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\
1063
+ an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=Dg&&n.push(`s:${r.toLowerCase()}`);}else if(Array.isArray(t))for(let r of t)Lo(r,e+1,n);else if(t&&typeof t=="objec\
1064
+ t")for(let r of Object.keys(t).sort())Lo(t[r],e+1,n);return n.sort()}function Ag(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 dd="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\
1065
+ , because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function Og(t){if(t<=0)return "";let e=dd;for(;e.length<t;)e+=dd;return e.slice(
1066
+ 0,t)}function Lg(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 ra(t){if(t.enum&&t.enum.length>0)return {valor:Lg(t.enum)};switch(t.type??(t.properties?
1067
+ "object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:Og(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?
1068
1068
  {valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=ra(t.items);return n?{valor:Array.from({length:t.maxItems},()=>n.valor)}:void 0}case "ob\
1069
- ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let i=ra(o);if(!i)return;n[r]=i.valor;}return {valor:n}}default:return}}function Og(t){let e=ra(
1070
- t);return e?JSON.stringify(e.valor):null}function pd(t,e){let n=Og(t);return n===null?null:e(n)}var Mo=16,fd=64,Lg=8,Mg="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 md(t,e,n,r={}){
1071
- let o=r.minimumSavingsTokens??Lg,i;try{if(sa(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};i=ca(t,0);}catch(R){return {applied:false,reason:R instanceof
1069
+ ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let i=ra(o);if(!i)return;n[r]=i.valor;}return {valor:n}}default:return}}function Mg(t){let e=ra(
1070
+ t);return e?JSON.stringify(e.valor):null}function pd(t,e){let n=Mg(t);return n===null?null:e(n)}var Mo=16,fd=64,$g=8,Ng="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 md(t,e,n,r={}){
1071
+ let o=r.minimumSavingsTokens??$g,i;try{if(sa(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};i=ca(t,0);}catch(R){return {applied:false,reason:R instanceof
1072
1072
  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;
1073
- if(!s)return {applied:false,reason:"nothing to compact"};let a=R=>xn(R,s,true),c=R=>xn(R,s,false),l=Fg(t),u=$g(t,i.compact,s,l);if(!u.ok)return {applied:false,reason:u.reason};let d=e(JSON.stringify(t)),p=e(JSON.stringify(
1073
+ if(!s)return {applied:false,reason:"nothing to compact"};let a=R=>xn(R,s,true),c=R=>xn(R,s,false),l=Ug(t),u=jg(t,i.compact,s,l);if(!u.ok)return {applied:false,reason:u.reason};let d=e(JSON.stringify(t)),p=e(JSON.stringify(
1074
1074
  i.compact)),h=d-p,f=Number.POSITIVE_INFINITY;for(let R of l){let M=e(JSON.stringify(R))-e(JSON.stringify(a(R)));M<f&&(f=M);}Number.isFinite(f)||(f=0);let m=R=>R/1e3*n.inputPer1k,g=R=>R/1e3*n.outputPer1k,
1075
1075
  b=m(o),y=n.outputPer1k>0?(o-h)*n.inputPer1k/n.outputPer1k:Number.NEGATIVE_INFINITY,v=Number.isFinite(y)?y.toFixed(1):"any",x=n.inputPer1k>0?`${(n.outputPer1k/n.inputPer1k).toFixed(1)}x`:"more than",E=r.
1076
1076
  evidencia;if(E==null)return {applied:false,reason:`no measured output delta for this model, so the codebook is not applied. Short field names change how much the model WRITES, and that is a property of th\
1077
- e model, not of the schema: ${Mg}. Here the compact contract saves ${h} input tokens and output is billed ${x} input, so it only pays while the output delta stays above ${v} tokens. Measure yours (ben\
1077
+ e model, not of the schema: ${Ng}. Here the compact contract saves ${h} input tokens and output is billed ${x} input, so it only pays while the output delta stays above ${v} tokens. Measure yours (ben\
1078
1078
  chmarks/ab-live.ts) and pass it in`};let S=E.deltaTokens;if(S<0)return {applied:false,reason:`the measured output delta is ${S} tokens: this model writes MORE from a compact contract (${E.procedencia}). T\
1079
1079
  he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${x} input, so no schema is big enough to buy it back`};let C=m(h)+g(S),A=n.inputPer1k>0?C*1e3/
1080
1080
  n.inputPer1k:h,T=`+${S} tokens (${S>0?"the model wrote LESS":"no measured change"}), ${E.procedencia}`;return C<b?{applied:false,reason:`net saving $${C.toFixed(9)}/request is below the floor of ${o} inp\
1081
1081
  ut tokens ($${b.toFixed(9)}): the compact contract saves ${h} input tokens and the measured output delta is ${T}; break-even at ${v}`}:{applied:true,reason:`net saving $${C.toFixed(9)}/request (${A.toFixed(
1082
1082
  1)} input tokens equivalent): the compact contract saves ${h} input tokens and the measured output delta is ${T}; break-even at ${v}`,plan:{compactSchema:i.compact,expand:c,compact:a,renamedKeys:i.renamed,
1083
1083
  codedEnumValues:i.coded,schemaTokensOriginal:d,schemaTokensCompact:p,modelledShapeSavingTokens:f,measuredOutputDeltaTokens:S,outputDeltaProvenance:E.procedencia,breakEvenOutputDeltaTokens:y,netSavingUsd:C}}}
1084
- function $g(t,e,n,r){for(let o of r){if(!be(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let i=xn(o,n,true);if(!be(i,e).valid)return {
1084
+ function jg(t,e,n,r){for(let o of r){if(!be(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let i=xn(o,n,true);if(!be(i,e).valid)return {
1085
1085
  ok:false,reason:"compact witness does not validate against the compact schema"};if(!aa(xn(i,n,false),o))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function hd(t){return t.type==="ob\
1086
- ject"||t.type==null&&t.properties!=null}function gd(t){return t.type==="array"||t.type==null&&t.items!=null}function Ng(t){let e=t.enum;return !e||e.length===0||e.length>fd||!e.every(n=>typeof n=="stri\
1087
- ng")?null:e}function ca(t,e){if(e>Mo)throw new RangeError("schema too deep");let n=Ng(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=bd(n,true);if(!r)return {compact:t,renamed:0,
1086
+ ject"||t.type==null&&t.properties!=null}function gd(t){return t.type==="array"||t.type==null&&t.items!=null}function Bg(t){let e=t.enum;return !e||e.length===0||e.length>fd||!e.every(n=>typeof n=="stri\
1087
+ ng")?null:e}function ca(t,e){if(e>Mo)throw new RangeError("schema too deep");let n=Bg(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=bd(n,true);if(!r)return {compact:t,renamed:0,
1088
1088
  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,
1089
- enumBack:i},renamed:0,coded:o}}return hd(t)?jg(t,e):gd(t)?Bg(t,e):{compact:t,renamed:0,coded:0}}function jg(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};
1089
+ enumBack:i},renamed:0,coded:o}}return hd(t)?zg(t,e):gd(t)?Fg(t,e):{compact:t,renamed:0,coded:0}}function zg(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};
1090
1090
  let r=0,o=0,i=new Map,s=new Map;for(let[p,h]of n){let f=ca(h,e+1);s.set(p,f.compact),f.node&&i.set(p,f.node),r+=f.renamed,o+=f.coded;}let a=null;t.additionalProperties===false&&(a=bd(n.map(([p])=>p),false));
1091
1091
  let c={};for(let[p]of n)c[a?.get(p)??p]=s.get(p);let l={...t,properties:c};t.required&&(l.required=t.required.map(p=>a?.get(p)??p));let u={};if(a){let p=new Map;for(let[f,m]of a)p.set(m,f);let h=false;for(let[
1092
- f,m]of a)f!==m&&(h=true);if(h){u.keysFwd=a,u.keysBack=p;for(let[f,m]of a)f!==m&&(r+=1);}}i.size>0&&(u.props=i);let d=!u.keysFwd&&!u.props;return {compact:l,...d?{}:{node:u},renamed:r,coded:o}}function Bg(t,e){
1092
+ f,m]of a)f!==m&&(h=true);if(h){u.keysFwd=a,u.keysBack=p;for(let[f,m]of a)f!==m&&(r+=1);}}i.size>0&&(u.props=i);let d=!u.keysFwd&&!u.props;return {compact:l,...d?{}:{node:u},renamed:r,coded:o}}function Fg(t,e){
1093
1093
  if(!t.items)return {compact:t,renamed:0,coded:0};let n=ca(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function bd(t,e){let n=[
1094
1094
  ...t].sort(),r=new Set,o=new Map;n.forEach((s,a)=>{let c=e?s.toUpperCase():s,l=s;for(let u=1;u<s.length;u++){let d=c.slice(0,u);if(!r.has(d)){l=d;break}}if(l===s){let u=a.toString(36);u.length<s.length&&
1095
1095
  !r.has(u)&&(l=u);}r.add(l),o.set(s,l);});let i=new Set(t);for(let[s,a]of o)if(a!==s&&i.has(a))return null;return o}function xn(t,e,n){let r=n?e.enumFwd:e.enumBack;if(r&&typeof t=="string")return r.get(t)??
1096
- t;if(e.items&&Array.isArray(t))return t.map(i=>xn(i,e.items,n));let o=n?e.keysFwd:e.keysBack;if((o||e.props)&&zg(t)){let i={};for(let[s,a]of Object.entries(t)){let c=o?.get(s)??s,l=n?s:c,u=e.props?.get(
1097
- l);i[c]=u?xn(a,u,n):a;}return i}return t}function zg(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Fg(t){let e=Math.min(fd,Math.max(1,oa(t,0))),n=[];for(let r=0;r<e;r++)n.push(ia(t,
1096
+ t;if(e.items&&Array.isArray(t))return t.map(i=>xn(i,e.items,n));let o=n?e.keysFwd:e.keysBack;if((o||e.props)&&qg(t)){let i={};for(let[s,a]of Object.entries(t)){let c=o?.get(s)??s,l=n?s:c,u=e.props?.get(
1097
+ l);i[c]=u?xn(a,u,n):a;}return i}return t}function qg(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ug(t){let e=Math.min(fd,Math.max(1,oa(t,0))),n=[];for(let r=0;r<e;r++)n.push(ia(t,
1098
1098
  r,0));return n}function oa(t,e){if(e>Mo)return 0;let n=t.enum?.length??0;for(let r of Object.values(t.properties??{}))n=Math.max(n,oa(r,e+1));return t.items&&(n=Math.max(n,oa(t.items,e+1))),n}function ia(t,e,n){
1099
1099
  if(n>Mo)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(hd(t)){let r={};for(let[o,i]of Object.entries(t.properties??{}))r[o]=ia(i,e,n+1);return r}if(gd(t)){if(t.maxItems===
1100
1100
  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?ia(i,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";
@@ -1102,16 +1102,16 @@ let r=Math.max(1,t.minLength??1),o=t.maxLength!=null?Math.min(r,t.maxLength):r;r
1102
1102
  "integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function sa(t,e){if(e>Mo)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.
1103
1103
  values(t.properties??{}))if(sa(n,e+1))return true;return !!(t.items&&sa(t.items,e+1))}function aa(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.
1104
1104
  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(!aa(t[s],e[s]))return false;return true}let o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)
1105
- return false;for(let s of o)if(!Object.prototype.hasOwnProperty.call(e,s)||!aa(t[s],e[s]))return false;return true}var qg="2026-08-14",vd={"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 \
1106
- enums)",pares:8}},Ug=ci(vd);function Vg(t){return ai(vd,Ug,t)}var $o=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&&
1105
+ return false;for(let s of o)if(!Object.prototype.hasOwnProperty.call(e,s)||!aa(t[s],e[s]))return false;return true}var Vg="2026-08-14",vd={"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 \
1106
+ enums)",pares:8}},Hg=ci(vd);function Wg(t){return ai(vd,Hg,t)}var $o=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&&
1107
1107
  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,
1108
- origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let i=Vg(e);return i?{deltaTokens:i.deltaTokens,origen:"catalogue",procedencia:`measured by Bi\
1109
- Velio on ${e} (${qg}, ${i.pares} paired reps, ${i.contrato}, ${i.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};var ua="[BiVelio Savings: an older tool result was trimmed here to lower the cost; the most recent results travel in full.]",Hg=new TextEncoder;function Wg(t){return Hg.encode(t).length}function Gg(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;
1108
+ origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let i=Wg(e);return i?{deltaTokens:i.deltaTokens,origen:"catalogue",procedencia:`measured by Bi\
1109
+ Velio on ${e} (${Vg}, ${i.pares} paired reps, ${i.contrato}, ${i.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};var ua="[BiVelio Savings: an older tool result was trimmed here to lower the cost; the most recent results travel in full.]",Gg=new TextEncoder;function Kg(t){return Gg.encode(t).length}function Jg(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;
1110
1110
  r=la(o);}catch{r=n;}return `${t} ${r}`}function la(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(la).join(",")}]`:`{${Object.keys(t).sort().map(n=>`${JSON.stringify(
1111
1111
  n)}:${la(t[n])}`).join(",")}}`}function yd(t){let e=new Map,n=new Map;for(let l of t)if(l.role==="assistant"&&l.toolCalls)for(let u of l.toolCalls)u.id&&(e.set(u.id,u.arguments),n.set(u.id,u.name));let r=[],
1112
- o=new Map;for(let l=0;l<t.length;l++){let u=t[l];if(u.role!=="tool")continue;r.push(l);let d=(u.toolCallId?n.get(u.toolCallId):void 0)??u.name,p=u.toolCallId?e.get(u.toolCallId):void 0,h=Gg(d,p);h!==null&&
1112
+ o=new Map;for(let l=0;l<t.length;l++){let u=t[l];if(u.role!=="tool")continue;r.push(l);let d=(u.toolCallId?n.get(u.toolCallId):void 0)??u.name,p=u.toolCallId?e.get(u.toolCallId):void 0,h=Jg(d,p);h!==null&&
1113
1113
  o.set(l,h);}let i=r.length?r[r.length-1]:-1,s=new Map;for(let l of r){let u=o.get(l);if(u===void 0)continue;let d=s.get(u);(d===void 0||l>d)&&s.set(u,l);}let a=[],c=0;for(let l of r){if(l===i)continue;let u=o.
1114
- get(l);if(u===void 0||s.get(u)===l)continue;let d=Wg(t[l].content);d<1024||(a.push(l),c+=d);}return {indices:a,bytesOriginales:c}}function kd(t,e){if(e.length===0)return t;let n=new Set(e);return t.map(
1114
+ get(l);if(u===void 0||s.get(u)===l)continue;let d=Kg(t[l].content);d<1024||(a.push(l),c+=d);}return {indices:a,bytesOriginales:c}}function kd(t,e){if(e.length===0)return t;let n=new Set(e);return t.map(
1115
1115
  (r,o)=>n.has(o)?{...r,content:ua}:r)}function No(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"?qs:o==="anthropic"?Us(i):
1116
1116
  o==="google"||o==="google-vertex"?Vs:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(i)?qs:i.startsWith("claude")?Us(i):i.startsWith("gemini")?Vs:Yu}function xd(t){let e=t.prefix!=null,n=Hs({originalTokens:t.originalTokens,
1117
1117
  compressedTokens:t.compressedTokens,stablePrefixTokens:t.prefix?.stableTokens??0,prefixHitRate:t.prefix?.hitRate??0,tier:t.tier,...t.compressorCostTokens!=null?{compressorCostTokens:t.compressorCostTokens}:
@@ -1123,26 +1123,26 @@ ompt and the probe`:l="the gain does not cover the cost of degrading: if the pro
1123
1123
  costeDeDosLlamadas:i,ganancia:s,perdidaSiDegrada:a,razon:l}}function Ed(t){let n=(t.description??(Array.isArray(t.intents)?t.intents.join("; "):"")).trim().split(/\r?\n/,1)[0]??"",r=n.length>wd?n.slice(
1124
1124
  0,wd-1).trimEnd()+"\u2026":n;return {id:t.id,intents:t.intents,risk:t.risk,...r?{description:r}:{}}}var wd=200;function Cd(t,e,n){let r=new Map(e.map(c=>[c.id,c])),o=[],i=[],s=new Set;for(let c of t){let l=r.
1125
1125
  get(c);if(!l){i.push(c);continue}o.includes(l.id)||(o.push(l.id),l.risk==="read"&&s.size<Math.max(0,n)&&s.add(l.id));}return {tools:e.filter(c=>c.risk!=="read"||s.has(c.id)),reconocidos:o,ignorados:i}}function Td(t,e){
1126
- 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 Jg=2;function ma(t){return X(de({messages:t.messages,structuredData:t.structuredData??null,tools:t.tools??[],schema:t.response?.schema??null}))}function Rd(t){return t.temperature===0}var wt=t=>typeof t==
1127
- "number"&&Number.isInteger(t)&&t>=0;function Yg(t,e){if(wt(t.reasoningTokens)){if(!e)return t.reasoningTokens;if(wt(e.reasoningTokens))return t.reasoningTokens+e.reasoningTokens}}function Pd(t){if(t.contadorSimulado)
1126
+ 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 Zg=2;function ma(t){return X(de({messages:t.messages,structuredData:t.structuredData??null,tools:t.tools??[],schema:t.response?.schema??null}))}function Rd(t){return t.temperature===0}var wt=t=>typeof t==
1127
+ "number"&&Number.isInteger(t)&&t>=0;function Xg(t,e){if(wt(t.reasoningTokens)){if(!e)return t.reasoningTokens;if(wt(e.reasoningTokens))return t.reasoningTokens+e.reasoningTokens}}function Pd(t){if(t.contadorSimulado)
1128
1128
  return "simulated-provider";if(t.origen==="no-oficial")return "unofficial-origin";let e=t.usoPrimario;if(!e||e.complete===false||!wt(e.inputTokens)||e.inputTokens<=0||!wt(e.outputTokens))return "no-usage";let n=t.
1129
- usoReparacion;if(n&&(n.complete===false||!wt(n.outputTokens)))return "no-usage";if(t.eliminatedInput!==0||t.compressedInput!==0||t.elididoLocal!==0||Math.abs(t.sentLocalSinSondeo-t.baselineInput)>Jg)return "\
1129
+ usoReparacion;if(n&&(n.complete===false||!wt(n.outputTokens)))return "no-usage";if(t.eliminatedInput!==0||t.compressedInput!==0||t.elididoLocal!==0||Math.abs(t.sentLocalSinSondeo-t.baselineInput)>Zg)return "\
1130
1130
  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.
1131
1131
  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!==
1132
- t.modeloPedido)return "cheaper-model-served";if(!t.cacheable)return "not-cacheable";let r=Gi(t.tierServido),o=r?.conDescuento&&r.factor!=null&&r.factor>0&&r.factor<1?r.factor:void 0,i=Yg(e,n);return {v:2,
1132
+ t.modeloPedido)return "cheaper-model-served";if(!t.cacheable)return "not-cacheable";let r=Gi(t.tierServido),o=r?.conDescuento&&r.factor!=null&&r.factor>0&&r.factor<1?r.factor:void 0,i=Xg(e,n);return {v:2,
1133
1133
  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.
1134
1134
  max(0,t.mensajesDeLaCapa)+Math.max(0,t.piezasDelAdaptador)+(t.hayEsquema?1:0),...i!==void 0?{reasoningTokens:i}:{},requestFingerprint:t.huella(),textSha256:X(t.textoServido)}}var jo=t=>typeof t=="stri\
1135
- ng"&&t.length>0;function Id(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,
1135
+ ng"&&t.length>0;function _d(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,
1136
1136
  o=n.reasoningTokens;return n.v===2&&typeof n.inputTokens=="number"&&Number.isInteger(n.inputTokens)&&n.inputTokens>0&&wt(n.outputTokens)&&typeof n.at=="number"&&Number.isFinite(n.at)&&(r===void 0||typeof r==
1137
1137
  "number"&&r>0&&r<1)&&wt(n.layerInsertions)&&(o===void 0||wt(o))&&jo(n.requestId)&&jo(n.model)&&jo(n.requestFingerprint)&&jo(n.textSha256)?{v:2,requestId:n.requestId,at:n.at,model:n.model,inputTokens:n.
1138
1138
  inputTokens,outputTokens:n.outputTokens,...r!==void 0?{tierFactor:r}:{},layerInsertions:n.layerInsertions,...o!==void 0?{reasoningTokens:o}:{},requestFingerprint:n.requestFingerprint,textSha256:n.textSha256,
1139
- ...typeof n.cacheKey=="string"?{cacheKey:n.cacheKey}:{}}:"malformed"}function Zg(t,e){if(!e.determinista)return "sampled";if(e.salidaDelModelo!==void 0)return e.salidaDelModelo;if(t.reasoningTokens===void 0)
1140
- return "reasoning-not-reported";if(t.reasoningTokens!==0)return "reasoning-reported"}function _d(t,e){if(e.textoServidoSha256!==t.textSha256)return {ok:false,reason:"witness"};if(e.claveLeida!==void 0&&t.cacheKey!==
1139
+ ...typeof n.cacheKey=="string"?{cacheKey:n.cacheKey}:{}}:"malformed"}function Qg(t,e){if(!e.determinista)return "sampled";if(e.salidaDelModelo!==void 0)return e.salidaDelModelo;if(t.reasoningTokens===void 0)
1140
+ return "reasoning-not-reported";if(t.reasoningTokens!==0)return "reasoning-reported"}function Id(t,e){if(e.textoServidoSha256!==t.textSha256)return {ok:false,reason:"witness"};if(e.claveLeida!==void 0&&t.cacheKey!==
1141
1141
  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,
1142
1142
  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\
1143
1143
  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"};
1144
1144
  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,
1145
- a=Zg(t,e),c=a===void 0?Math.floor(.95*Math.min(t.outputTokens,s)):0,l=Math.min(1,t.tierFactor??1,e.diferible?Gc:1);return {ok:true,...a!==void 0?{outputNotCredited:a}:{},credit:{requestId:t.requestId,at:t.
1145
+ a=Qg(t,e),c=a===void 0?Math.floor(.95*Math.min(t.outputTokens,s)):0,l=Math.min(1,t.tierFactor??1,e.diferible?Gc:1);return {ok:true,...a!==void 0?{outputNotCredited:a}:{},credit:{requestId:t.requestId,at:t.
1146
1146
  at,inputTokens:t.inputTokens,outputTokens:t.outputTokens,creditedInputTokens:i,creditedOutputTokens:c,cachedInputPer1k:o,outputPer1k:r.outputPer1k,tierFactor:l}}}var rr={done:true,value:void 0},or=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){
1147
1147
  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);},
1148
1148
  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.
@@ -1156,176 +1156,181 @@ return;let n=this.esperas.shift();n?n.resolve({done:false,value:e}):this.cola.pu
1156
1156
  esperas.splice(0);if(n){n.reject(e);for(let o of r)o.resolve(rr);}else this.errorPendiente={valor:e};}siguiente(){if(this.consumidorSalio)return Promise.resolve(rr);let e=this.cola.shift();if(e)return Promise.
1157
1157
  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(rr):new Promise((n,r)=>{this.esperas.
1158
1158
  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(),
1159
- this.consumidorSalio=true,this.cola.length=0,Promise.resolve(rr))}}};function Xg(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===
1160
- "fail_open"?"fail_open":"provider"}}function Qg(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!==
1159
+ this.consumidorSalio=true,this.cola.length=0,Promise.resolve(rr))}}};function e0(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===
1160
+ "fail_open"?"fail_open":"provider"}}function t0(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!==
1161
1161
  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 Dd(t){let e=t.
1162
- hechos,n=Xg(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,
1162
+ hechos,n=e0(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,
1163
1163
  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\
1164
1164
  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.
1165
1165
  finishReason}:{},...i?.finishReasonDetail!==void 0?{finishReasonDetail:i.finishReasonDetail}:{},capSetByCaller:s!=null,...s!=null?{outputLimit:s}:{}};}if(n==="exact_cache")r.cacheMatch={kind:"exact",...t.
1166
1166
  ageMs!==void 0?{ageMs:t.ageMs}:{}};else if(n==="semantic_cache"&&e?.semantico){let i=e.semantico;r.cacheMatch={kind:"semantic",ageMs:i.ageMs,similarity:i.similarity,similarityFloor:i.similarityFloor,acceptFloor:i.
1167
- acceptFloor,...i.verifierRan?{verifierScore:i.verifierScore}:{},embedder:i.embedder,factGuard:"passed",...i.calibration?{calibration:{...i.calibration}}:{}};}let o=Qg(t.cascada);return o&&(r.cascade=o),
1167
+ acceptFloor,...i.verifierRan?{verifierScore:i.verifierScore}:{},embedder:i.embedder,factGuard:"passed",...i.calibration?{calibration:{...i.calibration}}:{}};}let o=t0(t.cascada);return o&&(r.cascade=o),
1168
1168
  r}function Ad(t){return {source:"coalesced",sharedFrom:t==null?"provider":t.source==="coalesced"?t.sharedFrom??"provider":t.source,...t?.schema?{schema:{...t.schema}}:{},...t?.repair?{repair:{...t.repair}}:
1169
- {},...t?.truncation?{truncation:{...t.truncation}}:{},...t?.cacheMatch?{cacheMatch:e0(t.cacheMatch)}:{},...t?.cascade?{cascade:{...t.cascade}}:{}}}function e0(t){return t.kind==="semantic"&&t.calibration?
1169
+ {},...t?.truncation?{truncation:{...t.truncation}}:{},...t?.cacheMatch?{cacheMatch:n0(t.cacheMatch)}:{},...t?.cascade?{cascade:{...t.cascade}}:{}}}function n0(t){return t.kind==="semantic"&&t.calibration?
1170
1170
  {...t,calibration:{...t.calibration}}:{...t}}var zo="https://savings.bivelio.com/dashboard/account",Od=["semantic_cache","deterministic_resolvers","format_selection","compression","context_elision","tool_result_elision","model_cascade","output_c\
1171
1171
  odebook","prompt_cache_placement","deferred_tier"],Ld=`[bvsala] Measure license: the layer is running in SHADOW mode. Every request goes to your provider exactly as you built it and nothing is served \
1172
1172
  from any cache; \`report.measure.wouldHaveSaved\` shows what the levers would have saved (a lower bound, never billed). To turn the levers on, upgrade to a paid plan at ${zo} - the layer picks up the \
1173
- new license by itself (with \`serviceAccountKey\` and \`licenseServerUrl\`) or on restart.`,t0=1e4,Bo=class{constructor(e=t0){this.max=e;}max;vistas=new Map;enVuelo=new Map;vista(e,n){let r=this.vistas.
1173
+ new license by itself (with \`serviceAccountKey\` and \`licenseServerUrl\`) or on restart.`,r0=1e4,Bo=class{constructor(e=r0){this.max=e;}max;vistas=new Map;enVuelo=new Map;vista(e,n){let r=this.vistas.
1174
1174
  get(e);return r===void 0?false:n>r?(this.vistas.delete(e),false):true}anotar(e,n){for(this.vistas.delete(e),this.vistas.set(e,n);this.vistas.size>this.max;){let r=this.vistas.keys().next().value;if(r===void 0)
1175
1175
  break;this.vistas.delete(r);}}hayEnVuelo(e){return (this.enVuelo.get(e)??0)>0}entrar(e){this.enVuelo.set(e,(this.enVuelo.get(e)??0)+1);}salir(e){let n=(this.enVuelo.get(e)??0)-1;n<=0?this.enVuelo.delete(
1176
1176
  e):this.enVuelo.set(e,n);}tamano(){return this.vistas.size}};function Md(t){return Math.round(t*1e10)/1e10}var ba="i(?:'m| am)? ?(?:"+["can't","cannot","can not","won't","will not","shouldn't","should not","unable to","not able to","not going to","not in a position to","not comfortable","don't feel comfort\
1177
1177
  able","do not feel comfortable","'d rather not","would rather not","don't think i can","do not think i can"].join("|")+")",ha="(?:much|many times|happy|glad|grateful|excited|thankful|proud|sorry|impor\
1178
- tant|good|great|amazing|nice|relieved|pleased|delighted|impressed|helpful|useful|valuable|lucky|blessed|thrilled|fun|cool|beautiful|wonderful)",n0=`(?:help(?! but| feeling| thinking| noticing| wonderi\
1178
+ tant|good|great|amazing|nice|relieved|pleased|delighted|impressed|helpful|useful|valuable|lucky|blessed|thrilled|fun|cool|beautiful|wonderful)",o0=`(?:help(?! but| feeling| thinking| noticing| wonderi\
1179
1179
  ng| laughing| smiling| myself| it(?![\\p{L}]))|assist|provide|comply|fulfil|fulfill|create|write|generate|produce|give|share|support|engage|participate|answer|respond|discuss|offer|continue|draft|facil\
1180
1180
  itate|contribute|go along|go into|walk you through|explain how|describe how(?! ${ha})|tell you how(?! ${ha})|teach|instruct|encourage|condone|endorse|promote|role-?play|pretend|do that|do this|do so|w\
1181
1181
  ith that|with this|with your request|with this request|that request|this request|determine|identify(?! any| anything| a single| no )|know|access|disclose|reveal|divulge|verify|confirm|locate|find(?! a\
1182
1182
  ny| anything| a single| no | nothing| it in me)|find out|track|trace|guess|predict|diagnose|recommend(?![^.!?]{0,60}enough)|prescribe|advise|look up|retrieve|obtain|browse|search|speculate|infer|asses\
1183
- s|evaluate|comment on|speak to|give out|dox|tell (?:you )?(?:whether|if))`,r0="i(?:'ll| will| must| need to|'d| would)?(?: have to)? ?(?:respectfully |politely )?decline",o0="(?:(?:that|this|it)(?:'s|\
1183
+ s|evaluate|comment on|speak to|give out|dox|tell (?:you )?(?:whether|if))`,i0="i(?:'ll| will| must| need to|'d| would)?(?: have to)? ?(?:respectfully |politely )?decline",s0="(?:(?:that|this|it)(?:'s|\
1184
1184
  is) not something i(?:'m| am)? ?(?:can|will|able to|comfortable)|(?:it|that|this)(?:'s| is| would be| would not be| wouldn't be) (?:not )?(?:appropriate|ethical|responsible) for me to|i(?:'m| am) not\
1185
- sure (?:that )?it(?:'s| is| would be) appropriate)",i0="(?:(?:i'm |i am |i'm really |i am really |i'm so |really |so )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettably|i'm afraid\
1186
- |i am afraid|as an ai|as a language model|as an assistant|i understand|i appreciate|thank you for|thanks for|while i understand|while i appreciate)",k="\\p{L}*",Nd="no (?:puedo|voy a|me es posible|est\
1187
- oy en condiciones de|me siento c\xF3mod[oa])",s0=`(?:ayudar${k}|asistir${k}|proporcionar${k}|facilitar${k}|dar${k}|ofrecer${k}|crear${k}|escribir${k}|generar${k}|compartir${k}|cumplir|responder${k}|co\
1188
- laborar|participar|atender${k}|hacer eso|hacerlo|con eso|con esto|con esa|con esta|con tu|determinar${k}|identificar${k}|saber${k}|acceder|revelar${k}|divulgar${k}|verificar${k}|confirmar${k}|localiza\
1189
- r${k}|rastrear${k}|adivinar${k}|predecir${k}|diagnosticar${k}|recomendar${k}(?![^.!?]{0,60}suficiente)|recetar${k}|aconsejar${k})`,a0="(?:lo siento|lo lamento|siento|lamento|disculpa|disculpe|perd\xF3n|p\
1190
- erdona|lamentablemente|desafortunadamente|me temo que|como (?:una )?(?:ia|inteligencia artificial|modelo de lenguaje|asistente)|entiendo)",jd="no (?:puc|et puc|us puc|em sento c\xF2mod[ea]|estic en condi\
1191
- cions de)",c0=`(?:ajudar${k}|assistir${k}|proporcionar${k}|facilitar${k}|donar${k}|oferir${k}|crear${k}|escriure${k}|generar${k}|compartir${k}|complir|respondre${k}|col\xB7laborar|participar|fer aix\xF2|fer\
1192
- -ho|amb aix\xF2|amb aquesta|amb la teva|determinar${k}|identificar${k}|saber${k}|accedir|revelar${k}|divulgar${k}|verificar${k}|confirmar${k}|localitzar${k}|rastrejar${k}|endevinar${k}|predir${k}|diag\
1193
- nosticar${k}|recomanar${k}(?![^.!?]{0,60}prou)|receptar${k}|aconsellar${k})`,l0="(?:ho sento|ho lamento|em sap greu|disculpa|disculpeu|perdona|malauradament|lamentablement|dissortadament|com a (?:ia|i\
1194
- ntel\xB7lig\xE8ncia artificial|model de llenguatge|assistent)|entenc)",Bd="(?:je ne (?:peux|pourrai|pourrais|vais|souhaite)(?: malheureusement)? pas|je ne suis pas en mesure d[e']|je refuse d[e'])",u0="\
1195
- (?:aider|assister|fournir|r\xE9pondre|cr\xE9er|\xE9crire|g\xE9n\xE9rer|partager|donner|proposer|participer|expliquer comment|acc\xE9der \xE0|satisfaire|faire cela|faire \xE7a|le faire|d\xE9terminer|identifier|savoir|divulguer|r\
1196
- \xE9v\xE9ler|v\xE9rifier|confirmer|localiser|retrouver|deviner|pr\xE9dire|diagnostiquer|prescrire|conseiller|recommander(?![^.!?]{0,60}assez))",d0="(?:d\xE9sol\xE9e?|je suis d\xE9sol\xE9e?|je regrette|malheureuse\
1197
- ment|h\xE9las|je comprends|en tant qu'(?:ia|intelligence artificielle|mod\xE8le de langage|assistant))",zd="(?:ich (?:kann|werde|darf|m\xF6chte)|(?:kann|werde|darf|m\xF6chte) ich)(?: \\p{L}+){0,4}? (?:nicht|\
1198
- keine\\p{L}*)(?: \\p{L}+){0,3}?",p0="(?:helfen|unterst\xFCtzen|bereitstellen|geben|erstellen|schreiben|generieren|beantworten|liefern|nachkommen|teilen|anbieten|erkl\xE4ren|behilflich sein|bestimmen|festste\
1199
- llen|identifizieren|wissen|zugreifen|preisgeben|offenlegen|verraten|\xFCberpr\xFCfen|best\xE4tigen|ausfindig machen|orten|verfolgen|erraten|vorhersagen|diagnostizieren|verschreiben|raten|sagen, ob)",f0="\
1200
- (?:es tut mir leid|tut mir leid|entschuldigung|entschuldige|leider|bedauerlicherweise|ich verstehe|als (?:eine )?(?:ki|k\xFCnstliche intelligenz|sprachmodell|assistent))",Fd="non (?:posso|sono in grad\
1201
- o di|riesco a|mi sento a mio agio (?:a|nel))",m0=`(?:aiutar${k}|assister${k}|fornir${k}|crear${k}|scriver${k}|generar${k}|condivider${k}|risponder${k}|dar${k}|offrir${k}|soddisfare|partecipare|farlo|f\
1202
- are questo|con questo|con questa|determinar${k}|identificar${k}|saper${k}|accedere|rivelar${k}|divulgar${k}|verificar${k}|confermar${k}|localizzar${k}|rintracciar${k}|indovinar${k}|prevedere|diagnosti\
1203
- car${k}|prescriver${k}|consigliar${k}(?![^.!?]{0,60}abbastanza))`,h0="(?:mi dispiace|spiacente|purtroppo|sfortunatamente|capisco|come (?:un'?\\s?)?(?:ia|intelligenza artificiale|modello linguistico|ass\
1204
- istente))",qd="n\xE3o (?:posso|consigo|vou|sou capaz de|estou em condi\xE7\xF5es de|me sinto confort\xE1vel (?:em|a))",g0=`(?:ajudar${k}|auxiliar${k}|assistir${k}|fornecer${k}|criar${k}|escrever${k}|g\
1205
- erar${k}|compartilhar${k}|partilhar${k}|dar${k}|oferecer${k}|responder${k}|atender${k}|cumprir|participar|fazer isso|com isso|com esse|com essa|determinar${k}|identificar${k}|saber${k}|acessar|aceder|\
1206
- revelar${k}|divulgar${k}|verificar${k}|confirmar${k}|localizar${k}|rastrear${k}|adivinhar${k}|prever${k}|diagnosticar${k}|receitar${k}|aconselhar${k}|recomendar${k}(?![^.!?]{0,60}o suficiente))`,b0="(\
1207
- ?:desculpe|desculpa|sinto muito|lamento|infelizmente|entendo|compreendo|como (?:uma? )?(?:ia|intelig\xEAncia artificial|modelo de linguagem|assistente))",Vt="(?:[\\s,]+[\\p{L}'\u2019-]+){0,4}?[\\s,]+",
1208
- va=[`${ba}${Vt}${n0}`,r0,o0,`${Nd}${Vt}${s0}`,"lamento no poder",`${jd}${Vt}${c0}`,`${Bd}${Vt}${u0}`,`${zd} ${p0}`,`${Fd}${Vt}${m0}`,`${qd}${Vt}${g0}`].join("|"),v0=[i0,a0,l0,d0,f0,h0,b0].join("|"),y0=new RegExp(
1209
- `^(?:${va})(?![\\p{L}])`,"u"),k0=new RegExp(`^(?:${v0})(?![\\p{L}])`,"u"),Ud=new RegExp(`(?:^|[^\\p{L}'])(?:${va})(?![\\p{L}])`,"u"),x0="(?:really|even|honestly|quite|possibly|truly|personally|actuall\
1210
- y|simply|just|ever|always)",ya="i(?:'m| am)? ?(?:can't|cannot|can not|won't|will not|not going to|not able to|unable to)",w0=["wait","believe","imagine (?:how|what|why|anything|anyone|anybody|life|liv\
1211
- ing|being|a (?:better|world|life|time|single))","thank","stress","(?:over|under)?emphasi[sz]e","overstate","understate","exaggerate","(?:recommend|praise|rave about|speak highly of|say enough good)[^.\
1212
- !?]{0,60}enough","say enough","get enough","help (?:but|feeling|thinking|noticing|wondering|laughing|smiling|myself|it)",`(?:tell you|say|express|describe|explain|put into words) (?:how|what a) ${ha}`,
1213
- "express (?:my|our) (?:gratitude|thanks|appreciation)","begin to (?:describe|imagine|tell|express|thank|understand|fathom|comprehend|count)","agree (?:more|with you more)","complain","disagree","deny \
1214
- (?:that|it|this|the)","fault (?:you|it|that|this|the)","argue with (?:that|this|you|those|these|the (?:logic|results|data|numbers|math|facts))","find (?:any|anything|a single|no|nothing)","identify (?\
1215
- :any|anything|a single)","spot (?:any|anything|a single)","see (?:any|anything|a single|why not|a (?:reason|problem|downside|issue|bug))","think of (?:any|anything|a (?:reason|better|single|downside))",
1216
- "lie","sugar-?coat(?: it| this| that)?","bore you","belabou?r","rehash","judge you","keep you","get over","resist","top (?:that|this)","go wrong","say (?:that )?i","pretend (?:otherwise|(?:that )?(?:i\
1217
- 'm|i am|it's|it is|this is|everything|there's|there is|we|you))","remember (?:a time|the last time|when i)","stop (?:thinking|smiling|laughing|listening|reading|talking about)"],S0="(?:be (?:100% |com\
1218
- pletely |entirely |absolutely |totally |fully |one hundred percent )?(?:sure|certain)|say (?:for (?:sure|certain)|with (?:certainty|confidence)|definitively|exactly|precisely|for a fact)|know (?:for (\
1219
- ?:sure|certain)|exactly|precisely)|guarantee|promise|speak for|vouch for|recall|remember|run|test|execute|see (?:your|the) (?:screen|code|file|image|output|logs?))[^.!?]{0,160}?(?:,|\\s)(?:but|however)\
1220
- (?![\\p{L}])",Fo=`(?:${x0} ){0,2}(?:(?:${w0.join("|")})(?![\\p{L}])|${S0})`,Vd="no (?:(?:te|le|les|os|lo|la|me|se) )?(?:puedo|voy a)",E0=["esperar",`creer${k}`,`imaginar${k}`,"dejar de",`evitar${k}`,`\
1221
- agradecer${k}`,`negar${k}`,`mentir${k}`,`quejar${k}`,"estar m\xE1s",`(?:encontrar|ver|detectar|identificar|notar)${k} (?:ning\xFAn|ninguna|ningun|nada|ni un|motivo para no|raz\xF3n para no)`,`recomend\
1222
- ar${k}[^.!?]{0,60}(?:suficiente|bastante)`,`(?:enfatizar|recalcar|subrayar|insistir|exagerar|ponderar)${k}`,`(?:decir|expresar)${k} (?:lo|cu\xE1nto|cuanto|c\xF3mo de|como de)`,`resistir${k}`,"m\xE1s que",
1223
- "sino","pedir m\xE1s"],C0=`(?:estar (?:100 ?% |completamente |totalmente |del todo )?segur[oa]|asegurar${k}|garantizar${k}|prometer${k}|(?:decir|saber|afirmar)${k} con (?:certeza|seguridad|exactitud)|\
1224
- ejecutar${k}|probar${k}|recordar${k}|ver (?:tu|la|el) (?:pantalla|c\xF3digo|archivo))[^.!?]{0,160}?(?:,|\\s)(?:pero|aunque|sin embargo)(?![\\p{L}])`,ka=`(?:(?:${E0.join("|")})(?![\\p{L}])|${C0})`,Hd="\
1225
- no (?:(?:et|us|el|la|ho|em|li|els|les) )?(?:puc|penso|podr\xE9)",T0=[`esperar${k}`,`creure${k}`,`imaginar${k}`,"deixar de",`evitar${k}`,`agrair${k}`,`negar${k}`,`mentir${k}`,`queixar${k}`,"estar m\xE9s",
1226
- `(?:trobar|veure|detectar|identificar)${k} (?:cap|res|ni un|ni una)`,`recomanar${k}[^.!?]{0,60}prou`,`(?:emfatitzar|remarcar|subratllar|insistir|exagerar)${k}`,`dir${k} (?:com de|quant|prou)`,`resisti\
1227
- r${k}`,"m\xE9s que","sin\xF3","fer altra cosa que"],R0=`(?:estar (?:100 ?% |completament |del tot )?segura?|assegurar${k}|garantir${k}|prometre${k}|(?:dir|saber|afirmar)${k} amb (?:certesa|seguretat)|\
1228
- executar${k}|provar${k}|recordar${k})[^.!?]{0,160}?(?:,|\\s)(?:per\xF2|pero|tot i que)(?![\\p{L}])`,xa=`(?:(?:${T0.join("|")})(?![\\p{L}])|${R0})`,Wd="je ne (?:peux|pourrai|pourrais|vais)(?: malheureu\
1229
- sement)? pas",P0="(?:vous |te |t'|me |m'|le |la |les |l'|lui |leur |y |en |se |s')",I0=["attendre","croire","imaginer","emp\xEAcher","remercier","(?:trop |assez )?(?:insister|souligner|exag\xE9rer)","\
1230
- mentir","nier","plaindre","\xEAtre plus","(?:trouver|voir|d\xE9tecter|identifier|rep\xE9rer) (?:aucun|aucune|rien|de (?:probl\xE8me|raison|souci))","dire (?:\xE0 quel point|combien|assez)","recommande\
1231
- r[^.!?]{0,60}assez","r\xE9sister","faire autrement que"],_0="(?:\xEAtre (?:(?:tout \xE0 fait|absolument|enti\xE8rement|100 ?%) )?(?:s\xFBre?|certaine?)|garantir|promettre|affirmer|dire avec certitude|ex\xE9cuter|tes\
1232
- ter|souvenir|rappeler|voir (?:votre|ton|ta|le|la) (?:\xE9cran|code|fichier))[^.!?]{0,160}?(?:,|\\s)(?:mais|cependant|toutefois)(?![\\p{L}])",wa=`${P0}*(?:(?:${I0.join("|")})(?![\\p{L}])|${_0})`,Gd="no\
1233
- n (?:(?:ti|vi|la|lo|le|gli|ne|mi|ci) )?(?:posso|riesco a|sono in grado di|ho intenzione di)",D0=[`aspettar${k}`,`creder${k}`,`immaginar${k}`,"fare a meno",`ringraziar${k}`,"che","non",`negar${k}`,`men\
1234
- tir${k}`,`lamentar${k}`,"(?:essere|esser) pi\xF9",`(?:trovare|vedere|notare|individuare|rilevare) (?:nessun${k}|niente|alcun${k}|un solo)`,`consigliar${k}[^.!?]{0,60}abbastanza`,`(?:sottolinear|enfati\
1235
- zzar|insister|esagerar)${k}`,`dir${k} (?:quanto|abbastanza)`,`resister${k}`],A0=`(?:(?:esserne|essere) (?:del tutto |completamente |al 100 ?% )?(?:sicur[oa]|cert[oa])|garantir${k}|prometter${k}|(?:dir\
1236
- |affermar)${k} con certezza|eseguir${k}|testar${k}|ricordar${k})[^.!?]{0,160}?(?:,|\\s)(?:ma|per\xF2|tuttavia)(?![\\p{L}])`,Sa=`(?:(?:${D0.join("|")})(?![\\p{L}])|${A0})`,Kd="n\xE3o (?:(?:te|lhe|lhes|vos\
1237
- |o|a|me) )?(?:posso|consigo|vou|sou capaz de)",O0=["esperar","acreditar",`imaginar${k}`,"deixar de",`evitar${k}`,`agradecer${k}`,`negar${k}`,`mentir${k}`,`(?:me )?(?:queixar|reclamar)${k}`,"concordar \
1238
- mais","estar mais","sen\xE3o","(?:fazer )?mais (?:do )?que",`(?:encontrar|ver|identificar|detetar|detectar|notar) (?:nenhum${k}|nada|um \xFAnico|uma \xFAnica)`,`recomendar${k}[^.!?]{0,60}(?:o )?sufici\
1239
- ente`,`(?:enfatizar|sublinhar|ressaltar|insistir|exagerar)${k}`,`dizer${k} (?:o quanto|quanto|como|o suficiente)`,`resistir${k}`],L0=`(?:ter (?:a )?certeza|estar (?:100 ?% |completamente |totalmente )\
1240
- ?(?:segur[oa]|cert[oa])|garantir${k}|prometer${k}|(?:dizer|afirmar|saber)${k} com (?:certeza|seguran\xE7a)|executar${k}|testar${k}|lembrar${k})[^.!?]{0,160}?(?:,|\\s)(?:mas|por\xE9m|contudo)(?![\\p{L}])`,
1241
- Ea=`(?:(?:${O0.join("|")})(?![\\p{L}])|${L0})`,Jd="(?:ich (?:kann|werde|darf)|kann ich|werde ich)",M0=["(?:kaum|nicht) erwarten","glauben","vorstellen","genug (?:danken|betonen|empfehlen|loben|sagen|h\
1242
- ervorheben)","oft genug","\\p{L}*l\xFCgen","leugnen","bestreiten","beschweren","beklagen","(?:mehr|besser) zustimmen","widerstehen","keine?n? (?:fehler|probleme?|grund|haken|m\xE4ngel|bugs?|nachteile?|ei\
1243
- nw\xE4nde?)","sagen, wie (?:sehr|froh|dankbar|gl\xFCcklich)"],$0="(?:(?:mit )?sicherheit|genau|garantieren|versprechen|100 ?%|ausf\xFChren|testen|erinnern)[^.!?]{0,160}?(?:,|\\s)(?:aber|jedoch|allerdings)\
1244
- (?![\\p{L}])",Yd=`[^.!?]*?(?<![\\p{L}])(?:(?:${M0.join("|")})(?![\\p{L}])|${$0})`,Zd="(?:no[,.!]? |non[,.!]? |n\xE3o[,.!]? |nein[,.!]? )?",N0=new RegExp("^"+Zd+"(?:"+[`${ya}\\s(?!${Fo})\\p{L}`,`${Vd}\\\
1245
- s(?!${ka})\\p{L}`,`${Hd}\\s(?!${xa})\\p{L}`,`${Wd}\\s?(?!${wa})\\p{L}`,`${Gd}\\s(?!${Sa})\\p{L}`,`${Kd}\\s(?!${Ea})\\p{L}`,`${Jd}(?!${Yd})(?:\\s[\\p{L}\\p{N}'-]+){0,6}?\\s(?:nicht|keine?\\p{L}*)(?![\\p{L}])\
1246
- (?!\\s(?:nur|mehr als|anders|umhin))`].join("|")+")","u"),j0=new RegExp("^"+Zd+"(?:"+[`${ya}\\s(?=${Fo})`,`${Vd}\\s(?=${ka})`,`${Hd}\\s(?=${xa})`,`${Wd}\\s?(?=${wa})`,`${Gd}\\s(?=${Sa})`,`${Kd}\\s(?=${Ea}\
1247
- )`,`${Jd}(?=${Yd})`].join("|")+")","u"),B0="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettably|i'm afraid|i am afraid)",z0="\
1248
- (?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que)",F0="(?:ho sento(?: molt)?|em sap greu|disculpa|disculpeu|perdona|malauradament|l\
1249
- amentablement|dissortadament)",q0="(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|je regrette|pardon|malheureusement|h\xE9las)",U0="(?:es tut mir (?:sehr |wirklich )?leid|tut mir leid|entschuldigung|lei\
1250
- der|bedauerlicherweise)",V0="(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso|purtroppo|sfortunatamente)",H0="(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o desculpa|infelizmente)",W0=Fo,G0=ka,
1251
- K0=xa,J0=wa,Y0=Sa,Z0=Ea,qt=t=>`[,.!:;]?\\s(?:(?:${t})\\s)?`,X0="\\s\\p{L}",Q0=[`${B0}${qt("but|however,?")}(?:as an ai(?: language model| assistant)?,?\\s)?${ba}\\s(?!${W0})\\p{L}`,`${z0}${qt("pero")}${Nd}\
1252
- (?:\\s(?:te|le|les|os))?\\s(?!${G0})\\p{L}`,`${F0}${qt("per\xF2|pero")}${jd}\\s(?!${K0})\\p{L}`,`${q0}${qt("mais")}${Bd}(?:\\s(?:vous|te))?\\s?(?!${J0})\\p{L}`,`${U0}${qt("aber")}${zd}${X0}`,`${V0}${qt(
1253
- "ma")}${Fd}\\s(?!${Y0})\\p{L}`,`${H0}${qt("mas")}${qd}\\s(?!${Z0})\\p{L}`].join("|"),eb="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my apologies|apologies)",tb="(?:(\
1254
- ?:is|are|was|would be|could be|may be|might be|it's|that's|this is|it is|that is)(?: considered| generally| strictly| both)? (?:illegal|unlawful|unethical|against|a violation|a serious violation|a bre\
1255
- ach|an invasion|prohibited|not (?:something|appropriate|possible|allowed|permitted|legal|ethical|safe|advisable|ok|okay))|violates?|goes against|go against|infringes?|i (?:don't|do not) have (?:access\
1256
- |the ability|the means|the capability|any way|a way|information about|any information about|personal (?:information|data)))",nb="(?:(?:es|son|ser\xEDa|ser\xEDan|est\xE1|estar\xEDa|resulta)(?: considerado)? (?:ile\
1257
- gal|poco \xE9tic[oa]|inapropiad[oa]|contrari[oa] a|una violaci\xF3n|una infracci\xF3n|una invasi\xF3n|prohibid[oa])|no (?:es|ser\xEDa|est\xE1) (?:apropiado|posible|\xE9tico|legal|permitido|algo)|viola|violar\xEDa|infringe|va\
1258
- en contra|no tengo (?:acceso|la capacidad|forma de|manera de|informaci\xF3n (?:sobre|personal)|datos personales))",rb="(?:(?:\xE9s|s\xF3n|seria|serien) (?:il\xB7legal|ilegal|poc \xE8tic|inadequat|inapropiat|cont\
1259
- rari a|una violaci\xF3|una infracci\xF3|prohibit)|no (?:\xE9s|seria) (?:apropiat|adequat|possible|\xE8tic|legal|perm\xE8s)|viola|infringeix|va en contra)",ob="(?:(?:c'est|est|sont|serait|seraient) (?:\
1260
- ill\xE9gale?|contraire \xE0|une violation|une atteinte|interdite?|inappropri\xE9)|(?:ce )?n'est pas (?:appropri\xE9|possible|\xE9thique|l\xE9gal|autoris\xE9)|viole|enfreint|va \xE0 l'encontre)",ib="(?\
1261
- :(?:ist|sind|w\xE4re|w\xE4ren)(?: \\p{L}+)? (?:illegal|rechtswidrig|unethisch|verboten|unangemessen|unzul\xE4ssig|ein versto\xDF|nicht (?:angemessen|m\xF6glich|erlaubt|zul\xE4ssig|legal|ethisch))|verst\xF6\xDFt|verletzt)",
1262
- sb="(?:(?:\xE8|sono|sarebbe|sarebbero) (?:illegale|illecito|non etico|contrario a|una violazione|vietato|inappropriato)|non (?:\xE8|sarebbe) (?:appropriato|possibile|etico|legale|consentito)|viola|va contro\
1263
- )",ab="(?:(?:\xE9|s\xE3o|seria|seriam) (?:ilegal|anti\xE9tic[oa]|contr\xE1ri[oa] a|uma viola\xE7\xE3o|proibid[oa]|inapropriad[oa])|n\xE3o (?:\xE9|seria) (?:apropriado|poss\xEDvel|\xE9tico|legal|permitido)|viola|vai contra)",
1264
- Ut="(?:[\\p{L}\\p{N}'\u2019-]+[\\s,]+){0,14}?",cb=[`${eb},?\\sbut\\s${Ut}${tb}`,`(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona),?\\spero\\s${Ut}${nb}`,`(?:ho sento(?: molt)?|e\
1265
- m sap greu|disculpa|perdona),?\\s(?:per\xF2|pero)\\s${Ut}${rb}`,`(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|pardon),?\\smais\\s${Ut}${ob}`,`(?:es tut mir (?:sehr |wirklich )?leid|tut mir leid|entsch\
1266
- uldigung),?\\saber\\s${Ut}${ib}`,`(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso),?\\sma\\s${Ut}${sb}`,`(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o desculpa),?\\smas\\s${Ut}${ab}`].join(
1267
- "|"),lb=new RegExp(`^(?:${Q0}|(?:${cb})(?![\\p{L}]))`,"u"),ub="(?:(?:i'm |i am )?(?:really |so |very |truly |deeply |terribly )?sorry (?:to hear|to read|that you|you(?:'re| are)|you feel|for what you|\
1268
- about what you)|it sounds like you(?:'re| are)|that sounds (?:really |so |very |incredibly )?(?:hard|difficult|painful|overwhelming|tough|awful)|i(?:'m| am) (?:really |so |very )?(?:concerned|worried)\
1269
- (?:about|for|by|to hear)|i hear (?:you|how|that you)|you(?:'re| are) not alone|i(?:'m| am) (?:so |really )?glad you reached out)",db="(?:mental health (?:professional|provider|expert|specialist|servi\
1270
- ce|services|support|crisis|line)|therapist|counsel(?:l)?or|psychologist|psychiatrist|crisis (?:line|hotline|helpline|center|centre|text line|counsel(?:l)?or|team|service|services)|(?:suicide|crisis) (\
1271
- ?:prevention|hotline|helpline|lifeline)|hotline|helpline|lifeline|samaritans|emergency services|emergency number|call (?:911|988|999|112|000|emergency)|988|someone you trust|people you trust|(?:a )?tr\
1272
- usted (?:person|friend|adult|family member|individual|someone|loved one)|someone who can (?:help|support|provide support)|reach out to (?:someone|a friend|friends|family|a loved one|loved ones)|profes\
1273
- sional (?:help|support)|seek (?:immediate|urgent|professional) (?:help|support))",pb="(?:(?:lo )?(?:siento|lamento) (?:mucho |much\xEDsimo )?(?:que (?:te sientas|est\xE9s|estes|te encuentres|pases|est\xE9s pas\
1274
- ando)|escuchar|o\xEDr|leer|saber)|parece que (?:est\xE1s|estas) (?:pasando|atravesando)|me preocupa)",fb="(?:profesional(?:es)? de (?:la )?salud mental|psic\xF3log[oa]|psiquiatra|terapeuta|l\xEDnea (?:de )?\
1275
- (?:crisis|ayuda|prevenci\xF3n|atenci\xF3n)|tel\xE9fono de la esperanza|024|servicios de emergencia|(?:llama|llamar|llames) al (?:112|911|024)|alguien de (?:tu )?confianza|(?:una )?persona de (?:tu )?confianza|\
1276
- ayuda profesional)",mb="(?:em sap (?:molt )?greu (?:que (?:et sentis|estiguis|passis)|sentir|llegir|saber)|ho sento (?:molt|molt\xEDssim)|sembla que (?:est\xE0s|passes) (?:passant|travessant)?)",hb="(\
1277
- ?:professional(?:s)? de (?:la )?salut mental|psic\xF2leg|psic\xF2loga|psiquiatre|terapeuta|l\xEDnia (?:d'ajuda|d'atenci\xF3|de crisi|de prevenci\xF3)|tel\xE8fon de l'esperan\xE7a|024|serveis d'emerg\xE8ncia|(?:truca|trucar|t\
1278
- ruquis) al (?:112|024)|alg\xFA de (?:la teva )?confian\xE7a|(?:una )?persona de confian\xE7a|ajuda professional)",gb="(?:(?:je suis )?(?:vraiment |sinc\xE8rement |tellement |profond\xE9ment )?d\xE9sol\xE9e? (?:d'\
1279
- apprendre|de lire|d'entendre|que tu|que vous)|il semble que (?:tu traverses|vous traversez)|\xE7a a l'air (?:tr\xE8s |vraiment )?(?:difficile|dur))",bb="(?:professionnel(?:le)?s? de (?:la )?sant\xE9 ment\
1280
- ale|psychologue|psychiatre|th\xE9rapeute|ligne d'\xE9coute|ligne de crise|ligne d'assistance|num\xE9ro d'urgence|services d'urgence|(?:appelle|appelez|composez|compose) le (?:3114|15|112|911)|3114|personne de \
1281
- confiance|quelqu'un en qui (?:tu as|vous avez) confiance|aide professionnelle|sos amiti\xE9)",vb="(?:es tut mir (?:sehr |wirklich |so )?leid,? (?:dass|zu h\xF6ren|das zu h\xF6ren|zu lesen|das zu lesen)|das \
1282
- klingt (?:sehr |wirklich )?(?:schwer|belastend|schmerzhaft)|ich mache mir sorgen)",yb="(?:psychotherapeut\\p{L}*|psycholog\\p{L}*|psychiater\\p{L}*|therapeut\\p{L}*|fachkraft f\xFCr psychische|telefonseelsor\
1283
- ge|krisendienst|krisentelefon|notruf\\p{L}*|notdienst|rettungsdienst|vertrauensperson|jemandem,? dem (?:du|sie) vertrau\\p{L}*|professionelle hilfe|professionelle unterst\xFCtzung)",kb="(?:mi dispiace\
1284
- (?:molto |davvero |tanto )?(?:sentire|leggere|sapere|che tu|che ti|che stia)|sembra che (?:tu stia|stai) (?:passando|attraversando))",xb="(?:professionista della salute mentale|psicolog[oa]|psichiatr\
1285
- a|terapeuta|linea (?:di crisi|di ascolto|di supporto|d'ascolto)|telefono amico|telefono azzurro|numero di emergenza|servizi di emergenza|(?:chiama|chiamare) (?:il )?(?:112|118)|persona di fiducia|qual\
1286
- cuno di cui ti fidi|aiuto professionale)",wb="(?:sinto muito (?:que voc\xEA|por voc\xEA estar|em saber|ouvir|que esteja|que estejas)|lamento (?:muito )?(?:que voc\xEA|saber|ouvir)|parece que voc\xEA (?:est\xE1|estej\
1287
- a) (?:passando|a passar))",Sb="(?:profissional de sa\xFAde mental|profissionais de sa\xFAde mental|psic\xF3log[oa]|psiquiatra|terapeuta|cvv|linha de (?:apoio|crise|ajuda)|servi\xE7os de emerg\xEAncia|(?:ligue|liga|l\
1288
- igar) (?:para )?(?:o )?(?:188|192|112|190)|188|pessoa de confian\xE7a|algu\xE9m (?:de confian\xE7a|em quem (?:voc\xEA )?confie)|ajuda profissional|sns 24)",Eb=new RegExp(`^(?:${[ub,pb,mb,gb,vb,kb,wb].
1289
- join("|")})(?![\\p{L}])`,"u"),Cb=new RegExp(`(?<![\\p{L}\\p{N}])(?:${[db,fb,hb,bb,yb,xb,Sb].join("|")})(?![\\p{L}\\p{N}])`,"u"),Tb=2e4,Rb="(?:explain|detail|describe|elaborate)",Pb=new RegExp(`(?:^|[^\
1290
- \\p{L}'])(?:${va}|${ba}${Vt}${Rb})(?![\\p{L}])`,"gu"),Ib=new RegExp(`^[^\\p{L}]*${ya}\\s${Fo}`,"u");function $d(t,e){for(let n of t.matchAll(e))if(!Ib.test(t.slice(n.index)))return true;return false}var _b=new RegExp(
1291
- Ud.source,"gu");function Db(t){return t.slice(0,4*300).replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim()}function Ab(t){let e=[...t.
1185
+ sure (?:that )?it(?:'s| is| would be) appropriate|(?:this|that|the|your) request (?:cannot|can't|can not|will not|won't) be (?:fulfilled|completed|processed|honou?red|accommodated|carried out|answere\
1186
+ d)|(?:this|that|your) request (?:is|would be) (?:considered )?(?:inappropriate|illegal|unlawful|unethical|harmful|dangerous|against|not appropriate|a violation))",a0="(?:(?:i'm |i am |i'm really |i am\
1187
+ really |i'm so |really |so )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettably|i'm afraid|i am afraid|as an ai|as a language model|as an assistant|i understand|i appreciate|thank \
1188
+ you for|thanks for|while i understand|while i appreciate)",k="\\p{L}*",Bd="no (?:puedo|voy a|me es posible|estoy en condiciones de|me siento c\xF3mod[oa])",c0=`(?:ayudar${k}|asistir${k}|proporcionar${k}\
1189
+ |facilitar${k}|dar${k}|ofrecer${k}|crear${k}|escribir${k}|generar${k}|compartir${k}|cumplir|responder${k}|colaborar|participar|atender${k}|hacer eso|hacerlo|con eso|con esto|con esa|con esta|con tu|de\
1190
+ terminar${k}|identificar${k}|saber${k}|acceder|revelar${k}|divulgar${k}|verificar${k}|confirmar${k}|localizar${k}|rastrear${k}|adivinar${k}|predecir${k}|diagnosticar${k}|recomendar${k}(?![^.!?]{0,60}s\
1191
+ uficiente)|recetar${k}|aconsejar${k})`,l0="(?:lo siento|lo lamento|siento|lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que|como (?:una )?(?:ia|inteligencia artif\
1192
+ icial|modelo de lenguaje|asistente)|entiendo)",zd="no (?:puc|et puc|us puc|em sento c\xF2mod[ea]|estic en condicions de)",u0=`(?:ajudar${k}|assistir${k}|proporcionar${k}|facilitar${k}|donar${k}|oferir${k}\
1193
+ |crear${k}|escriure${k}|generar${k}|compartir${k}|complir|respondre${k}|col\xB7laborar|participar|fer aix\xF2|fer-ho|amb aix\xF2|amb aquesta|amb la teva|determinar${k}|identificar${k}|saber${k}|accedi\
1194
+ r|revelar${k}|divulgar${k}|verificar${k}|confirmar${k}|localitzar${k}|rastrejar${k}|endevinar${k}|predir${k}|diagnosticar${k}|recomanar${k}(?![^.!?]{0,60}prou)|receptar${k}|aconsellar${k})`,d0="(?:ho \
1195
+ sento|ho lamento|em sap greu|disculpa|disculpeu|perdona|malauradament|lamentablement|dissortadament|com a (?:ia|intel\xB7lig\xE8ncia artificial|model de llenguatge|assistent)|entenc)",Fd="(?:je ne (?:\
1196
+ peux|pourrai|pourrais|vais|souhaite)(?: malheureusement)? pas|je ne suis pas en mesure d[e']|je refuse d[e'])",p0="(?:aider|assister|fournir|r\xE9pondre|cr\xE9er|\xE9crire|g\xE9n\xE9rer|partager|donner|proposer|part\
1197
+ iciper|expliquer comment|acc\xE9der \xE0|satisfaire|faire cela|faire \xE7a|le faire|d\xE9terminer|identifier|savoir|divulguer|r\xE9v\xE9ler|v\xE9rifier|confirmer|localiser|retrouver|deviner|pr\xE9dire|diagnostiquer|prescrire\
1198
+ |conseiller|recommander(?![^.!?]{0,60}assez))",f0="(?:d\xE9sol\xE9e?|je suis d\xE9sol\xE9e?|je regrette|malheureusement|h\xE9las|je comprends|en tant qu'(?:ia|intelligence artificielle|mod\xE8le de langage|assistant))",
1199
+ qd="(?:ich (?:kann|werde|darf|m\xF6chte)|(?:kann|werde|darf|m\xF6chte) ich)(?: \\p{L}+){0,4}? (?:nicht|keine\\p{L}*)(?: \\p{L}+){0,3}?",m0="(?:helfen|unterst\xFCtzen|bereitstellen|geben|erstellen|schreib\
1200
+ en|generieren|beantworten|liefern|nachkommen|teilen|anbieten|erkl\xE4ren|behilflich sein|bestimmen|feststellen|identifizieren|wissen|zugreifen|preisgeben|offenlegen|verraten|\xFCberpr\xFCfen|best\xE4tigen|ausfind\
1201
+ ig machen|orten|verfolgen|erraten|vorhersagen|diagnostizieren|verschreiben|raten|sagen, ob)",h0="(?:es tut mir leid|tut mir leid|entschuldigung|entschuldige|leider|bedauerlicherweise|ich verstehe|als \
1202
+ (?:eine )?(?:ki|k\xFCnstliche intelligenz|sprachmodell|assistent))",Ud="non (?:posso|sono in grado di|riesco a|mi sento a mio agio (?:a|nel))",g0=`(?:aiutar${k}|assister${k}|fornir${k}|crear${k}|scriv\
1203
+ er${k}|generar${k}|condivider${k}|risponder${k}|dar${k}|offrir${k}|soddisfare|partecipare|farlo|fare questo|con questo|con questa|determinar${k}|identificar${k}|saper${k}|accedere|rivelar${k}|divulgar${k}\
1204
+ |verificar${k}|confermar${k}|localizzar${k}|rintracciar${k}|indovinar${k}|prevedere|diagnosticar${k}|prescriver${k}|consigliar${k}(?![^.!?]{0,60}abbastanza))`,b0="(?:mi dispiace|spiacente|purtroppo|sf\
1205
+ ortunatamente|capisco|come (?:un'?\\s?)?(?:ia|intelligenza artificiale|modello linguistico|assistente))",Vd="n\xE3o (?:posso|consigo|vou|sou capaz de|estou em condi\xE7\xF5es de|me sinto confort\xE1vel (?:em|a))",
1206
+ v0=`(?:ajudar${k}|auxiliar${k}|assistir${k}|fornecer${k}|criar${k}|escrever${k}|gerar${k}|compartilhar${k}|partilhar${k}|dar${k}|oferecer${k}|responder${k}|atender${k}|cumprir|participar|fazer isso|co\
1207
+ m isso|com esse|com essa|determinar${k}|identificar${k}|saber${k}|acessar|aceder|revelar${k}|divulgar${k}|verificar${k}|confirmar${k}|localizar${k}|rastrear${k}|adivinhar${k}|prever${k}|diagnosticar${k}\
1208
+ |receitar${k}|aconselhar${k}|recomendar${k}(?![^.!?]{0,60}o suficiente))`,y0="(?:desculpe|desculpa|sinto muito|lamento|infelizmente|entendo|compreendo|como (?:uma? )?(?:ia|intelig\xEAncia artificial|mode\
1209
+ lo de linguagem|assistente))",Vt="(?:[\\s,]+[\\p{L}'\u2019-]+){0,4}?[\\s,]+",va=[`${ba}${Vt}${o0}`,i0,s0,`${Bd}${Vt}${c0}`,"lamento no poder","(?:esta|esa|la|tu) (?:solicitud|petici\xF3n) no (?:se )?pued\
1210
+ e (?:ser )?(?:atender|atendida|cumplir|cumplida|completar|completada|procesar|procesada)",`${zd}${Vt}${u0}`,`${Fd}${Vt}${p0}`,`${qd} ${m0}`,`${Ud}${Vt}${g0}`,`${Vd}${Vt}${v0}`].join("|"),k0=[a0,l0,d0,
1211
+ f0,h0,b0,y0].join("|"),x0=new RegExp(`^(?:${va})(?![\\p{L}])`,"u"),w0=new RegExp(`^(?:${k0})(?![\\p{L}])`,"u"),Hd=new RegExp(`(?:^|[^\\p{L}'])(?:${va})(?![\\p{L}])`,"u"),S0="(?:really|even|honestly|qu\
1212
+ ite|possibly|truly|personally|actually|simply|just|ever|always)",ya="i(?:'m| am)? ?(?:can't|cannot|can not|won't|will not|not going to|not able to|unable to)",E0=["wait","believe","imagine (?:how|what\
1213
+ |why|anything|anyone|anybody|life|living|being|a (?:better|world|life|time|single))","thank","stress","(?:over|under)?emphasi[sz]e","overstate","understate","exaggerate","(?:recommend|praise|rave abou\
1214
+ t|speak highly of|say enough good)[^.!?]{0,60}enough","say enough","get enough","help (?:but|feeling|thinking|noticing|wondering|laughing|smiling|myself|it)",`(?:tell you|say|express|describe|explain|\
1215
+ put into words) (?:how|what a) ${ha}`,"express (?:my|our) (?:gratitude|thanks|appreciation)","begin to (?:describe|imagine|tell|express|thank|understand|fathom|comprehend|count)","agree (?:more|with y\
1216
+ ou more)","complain","disagree","deny (?:that|it|this|the)","fault (?:you|it|that|this|the)","argue with (?:that|this|you|those|these|the (?:logic|results|data|numbers|math|facts))","find (?:any|anyth\
1217
+ ing|a single|no|nothing)","identify (?:any|anything|a single)","spot (?:any|anything|a single)","see (?:any|anything|a single|why not|a (?:reason|problem|downside|issue|bug))","think of (?:any|anythin\
1218
+ g|a (?:reason|better|single|downside))","lie","sugar-?coat(?: it| this| that)?","bore you","belabou?r","rehash","judge you","keep you","get over","resist","top (?:that|this)","go wrong","say (?:that )\
1219
+ ?i","pretend (?:otherwise|(?:that )?(?:i'm|i am|it's|it is|this is|everything|there's|there is|we|you))","remember (?:a time|the last time|when i)","stop (?:thinking|smiling|laughing|listening|reading\
1220
+ |talking about)"],C0="(?:be (?:100% |completely |entirely |absolutely |totally |fully |one hundred percent )?(?:sure|certain)|say (?:for (?:sure|certain)|with (?:certainty|confidence)|definitively|exa\
1221
+ ctly|precisely|for a fact)|know (?:for (?:sure|certain)|exactly|precisely)|guarantee|promise|speak for|vouch for|recall|remember|run|test|execute|see (?:your|the) (?:screen|code|file|image|output|logs\
1222
+ ?))[^.!?]{0,160}?(?:,|\\s)(?:but|however)(?![\\p{L}])",Fo=`(?:${S0} ){0,2}(?:(?:${E0.join("|")})(?![\\p{L}])|${C0})`,Wd="no (?:(?:te|le|les|os|lo|la|me|se) )?(?:puedo|voy a)",T0=["esperar",`creer${k}`,
1223
+ `imaginar${k}`,"dejar de",`evitar${k}`,`agradecer${k}`,`negar${k}`,`mentir${k}`,`quejar${k}`,"estar m\xE1s",`(?:encontrar|ver|detectar|identificar|notar)${k} (?:ning\xFAn|ninguna|ningun|nada|ni un|motivo\
1224
+ para no|raz\xF3n para no)`,`recomendar${k}[^.!?]{0,60}(?:suficiente|bastante)`,`(?:enfatizar|recalcar|subrayar|insistir|exagerar|ponderar)${k}`,`(?:decir|expresar)${k} (?:lo|cu\xE1nto|cuanto|c\xF3mo de|com\
1225
+ o de)`,`resistir${k}`,"m\xE1s que","sino","pedir m\xE1s"],R0=`(?:estar (?:100 ?% |completamente |totalmente |del todo )?segur[oa]|asegurar${k}|garantizar${k}|prometer${k}|(?:decir|saber|afirmar)${k} c\
1226
+ on (?:certeza|seguridad|exactitud)|ejecutar${k}|probar${k}|recordar${k}|ver (?:tu|la|el) (?:pantalla|c\xF3digo|archivo))[^.!?]{0,160}?(?:,|\\s)(?:pero|aunque|sin embargo)(?![\\p{L}])`,ka=`(?:(?:${T0.join(
1227
+ "|")})(?![\\p{L}])|${R0})`,Gd="no (?:(?:et|us|el|la|ho|em|li|els|les) )?(?:puc|penso|podr\xE9)",P0=[`esperar${k}`,`creure${k}`,`imaginar${k}`,"deixar de",`evitar${k}`,`agrair${k}`,`negar${k}`,`mentir${k}`,
1228
+ `queixar${k}`,"estar m\xE9s",`(?:trobar|veure|detectar|identificar)${k} (?:cap|res|ni un|ni una)`,`recomanar${k}[^.!?]{0,60}prou`,`(?:emfatitzar|remarcar|subratllar|insistir|exagerar)${k}`,`dir${k} (?\
1229
+ :com de|quant|prou)`,`resistir${k}`,"m\xE9s que","sin\xF3","fer altra cosa que"],_0=`(?:estar (?:100 ?% |completament |del tot )?segura?|assegurar${k}|garantir${k}|prometre${k}|(?:dir|saber|afirmar)${k}\
1230
+ amb (?:certesa|seguretat)|executar${k}|provar${k}|recordar${k})[^.!?]{0,160}?(?:,|\\s)(?:per\xF2|pero|tot i que)(?![\\p{L}])`,xa=`(?:(?:${P0.join("|")})(?![\\p{L}])|${_0})`,Kd="je ne (?:peux|pourrai|\
1231
+ pourrais|vais)(?: malheureusement)? pas",I0="(?:vous |te |t'|me |m'|le |la |les |l'|lui |leur |y |en |se |s')",D0=["attendre","croire","imaginer","emp\xEAcher","remercier","(?:trop |assez )?(?:insiste\
1232
+ r|souligner|exag\xE9rer)","mentir","nier","plaindre","\xEAtre plus","(?:trouver|voir|d\xE9tecter|identifier|rep\xE9rer) (?:aucun|aucune|rien|de (?:probl\xE8me|raison|souci))","dire (?:\xE0 quel point|com\
1233
+ bien|assez)","recommander[^.!?]{0,60}assez","r\xE9sister","faire autrement que"],A0="(?:\xEAtre (?:(?:tout \xE0 fait|absolument|enti\xE8rement|100 ?%) )?(?:s\xFBre?|certaine?)|garantir|promettre|affirmer|dire ave\
1234
+ c certitude|ex\xE9cuter|tester|souvenir|rappeler|voir (?:votre|ton|ta|le|la) (?:\xE9cran|code|fichier))[^.!?]{0,160}?(?:,|\\s)(?:mais|cependant|toutefois)(?![\\p{L}])",wa=`${I0}*(?:(?:${D0.join("|")})\
1235
+ (?![\\p{L}])|${A0})`,Jd="non (?:(?:ti|vi|la|lo|le|gli|ne|mi|ci) )?(?:posso|riesco a|sono in grado di|ho intenzione di)",O0=[`aspettar${k}`,`creder${k}`,`immaginar${k}`,"fare a meno",`ringraziar${k}`,"\
1236
+ che","non",`negar${k}`,`mentir${k}`,`lamentar${k}`,"(?:essere|esser) pi\xF9",`(?:trovare|vedere|notare|individuare|rilevare) (?:nessun${k}|niente|alcun${k}|un solo)`,`consigliar${k}[^.!?]{0,60}abbasta\
1237
+ nza`,`(?:sottolinear|enfatizzar|insister|esagerar)${k}`,`dir${k} (?:quanto|abbastanza)`,`resister${k}`],L0=`(?:(?:esserne|essere) (?:del tutto |completamente |al 100 ?% )?(?:sicur[oa]|cert[oa])|garant\
1238
+ ir${k}|prometter${k}|(?:dir|affermar)${k} con certezza|eseguir${k}|testar${k}|ricordar${k})[^.!?]{0,160}?(?:,|\\s)(?:ma|per\xF2|tuttavia)(?![\\p{L}])`,Sa=`(?:(?:${O0.join("|")})(?![\\p{L}])|${L0})`,Yd="\
1239
+ n\xE3o (?:(?:te|lhe|lhes|vos|o|a|me) )?(?:posso|consigo|vou|sou capaz de)",M0=["esperar","acreditar",`imaginar${k}`,"deixar de",`evitar${k}`,`agradecer${k}`,`negar${k}`,`mentir${k}`,`(?:me )?(?:queixa\
1240
+ r|reclamar)${k}`,"concordar mais","estar mais","sen\xE3o","(?:fazer )?mais (?:do )?que",`(?:encontrar|ver|identificar|detetar|detectar|notar) (?:nenhum${k}|nada|um \xFAnico|uma \xFAnica)`,`recomendar${k}\
1241
+ [^.!?]{0,60}(?:o )?suficiente`,`(?:enfatizar|sublinhar|ressaltar|insistir|exagerar)${k}`,`dizer${k} (?:o quanto|quanto|como|o suficiente)`,`resistir${k}`],$0=`(?:ter (?:a )?certeza|estar (?:100 ?% |co\
1242
+ mpletamente |totalmente )?(?:segur[oa]|cert[oa])|garantir${k}|prometer${k}|(?:dizer|afirmar|saber)${k} com (?:certeza|seguran\xE7a)|executar${k}|testar${k}|lembrar${k})[^.!?]{0,160}?(?:,|\\s)(?:mas|por\
1243
+ \xE9m|contudo)(?![\\p{L}])`,Ea=`(?:(?:${M0.join("|")})(?![\\p{L}])|${$0})`,Zd="(?:ich (?:kann|werde|darf)|kann ich|werde ich)",N0=["(?:kaum|nicht) erwarten","glauben","vorstellen","genug (?:danken|bet\
1244
+ onen|empfehlen|loben|sagen|hervorheben)","oft genug","\\p{L}*l\xFCgen","leugnen","bestreiten","beschweren","beklagen","(?:mehr|besser) zustimmen","widerstehen","keine?n? (?:fehler|probleme?|grund|hake\
1245
+ n|m\xE4ngel|bugs?|nachteile?|einw\xE4nde?)","sagen, wie (?:sehr|froh|dankbar|gl\xFCcklich)"],j0="(?:(?:mit )?sicherheit|genau|garantieren|versprechen|100 ?%|ausf\xFChren|testen|erinnern)[^.!?]{0,160}?(?:\
1246
+ ,|\\s)(?:aber|jedoch|allerdings)(?![\\p{L}])",Xd=`[^.!?]*?(?<![\\p{L}])(?:(?:${N0.join("|")})(?![\\p{L}])|${j0})`,Qd="(?:no[,.!]? |non[,.!]? |n\xE3o[,.!]? |nein[,.!]? )?",B0=new RegExp("^"+Qd+"(?:"+[`${ya}\
1247
+ \\s(?!${Fo})\\p{L}`,`${Wd}\\s(?!${ka})\\p{L}`,`${Gd}\\s(?!${xa})\\p{L}`,`${Kd}\\s?(?!${wa})\\p{L}`,`${Jd}\\s(?!${Sa})\\p{L}`,`${Yd}\\s(?!${Ea})\\p{L}`,`${Zd}(?!${Xd})(?:\\s[\\p{L}\\p{N}'-]+){0,6}?\\s(?:ni\
1248
+ cht|keine?\\p{L}*)(?![\\p{L}])(?!\\s(?:nur|mehr als|anders|umhin))`].join("|")+")","u"),z0=new RegExp("^"+Qd+"(?:"+[`${ya}\\s(?=${Fo})`,`${Wd}\\s(?=${ka})`,`${Gd}\\s(?=${xa})`,`${Kd}\\s?(?=${wa})`,`${Jd}\
1249
+ \\s(?=${Sa})`,`${Yd}\\s(?=${Ea})`,`${Zd}(?=${Xd})`].join("|")+")","u"),F0="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my apologies|apologies|unfortunately|regrettabl\
1250
+ y|i'm afraid|i am afraid)",q0="(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona|lamentablemente|desafortunadamente|me temo que)",U0="(?:ho sento(?: molt)?|em sap greu|disculpa|di\
1251
+ sculpeu|perdona|malauradament|lamentablement|dissortadament)",V0="(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|je regrette|pardon|malheureusement|h\xE9las)",H0="(?:es tut mir (?:sehr |wirklich )?leid|\
1252
+ tut mir leid|entschuldigung|leider|bedauerlicherweise)",W0="(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso|purtroppo|sfortunatamente)",G0="(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o des\
1253
+ culpa|infelizmente)",K0=Fo,J0=ka,Y0=xa,Z0=wa,X0=Sa,Q0=Ea,qt=t=>`[,.!:;]?\\s(?:(?:${t})\\s)?`,eb="\\s\\p{L}",tb=[`${F0}${qt("but|however,?")}(?:as an ai(?: language model| assistant)?,?\\s)?${ba}\\s(?!${K0}\
1254
+ )\\p{L}`,`${q0}${qt("pero")}${Bd}(?:\\s(?:te|le|les|os))?\\s(?!${J0})\\p{L}`,`${U0}${qt("per\xF2|pero")}${zd}\\s(?!${Y0})\\p{L}`,`${V0}${qt("mais")}${Fd}(?:\\s(?:vous|te))?\\s?(?!${Z0})\\p{L}`,`${H0}${qt(
1255
+ "aber")}${qd}${eb}`,`${W0}${qt("ma")}${Ud}\\s(?!${X0})\\p{L}`,`${G0}${qt("mas")}${Vd}\\s(?!${Q0})\\p{L}`].join("|"),nb="(?:(?:i'm |i am )?(?:really |so |very |truly |terribly )?sorry|i apologi[sz]e|my\
1256
+ apologies|apologies)",rb="(?:(?:is|are|was|would be|could be|may be|might be|it's|that's|this is|it is|that is)(?: considered| generally| strictly| both)? (?:illegal|unlawful|unethical|against|a viol\
1257
+ ation|a serious violation|a breach|an invasion|prohibited|not (?:something|appropriate|possible|allowed|permitted|legal|ethical|safe|advisable|ok|okay))|violates?|goes against|go against|infringes?|i \
1258
+ (?:don't|do not) have (?:access|the ability|the means|the capability|any way|a way|information about|any information about|personal (?:information|data)))",ob="(?:(?:es|son|ser\xEDa|ser\xEDan|est\xE1|estar\xEDa|r\
1259
+ esulta)(?: considerado)? (?:ilegal|poco \xE9tic[oa]|inapropiad[oa]|contrari[oa] a|una violaci\xF3n|una infracci\xF3n|una invasi\xF3n|prohibid[oa])|no (?:es|ser\xEDa|est\xE1) (?:apropiado|posible|\xE9tico|legal|permitido|a\
1260
+ lgo)|viola|violar\xEDa|infringe|va en contra|no tengo (?:acceso|la capacidad|forma de|manera de|informaci\xF3n (?:sobre|personal)|datos personales))",ib="(?:(?:\xE9s|s\xF3n|seria|serien) (?:il\xB7legal|ilegal|\
1261
+ poc \xE8tic|inadequat|inapropiat|contrari a|una violaci\xF3|una infracci\xF3|prohibit)|no (?:\xE9s|seria) (?:apropiat|adequat|possible|\xE8tic|legal|perm\xE8s)|viola|infringeix|va en contra)",sb="(?:(\
1262
+ ?:c'est|est|sont|serait|seraient) (?:ill\xE9gale?|contraire \xE0|une violation|une atteinte|interdite?|inappropri\xE9)|(?:ce )?n'est pas (?:appropri\xE9|possible|\xE9thique|l\xE9gal|autoris\xE9)|viole|enfreint|va \xE0 l'enco\
1263
+ ntre)",ab="(?:(?:ist|sind|w\xE4re|w\xE4ren)(?: \\p{L}+)? (?:illegal|rechtswidrig|unethisch|verboten|unangemessen|unzul\xE4ssig|ein versto\xDF|nicht (?:angemessen|m\xF6glich|erlaubt|zul\xE4ssig|legal|ethisch))|verst\xF6\xDFt|v\
1264
+ erletzt)",cb="(?:(?:\xE8|sono|sarebbe|sarebbero) (?:illegale|illecito|non etico|contrario a|una violazione|vietato|inappropriato)|non (?:\xE8|sarebbe) (?:appropriato|possibile|etico|legale|consentito)|viola\
1265
+ |va contro)",lb="(?:(?:\xE9|s\xE3o|seria|seriam) (?:ilegal|anti\xE9tic[oa]|contr\xE1ri[oa] a|uma viola\xE7\xE3o|proibid[oa]|inapropriad[oa])|n\xE3o (?:\xE9|seria) (?:apropriado|poss\xEDvel|\xE9tico|legal|permitido)|viola|vai contr\
1266
+ a)",Ut="(?:[\\p{L}\\p{N}'\u2019-]+[\\s,]+){0,14}?",ub=[`${nb},?\\sbut\\s${Ut}${rb}`,`(?:lo siento(?: mucho)?|lo lamento|disculpa|disculpe|perd\xF3n|perdona),?\\spero\\s${Ut}${ob}`,`(?:ho sento(?: molt\
1267
+ )?|em sap greu|disculpa|perdona),?\\s(?:per\xF2|pero)\\s${Ut}${ib}`,`(?:(?:je suis )?(?:vraiment )?d\xE9sol\xE9e?|pardon),?\\smais\\s${Ut}${sb}`,`(?:es tut mir (?:sehr |wirklich )?leid|tut mir leid|en\
1268
+ tschuldigung),?\\saber\\s${Ut}${ab}`,`(?:mi dispiace(?: molto)?|spiacente|scusa|scusami|mi scuso),?\\sma\\s${Ut}${cb}`,`(?:desculpe|desculpa|sinto muito|lamento|pe\xE7o desculpa),?\\smas\\s${Ut}${lb}`].
1269
+ join("|"),db=new RegExp(`^(?:${tb}|(?:${ub})(?![\\p{L}]))`,"u"),pb="(?:(?:i'm |i am )?(?:really |so |very |truly |deeply |terribly )?sorry (?:to hear|to read|that you|you(?:'re| are)|you feel|for what\
1270
+ you|about what you)|it sounds like you(?:'re| are)|that sounds (?:really |so |very |incredibly )?(?:hard|difficult|painful|overwhelming|tough|awful)|i(?:'m| am) (?:really |so |very )?(?:concerned|wor\
1271
+ ried) (?:about|for|by|to hear)|i hear (?:you|how|that you)|you(?:'re| are) not alone|i(?:'m| am) (?:so |really )?glad you reached out)",fb="(?:mental health (?:professional|provider|expert|specialist|\
1272
+ service|services|support|crisis|line)|therapist|counsel(?:l)?or|psychologist|psychiatrist|crisis (?:line|hotline|helpline|center|centre|text line|counsel(?:l)?or|team|service|services)|(?:suicide|cris\
1273
+ is) (?:prevention|hotline|helpline|lifeline)|hotline|helpline|lifeline|samaritans|emergency services|emergency number|call (?:911|988|999|112|000|emergency)|988|someone you trust|people you trust|(?:a\
1274
+ )?trusted (?:person|friend|adult|family member|individual|someone|loved one)|someone who can (?:help|support|provide support)|reach out to (?:someone|a friend|friends|family|a loved one|loved ones)|p\
1275
+ rofessional (?:help|support)|seek (?:immediate|urgent|professional) (?:help|support))",mb="(?:(?:lo )?(?:siento|lamento) (?:mucho |much\xEDsimo )?(?:que (?:te sientas|est\xE9s|estes|te encuentres|pases|est\xE9\
1276
+ s pasando)|escuchar|o\xEDr|leer|saber)|parece que (?:est\xE1s|estas) (?:pasando|atravesando)|me preocupa)",hb="(?:profesional(?:es)? de (?:la )?salud mental|psic\xF3log[oa]|psiquiatra|terapeuta|l\xEDnea (?:\
1277
+ de )?(?:crisis|ayuda|prevenci\xF3n|atenci\xF3n)|tel\xE9fono de la esperanza|024|servicios de emergencia|(?:llama|llamar|llames) al (?:112|911|024)|alguien de (?:tu )?confianza|(?:una )?persona de (?:tu )?confi\
1278
+ anza|ayuda profesional)",gb="(?:em sap (?:molt )?greu (?:que (?:et sentis|estiguis|passis)|sentir|llegir|saber)|ho sento (?:molt|molt\xEDssim)|sembla que (?:est\xE0s|passes) (?:passant|travessant)?)",
1279
+ bb="(?:professional(?:s)? de (?:la )?salut mental|psic\xF2leg|psic\xF2loga|psiquiatre|terapeuta|l\xEDnia (?:d'ajuda|d'atenci\xF3|de crisi|de prevenci\xF3)|tel\xE8fon de l'esperan\xE7a|024|serveis d'emerg\xE8ncia|(?:truca|tru\
1280
+ car|truquis) al (?:112|024)|alg\xFA de (?:la teva )?confian\xE7a|(?:una )?persona de confian\xE7a|ajuda professional)",vb="(?:(?:je suis )?(?:vraiment |sinc\xE8rement |tellement |profond\xE9ment )?d\xE9sol\xE9e? \
1281
+ (?:d'apprendre|de lire|d'entendre|que tu|que vous)|il semble que (?:tu traverses|vous traversez)|\xE7a a l'air (?:tr\xE8s |vraiment )?(?:difficile|dur))",yb="(?:professionnel(?:le)?s? de (?:la )?sant\xE9\
1282
+ mentale|psychologue|psychiatre|th\xE9rapeute|ligne d'\xE9coute|ligne de crise|ligne d'assistance|num\xE9ro d'urgence|services d'urgence|(?:appelle|appelez|composez|compose) le (?:3114|15|112|911)|3114|personn\
1283
+ e de confiance|quelqu'un en qui (?:tu as|vous avez) confiance|aide professionnelle|sos amiti\xE9)",kb="(?:es tut mir (?:sehr |wirklich |so )?leid,? (?:dass|zu h\xF6ren|das zu h\xF6ren|zu lesen|das zu lesen)\
1284
+ |das klingt (?:sehr |wirklich )?(?:schwer|belastend|schmerzhaft)|ich mache mir sorgen)",xb="(?:psychotherapeut\\p{L}*|psycholog\\p{L}*|psychiater\\p{L}*|therapeut\\p{L}*|fachkraft f\xFCr psychische|telefonse\
1285
+ elsorge|krisendienst|krisentelefon|notruf\\p{L}*|notdienst|rettungsdienst|vertrauensperson|jemandem,? dem (?:du|sie) vertrau\\p{L}*|professionelle hilfe|professionelle unterst\xFCtzung)",wb="(?:mi dis\
1286
+ piace (?:molto |davvero |tanto )?(?:sentire|leggere|sapere|che tu|che ti|che stia)|sembra che (?:tu stia|stai) (?:passando|attraversando))",Sb="(?:professionista della salute mentale|psicolog[oa]|psic\
1287
+ hiatra|terapeuta|linea (?:di crisi|di ascolto|di supporto|d'ascolto)|telefono amico|telefono azzurro|numero di emergenza|servizi di emergenza|(?:chiama|chiamare) (?:il )?(?:112|118)|persona di fiducia\
1288
+ |qualcuno di cui ti fidi|aiuto professionale)",Eb="(?:sinto muito (?:que voc\xEA|por voc\xEA estar|em saber|ouvir|que esteja|que estejas)|lamento (?:muito )?(?:que voc\xEA|saber|ouvir)|parece que voc\xEA (?:est\xE1|\
1289
+ esteja) (?:passando|a passar))",Cb="(?:profissional de sa\xFAde mental|profissionais de sa\xFAde mental|psic\xF3log[oa]|psiquiatra|terapeuta|cvv|linha de (?:apoio|crise|ajuda)|servi\xE7os de emerg\xEAncia|(?:ligue|l\
1290
+ iga|ligar) (?:para )?(?:o )?(?:188|192|112|190)|188|pessoa de confian\xE7a|algu\xE9m (?:de confian\xE7a|em quem (?:voc\xEA )?confie)|ajuda profissional|sns 24)",Tb=new RegExp(`^(?:${[pb,mb,gb,vb,kb,wb,
1291
+ Eb].join("|")})(?![\\p{L}])`,"u"),Rb=new RegExp(`(?<![\\p{L}\\p{N}])(?:${[fb,hb,bb,yb,xb,Sb,Cb].join("|")})(?![\\p{L}\\p{N}])`,"u"),Pb=2e4,_b="(?:explain|detail|describe|elaborate)",Ib=new RegExp(`(?:\
1292
+ ^|[^\\p{L}'])(?:${va}|${ba}${Vt}${_b})(?![\\p{L}])`,"gu"),Db=new RegExp(`^[^\\p{L}]*${ya}\\s${Fo}`,"u");function $d(t,e){for(let n of t.matchAll(e))if(!Db.test(t.slice(n.index)))return true;return false}var Ab=new RegExp(
1293
+ Hd.source,"gu");function Ob(t){return t.slice(0,4*300).replace(/[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim()}function Lb(t){let e=[...t.
1292
1294
  matchAll(/[.!?。](?:\s|$)/g)],n=e.length>=2?e[1].index+1:t.length;return t.slice(0,Math.min(n,240))}function ga(t){let e=/[.!?。:;](?:\s|$)/.exec(t);return e?t.slice(e.index+1).trim():""}function ir(t){
1293
- if(typeof t!="string"||t==="")return null;let e=Db(t);if(e==="")return null;let n=Ab(e),r=j0.test(n);if(!r&&(y0.test(n)||N0.test(n)))return "opens-with-refusal";let o=r?ga(n):n;return k0.test(n)&&Ud.test(
1294
- o)||lb.test(n)?"apology-then-refusal":e.length<=300&&$d(r?ga(e):e,_b)?"short-refusal":Eb.test(n)&&Cb.test(n)?"redirection":$d(Ob(t,r),Pb)?"partial-refusal":null}function Ob(t,e){let n=t.slice(0,Tb).replace(
1295
- /[‘’ʼ`´]/g,"'").toLowerCase().replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim();return e?ga(n):n}function qo(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,
1295
+ if(typeof t!="string"||t==="")return null;let e=Nd(t);if(e)return e;for(let n of Nb(t))if(Nd(n))return "refusal-in-structured-output";return null}var Mb=200,$b=4e4;function Nb(t){let e=t.trim();if(!(e.
1296
+ startsWith("{")||e.startsWith("["))||e.length>$b)return [];let n;try{n=JSON.parse(e);}catch{return []}let r=[],o=[n];for(;o.length>0&&r.length<Mb;){let i=o.pop();if(typeof i=="string")i.trim()!==""&&r.push(
1297
+ i);else if(Array.isArray(i))for(let s=i.length-1;s>=0;s--)o.push(i[s]);else if(i!==null&&typeof i=="object"){let s=Object.values(i);for(let a=s.length-1;a>=0;a--)o.push(s[a]);}}return r}function Nd(t){
1298
+ let e=Ob(t);if(e==="")return null;let n=Lb(e),r=z0.test(n);if(!r&&(x0.test(n)||B0.test(n)))return "opens-with-refusal";let o=r?ga(n):n;return w0.test(n)&&Hd.test(o)||db.test(n)?"apology-then-refusal":e.
1299
+ length<=300&&$d(r?ga(e):e,Ab)?"short-refusal":Tb.test(n)&&Rb.test(jd(t,false))?"redirection":$d(jd(t,r),Ib)?"partial-refusal":null}function jd(t,e){let n=t.slice(0,Pb).replace(/[‘’ʼ`´]/g,"'").toLowerCase().
1300
+ replace(/\s+/g," ").trim().replace(/^[\s*#>_"'«“¿¡(\[-]+/u,"").trim();return e?ga(n):n}function qo(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,
1296
1301
  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==
1297
- "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 Lb(t){let e=t*100,
1298
- n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function Xd(t){let e=Lb(t);return `[bvsala] Verification sampling is ON \
1302
+ "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 jb(t){let e=t*100,
1303
+ n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function ep(t){let e=jb(t);return `[bvsala] Verification sampling is ON \
1299
1304
  (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\
1300
1305
  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\
1301
- your statement or any commission.`}function Qd(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\
1302
- \` must be a number from 0 to 1 and \`verification.maxCheckCostUsd\`, when set, a positive number (got sampleRate ${e}); verification sampling is OFF.`}var ep="[bvsala] Verification sampling is set, b\
1306
+ your statement or any commission.`}function tp(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\
1307
+ \` must be a number from 0 to 1 and \`verification.maxCheckCostUsd\`, when set, a positive number (got sampleRate ${e}); verification sampling is OFF.`}var np="[bvsala] Verification sampling is set, b\
1303
1308
  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\
1304
- g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",tp="[bvsala] verification sampling hit an internal error and skipped a request; your\
1305
- request was not affected.";function np(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?
1309
+ g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",rp="[bvsala] verification sampling hit an internal error and skipped a request; your\
1310
+ request was not affected.";function op(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?
1306
1311
  {tools:[...t.tools]}:{},...t.response?.schema?{schema:t.response.schema}:{},...G(t)!=null?{maxOutputTokens:G(t)}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.seed!==void 0?{seed:t.
1307
- seed}:{}}}function rp(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==="\
1312
+ seed}:{}}}function ip(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==="\
1308
1313
  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===
1309
1314
  "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>
1310
1315
  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?
1311
- {estrato:"tokens_compressed"}:{estrato:"unchanged"}}function op(t,e){if(!(e>0))return false;if(e>=1)return true;let n=X(`${t}:verification-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function ip(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(
1312
- i*1e10)/1e10}var Mb=32,$b=6e5;function Nb(t){return new Date(t).toISOString().slice(0,10)}var Uo=class{tasa;tope;onCheck;waitUntil;provider;precio;contrato;now;sumidero;avisar;enVuelo=new Set;cerrado=false;constructor(e){
1316
+ {estrato:"tokens_compressed"}:{estrato:"unchanged"}}function sp(t,e){if(!(e>0))return false;if(e>=1)return true;let n=X(`${t}:verification-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function ap(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(
1317
+ i*1e10)/1e10}var Bb=32,zb=6e5;function Fb(t){return new Date(t).toISOString().slice(0,10)}var Uo=class{tasa;tope;onCheck;waitUntil;provider;precio;contrato;now;sumidero;avisar;enVuelo=new Set;cerrado=false;constructor(e){
1313
1318
  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,
1314
- 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=op(o.requestId,this.tasa),s=rp({request:e,result:n,
1315
- via:r,precio:this.precio,...this.tope!==void 0?{tope:this.tope}:{}}),a;if(i&&"estrato"in s){let u=this.precio(e.model);if(!u)throw new Error("price vanished between classification and launch");a={peticion:np(
1316
- e),precios:u,estrato:s.estrato};}let c=this.now();this.sumidero.contar?.(Nb(c),"estrato"in s?s.estrato:s.excluida),a&&this.lanzar(e,n,c,a);let l="estrato"in s?{sampled:i,stratum:s.estrato}:{sampled:i,excluded:s.
1317
- excluida};return {...n,report:{...o,verification:l}}}catch{return this.avisar("verificacion-fallo-interno",tp),n}}cerrar(){this.cerrado=true;let e=[...this.enVuelo];this.enVuelo.clear();for(let n of e)if(!n.
1319
+ 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=sp(o.requestId,this.tasa),s=ip({request:e,result:n,
1320
+ via:r,precio:this.precio,...this.tope!==void 0?{tope:this.tope}:{}}),a;if(i&&"estrato"in s){let u=this.precio(e.model);if(!u)throw new Error("price vanished between classification and launch");a={peticion:op(
1321
+ e),precios:u,estrato:s.estrato};}let c=this.now();this.sumidero.contar?.(Fb(c),"estrato"in s?s.estrato:s.excluida),a&&this.lanzar(e,n,c,a);let l="estrato"in s?{sampled:i,stratum:s.estrato}:{sampled:i,excluded:s.
1322
+ excluida};return {...n,report:{...o,verification:l}}}catch{return this.avisar("verificacion-fallo-interno",rp),n}}cerrar(){this.cerrado=true;let e=[...this.enVuelo];this.enVuelo.clear();for(let n of e)if(!n.
1318
1323
  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.
1319
1324
  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??
1320
- 0,outputTokens:i.tokens.actualOutput},prices:{inputPer1k:s.inputPer1k,...s.cachedInputPer1k!==void 0?{cachedInputPer1k:s.cachedInputPer1k}:{},outputPer1k:s.outputPer1k}};if(this.enVuelo.size>=Mb){this.
1325
+ 0,outputTokens:i.tokens.actualOutput},prices:{inputPer1k:s.inputPer1k,...s.cachedInputPer1k!==void 0?{cachedInputPer1k:s.cachedInputPer1k}:{},outputPer1k:s.outputPer1k}};if(this.enVuelo.size>=Bb){this.
1321
1326
  registrar({...a,outcome:"dropped"});return}let c=()=>{},l=new Promise(d=>{c=d;}),u={base:a,abortar:new AbortController,decidido:false,reloj:void 0,terminar:c};if(this.enVuelo.add(u),u.reloj=setTimeout(()=>{
1322
- try{u.abortar.abort();}catch{}this.resolverVuelo(u,{...a,outcome:"check_failed"});},$b),u.reloj.unref?.(),setTimeout(()=>{if(u.decidido)return;let d;try{d=Promise.resolve(this.provider.generate(o.peticion,
1327
+ try{u.abortar.abort();}catch{}this.resolverVuelo(u,{...a,outcome:"check_failed"});},zb),u.reloj.unref?.(),setTimeout(()=>{if(u.decidido)return;let d;try{d=Promise.resolve(this.provider.generate(o.peticion,
1323
1328
  {signal:u.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(u,h);},()=>{this.resolverVuelo(
1324
1329
  u,{...a,outcome:"check_failed"});});},0),this.waitUntil)try{this.waitUntil(l.catch(()=>{}));}catch{}}checkDeLaRespuesta(e,n,r,o){let i=r?.usage,s=i?.inputTokens,a=i?.outputTokens,c=i?.cachedInputTokens??
1325
1330
  0,l=h=>typeof h=="number"&&Number.isSafeInteger(h)&&h>=0;if(!i||i.complete===false||!l(s)||!l(a)||!l(c)||s===0&&a===0)return {...e,outcome:"check_unmeasured"};let u=Math.min(c,s),d=r.finishReason,p=typeof d==
1326
- "string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost:ip({inputTokens:s,outputTokens:a,cachedInputTokens:u},o),inputTokens:s,cachedInputTokens:u,outputTokens:a,...p!==
1331
+ "string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost:ap({inputTokens:s,outputTokens:a,cachedInputTokens:u},o),inputTokens:s,cachedInputTokens:u,outputTokens:a,...p!==
1327
1332
  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.
1328
- 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 Ca=true,pp=new WeakSet;function jb(t){typeof t=="object"&&t!==null&&pp.add(t);}function cp(t){return typeof t=="object"&&t!==null&&pp.has(t)}function lp(t,e){switch(t){case "none":return Bb();case "inv\
1333
+ 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 Ca=true,mp=new WeakSet;function qb(t){typeof t=="object"&&t!==null&&mp.add(t);}function up(t){return typeof t=="object"&&t!==null&&mp.has(t)}function dp(t,e){switch(t){case "none":return Ub();case "inv\
1329
1334
  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\
1330
1335
  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 \
1331
1336
  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\
@@ -1333,20 +1338,20 @@ status: invalid)":"BiVelio license key is not valid (it does not verify). Check
1333
1338
  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\
1334
1339
  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\
1335
1340
  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\
1336
- license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function Bb(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 t\
1341
+ license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function Ub(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 t\
1337
1342
  he signed token from your subscription, verified offline. This published package has no unlicensed mode. To try it without paying, the free Measure license (no card) runs the layer in shadow mode. Cop\
1338
- y your key and a ready-to-paste snippet at https://savings.bivelio.com/dashboard/install (license status: none)"}function zb(){return "licenseGate must implement isActive(): a gate that cannot prove th\
1343
+ y your key and a ready-to-paste snippet at https://savings.bivelio.com/dashboard/install (license status: none)"}function Vb(){return "licenseGate must implement isActive(): a gate that cannot prove th\
1339
1344
  e license is live is refused. In this published package an injected gate is not a licensing path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license statu\
1340
- s: invalid)"}var Vo=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new _o;espejoDeCache=new kn;verjaDeCascada;memoriaDelCodebook=new $o;referenciasDeLider=new WeakMap;memoriaDeSombra=new Bo;noReproducibles=new WeakSet;negativasSinCobro=new WeakSet;comprobador;constructor(e,n={}){
1345
+ s: invalid)"}var Vo=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new Io;espejoDeCache=new kn;verjaDeCascada;memoriaDelCodebook=new $o;referenciasDeLider=new WeakMap;memoriaDeSombra=new Bo;noReproducibles=new WeakSet;negativasSinCobro=new WeakSet;comprobador;constructor(e,n={}){
1341
1346
  this.config=e,e.silenceWarnings===true&&ll(e.provider),this.deps=Ro(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>Pt()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.
1342
1347
  verjaDeCascada=new Oo(e.modelCascade?.exploration!=null?{exploracion:e.modelCascade.exploration}:{});let r=qo(e.verification);this.comprobador=r.activo&&n.verificacion?new Uo({ajustes:r,provider:e.provider,
1343
- precio:o=>this.precioConocido(o),contrato:(o,i)=>Fb(o,i),now:this.now,sumidero:n.verificacion,avisar:(o,i)=>this.avisar(o,i)}):void 0;}conVerificacion(e,n,r){return n.report.measure?n:this.comprobador?
1348
+ precio:o=>this.precioConocido(o),contrato:(o,i)=>Hb(o,i),now:this.now,sumidero:n.verificacion,avisar:(o,i)=>this.avisar(o,i)}):void 0;}conVerificacion(e,n,r){return n.report.measure?n:this.comprobador?
1344
1349
  this.comprobador.decidir(e,n,r):n}cerrarVerificacion(){this.comprobador?.cerrar();}async generate(e){this.assertLicensed(),Fs(e),e=this.conPalancasPorDefecto(e);let n={llamadas:0,falloDelProveedor:false,sinContador:0},
1345
- r;try{r=await this.generateOptimized(e,n);}catch(o){if(o instanceof Ke||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||cp(o))throw o;return this.conVerificacion(e,await this.failOpenDirect(
1350
+ r;try{r=await this.generateOptimized(e,n);}catch(o){if(o instanceof Ke||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||up(o))throw o;return this.conVerificacion(e,await this.failOpenDirect(
1346
1351
  e,o),"fail-open")}return this.conVerificacion(e,r,"optimizado")}generateStream(e,n={},r){let o;try{o=new or(this.now,n?.signal);}catch(i){let s=new or(this.now);return s.fallar(i),s.handle}return this.
1347
1352
  ejecutarStream(e,o,r),o.handle}async ejecutarStream(e,n,r){try{if(r&&await r,n.abortado)throw new Te(!1);e=this.conPalancasPorDefecto(e);let o=this.motivoDeEntregaEntera(e);if(o){let a=await this.generate(
1348
1353
  e);n.completar(a,{vivo:!1,motivo:o});return}this.assertLicensed(),Fs(e),n.entrarEnVivo();let i={llamadas:0,falloDelProveedor:!1,sinContador:0},s;try{s=await this.generateOptimized(e,i,n.sumidero);}catch(a){
1349
- if(a instanceof Ke||a instanceof Te)throw a;if(n.sumidero.senal.aborted)throw new Te(i.llamadas>0);if(this.config.failOpen===!1||i.falloDelProveedor||i.llamadas>0||cp(a))throw a;let c=this.conVerificacion(
1354
+ if(a instanceof Ke||a instanceof Te)throw a;if(n.sumidero.senal.aborted)throw new Te(i.llamadas>0);if(this.config.failOpen===!1||i.falloDelProveedor||i.llamadas>0||up(a))throw a;let c=this.conVerificacion(
1350
1355
  e,await this.failOpenDirect(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:"\
1351
1356
  shortcut"});}catch(o){n.fallar(o);}}conPalancasPorDefecto(e){let n=this.config.priceLevers,r=e.savings,o=n?.deferrable===true&&r?.deferrable===void 0,i=n?.standalone===true&&r?.standalone===void 0,s=this.config.
1352
1357
  semanticCacheDefault,a=s!==void 0&&s!==false&&r?.semanticCache===void 0;return !o&&!i&&!a?e:{...e,savings:{...r??{},...o?{deferrable:true}:{},...i?{standalone:true}:{},...a?{semanticCache:s}:{}}}}motivoDeEntregaEntera(e){
@@ -1363,7 +1368,7 @@ t does not discount reads): not claiming a cacheable prefix`}),d;if(!o.setIsStab
1363
1368
  efix cannot hit. Pruning wins here (it is a measured saving); pass the tools you want fixed."}),d;if(i)return a.record("prefix-cache","skipped",{reason:"savings.toolDiscovery is on: which schemas trav\
1364
1369
  el is decided by a non-deterministic probe, so the tool block \u2014 which renders first \u2014 varies across requests that would share a prefix fingerprint. Marking would pay the 1.25x write premium for a pref\
1365
1370
  ix that cannot hit. Turn tool discovery off to reclaim the prefix cache."}),d;let h=null;if(this.config.cacheBreakpoints==="auto"&&!u){let C=this.colocarConEspejo(e,n,r,o,s,p,a,c);if("marcado"in C)return C.
1366
- marcado;h=C.observacion;}let f=p.cacheWriteMultiplier>1&&!u,m=f?Zb(r):true,g=Ao(r);if(f&&s>g&&!m&&(a.record("prefix-cache-history","deferred",{reason:`first follow-up of this conversation: nothing shows \
1371
+ marcado;h=C.observacion;}let f=p.cacheWriteMultiplier>1&&!u,m=f?tv(r):true,g=Ao(r);if(f&&s>g&&!m&&(a.record("prefix-cache-history","deferred",{reason:`first follow-up of this conversation: nothing shows \
1367
1372
  the history will be sent again, and writing it costs ${(p.cacheWriteMultiplier-1).toFixed(2)}x of its tokens that only a later turn can recover. The history is marked from the next turn or tool-loop s\
1368
1373
  tep on.`}),s=g),s<=0){let C=f&&m?this.prefijoDeHerramientas(e,n,r,o.tools,p,a):null;return C?{...C,colocacion:h}:{...d,colocacion:h}}let b=r.slice(0,s),y=this.tokensFor(this.assemblePromptText(b,o.tools),
1369
1374
  e),v=this.tokensFor(this.assemblePromptText(r,o.tools),e),x=X(de({model:n,tools:(o.tools??[]).map(C=>C.id),prefijo:b.map(C=>`${C.role}:${C.content}`)})),E=u?`${x}|explicit`:x,S=this.verjaDeCache.decidir(
@@ -1396,9 +1401,9 @@ coincidencia.posicionDelProveedor,providerCacheRead:c,confirmed:f,...!f&&m?{cach
1396
1401
  apagada&&!p.apagada?{reason:`the provider's counter confirmed only ${h.confirmadas} of ${h.predichas} predicted cache reads: this traffic goes back to the fixed placement`}:{}});}}o.registrar({clase:s.
1397
1402
  clase,huellas:s.huellas,tramos:s.tramos,enviada:s.enviada,ultimoMarcado:u?s.ultimo:null,posicionDelProveedor:a&&u?c+l:null,ttl:s.ttl,idDelProveedor:this.config.cacheMissDiagnostics===true&&u?i.id??null:
1398
1403
  null});}async apuntarEnElAlmacen(e,n,r,o){let i=this.config.cacheBreakpointStore,s=e.colocacion,a=Qs(s.clase),c;try{c=await i.get(a);}catch(u){r.record("prefix-cache-placement","store-error",{reason:`co\
1399
- uld not read the placement store (${dp(u)}), so this request was not recorded`});return}let l=new kn;if(c!=null&&l.importarClase(s.clase,c)==="newer"){r.record("prefix-cache-placement","store-error",{
1404
+ uld not read the placement store (${fp(u)}), so this request was not recorded`});return}let l=new kn;if(c!=null&&l.importarClase(s.clase,c)==="newer"){r.record("prefix-cache-placement","store-error",{
1400
1405
  reason:"the placement store holds a state written by a newer SDK version; left untouched"});return}l.observar(s.clase,s.huellas,s.enviada),this.apuntarEnElEspejo(e,n,r,l,o);try{await i.set(a,l.exportarClase(
1401
- s.clase),rd);}catch(u){r.record("prefix-cache-placement","store-error",{reason:`could not write the placement store (${dp(u)})`});}}async cargarEspejo(e,n,r,o,i){if(this.config.cacheBreakpoints!=="auto"||
1406
+ s.clase),rd);}catch(u){r.record("prefix-cache-placement","store-error",{reason:`could not write the placement store (${fp(u)})`});}}async cargarEspejo(e,n,r,o,i){if(this.config.cacheBreakpoints!=="auto"||
1402
1407
  !o.setIsStable||i)return null;let s=$t(this.config.provider);if(e.savings?.standalone===true&&Lt(n,s))return null;let a=Ra(n,this.config.compressionEconomics);if(!a)return null;let{tramoOpenAI:c,conPrima:l}=this.
1403
1408
  primasDelColocador(e,n,a);if(!l&&!c)return null;let u=this.huellasDelColocador(e,n,r,o.tools),d=u[Ao(r)],p=new kn,h;try{let f=await this.config.cacheBreakpointStore.get(Qs(d));h=f==null?"empty":p.importarClase(
1404
1409
  d,f)==="loaded"?"loaded":"unreadable";}catch{h="unavailable";}return {clase:d,huellas:u,espejo:p,estado:h}}primasDelColocador(e,n,r){let o=$t(this.config.provider),i=e.savings?.standalone===void 0&&Lt(n,
@@ -1421,7 +1426,7 @@ observada,verifier:c.fuerza,workload:h,reason:y.razon}),{...m,modeloServido:l,en
1421
1426
  "off (gate)",{reason:y.razon,observedEscalationRate:y.observada,breakEvenEscalationRate:p.equilibrio}),{...m,elegible:true,razon:y.razon,observada:y.observada,muestras:y.muestras})}devOpen(){return false}exigirLicencia(){
1422
1427
  this.assertLicensed();}exigirPalancas(){if(this.enSombra())throw new Ke(`[bvsala] Batches are a savings lever, and the Measure license runs the layer in shadow mode: no lever is applied. Upgrade to a p\
1423
1428
  aid plan at ${zo} to submit batches. (license status: measure)`,"measure")}assertLicensed(){if(this.devOpen())return;let e=this.config.licenseGate;if(e&&typeof e.isActive=="function"){if(e.isActive())
1424
- return;let n=typeof e.status=="function"?e.status():void 0,r=typeof e.reason=="function"?e.reason():void 0;throw new Ke(lp(n,r),n)}throw e?new Ke(zb(),"invalid"):new Ke(lp("none"),"none")}avisar(e,n){
1429
+ return;let n=typeof e.status=="function"?e.status():void 0,r=typeof e.reason=="function"?e.reason():void 0;throw new Ke(dp(n,r),n)}throw e?new Ke(Vb(),"invalid"):new Ke(dp("none"),"none")}avisar(e,n){
1425
1430
  this.config.silenceWarnings||Ee(e,n);}avisarDeTruncado(e,n,r,o,i){let s=G(e),a=lr(e)||"(no contractId)",c=i?" The layer has NOTED it: the next requests for this contract will carry their value limits w\
1426
1431
  ritten into the prompt, which is the only thing that can fix it without touching your cap. If it still gets cut off, the task does not fit the contract: widen the schema and raise the cap with it.":"",
1427
1432
  l=o===null?" The schema does not bound the response (no `maxLength`/`maxItems`), so there is no way to know in advance how much it needs: bound it and the cap stops being a guess.":s==null?` The contr\
@@ -1442,7 +1447,7 @@ la] This layer was given a `semanticCacheStore`, but this request does not ask f
1442
1447
  librating cache collects no labels. Passing the cache to `createSavingsLayer` does not switch it on. Ask for it per request with `savings: { semanticCache: true }`, or on every request with `createSav\
1443
1448
  ingsLayer({ semanticCacheStore, semanticCacheDefault: true })` \u2014 preferably with a cache built with `calibration`. If you switch it on per request on purpose, set `semanticCacheDefault: false` to say \
1444
1449
  so and this warning goes away."));}async generateOptimized(e,n={llamadas:0,falloDelProveedor:false,sinContador:0},r=null){if(this.assertLicensed(),this.enSombra())return this.generarEnSombra(e,n,r);let o=new pt(
1445
- this.now),i=new at,s=nn(e),a=It(s),c=e.savings??{};this.avisarDePalancasSinConfigurar(c),c.semanticCache&&c.semanticCache!=="include-agentic"&&this.deps.semanticCache&&up(s,a)&&this.avisar("semantica-\
1450
+ this.now),i=new at,s=nn(e),a=_t(s),c=e.savings??{};this.avisarDePalancasSinConfigurar(c),c.semanticCache&&c.semanticCache!=="include-agentic"&&this.deps.semanticCache&&pp(s,a)&&this.avisar("semantica-\
1446
1451
  agentica-apagada",'[bv-sala] `savings.semanticCache` is on, but this request is agentic (it declares tools, carries tool calls or results, or holds more than one user turn), so the semantic cache was \
1447
1452
  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 under the similarity score cannot see that. The exact cache \
1448
1453
  is unaffected. To include agentic requests, set `savings.semanticCache: "include-agentic"` after measuring it on your own traffic.');let l=this.now(),u=this.decidirCascada(e,s,c,o,l),d=this.costModelFor(
@@ -1451,101 +1456,101 @@ allowSemanticCache,...a.sensitiveTopic!==null?{skipReason:"sensitive_topic",sens
1451
1456
  baselineInput=p,i.baselineOutput=h,i.baselineTools=e.tools?.length??0,c.deterministicResolvers!==false){let v=this.deps.resolvers.try(s);if(v)return i.avoidCall(p,this.tokensFor(v.text,e)),o.record("reso\
1452
1457
  lver",v.resolver,{avoided:true}),this.finish(e,s,{text:v.text,data:v.data,storedAtMs:this.now()},"deterministic",i,d,o,ar(),cr(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(u,{servedModel:e.
1453
1458
  model}))}let g=rn(s,{servedModel:u.modeloServido});if(a.allowExactCache&&c.exactCache!==false){let v=await this.deps.exactCache.get(g),x=v?ir(v.text):null;x!==null&&o.record("exact-cache","ignored: the s\
1454
- tored answer reads as a refusal written as text (text_refusal); it is not replayed",{skipReason:"text_refusal",rule:x});let E=x===null?v:null;if(E){let S=this.creditoPorReferencia(Id(E.meta),{request:e,
1459
+ tored answer reads as a refusal written as text (text_refusal); it is not replayed",{skipReason:"text_refusal",rule:x});let E=x===null?v:null;if(E){let S=this.creditoPorReferencia(_d(E.meta),{request:e,
1455
1460
  cascada:u,toggles:c,huella:m,texto:E.text,claveLeida:g,calidad:()=>{let C=e.response?.schema;return !C||be(E.data,C).valid}});return S.ok?i.avoidCallByReference(S.credit):(i.avoidCall(p,this.tokensFor(
1456
1461
  E.text,e)),i.referenceRejected=S.reason),o.record("exact-cache","hit",{ageMs:this.now()-E.storedAtMs,basis:S.ok?"reference":"estimated",...S.ok?{}:{referenceRejected:S.reason},...S.ok&&S.outputNotCredited?
1457
1462
  {outputNotCredited:S.outputNotCredited}:{}}),this.finish(e,s,E,"exact",i,d,o,ar(),cr(),this.now()-E.storedAtMs,void 0,void 0,void 0,void 0,this.informeDeCascada(u))}o.record("exact-cache","miss");}let b=An(
1458
1463
  s,{servedModel:u.modeloServido,deferrable:c.deferrable===true,toolDiscovery:c.toolDiscovery===true,...G(e)!=null?{maxOutputTokens:G(e)}:{}}),y=async()=>{try{return await this.expensivePath(n,e,s,a,c,i,d,o,
1459
- g,p,u,r,l)}catch(v){throw (n.falloDelProveedor||n.llamadas>0)&&jb(v),v}};if(a.allowSingleflight&&c.singleflight!==false){if(r){let E=this.deps.singleflight,S=typeof E.join=="function"?E.join(b):void 0;if(S){
1464
+ g,p,u,r,l)}catch(v){throw (n.falloDelProveedor||n.llamadas>0)&&qb(v),v}};if(a.allowSingleflight&&c.singleflight!==false){if(r){let E=this.deps.singleflight,S=typeof E.join=="function"?E.join(b):void 0;if(S){
1460
1465
  let C=await S;return this.noReproducibles.has(C)?(o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),y()):(o.record("singleflight","coalesced",{key:b}),this.asCoalescedFollower(
1461
1466
  C,p,this.tokensFor(C.text??"",e),d,e))}return o.record("singleflight","skipped (streaming: a streamed request never leads)"),y()}let{value:v,coalesced:x}=await this.deps.singleflight.run(b,y);if(x&&this.
1462
1467
  noReproducibles.has(v))return o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),y();if(x){o.record("singleflight","coalesced",{key:b});let E=this.creditoPorReferencia(this.
1463
1468
  referenciasDeLider.get(v)??"absent",{request:e,cascada:u,toggles:c,huella:m,texto:v.text??"",claveLeida:void 0,calidad:()=>v.report.constraints.structurallyValid!==false&&v.report.qualityStatus!=="reject\
1464
1469
  ed"});return this.asCoalescedFollower(v,p,this.tokensFor(v.text??"",e),d,e,E)}return v}return y()}async expensivePath(e,n,r,o,i,s,a,c,l,u,d,p,h){let f=this.entitled("semantic_cache"),m=null;if(i.semanticCache&&
1465
- i.semanticCache!=="include-agentic"&&this.deps.semanticCache&&up(r,o)&&c.record("semantic-cache",'skipped: agentic traffic (default); set savings.semanticCache: "include-agentic" to include it'),o.allowSemanticCache&&
1466
- i.semanticCache&&this.deps.semanticCache&&!f&&c.record("semantic-cache","degraded: feature not included in this license"),o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache&&f){let I=this.
1467
- deps.semanticCache,L=I.calibrated?await I.lookup(r,{agentic:o.isAgentic}):{hit:await I.find(r),probe:null},U=L.hit?ir(L.hit.record.answer.text):null;U!==null&&c.record("semantic-cache","ignored: the s\
1470
+ i.semanticCache!=="include-agentic"&&this.deps.semanticCache&&pp(r,o)&&c.record("semantic-cache",'skipped: agentic traffic (default); set savings.semanticCache: "include-agentic" to include it'),o.allowSemanticCache&&
1471
+ i.semanticCache&&this.deps.semanticCache&&!f&&c.record("semantic-cache","degraded: feature not included in this license"),o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache&&f){let _=this.
1472
+ deps.semanticCache,L=_.calibrated?await _.lookup(r,{agentic:o.isAgentic}):{hit:await _.find(r),probe:null},U=L.hit?ir(L.hit.record.answer.text):null;U!==null&&c.record("semantic-cache","ignored: the s\
1468
1473
  tored answer reads as a refusal written as text (text_refusal); it is not replayed",{skipReason:"text_refusal",rule:U});let H=U===null?L.hit:null;if(m=L.probe,H)return s.avoidCall(u,this.tokensFor(H.record.
1469
1474
  answer.text,n)),c.record("semantic-cache","hit",{confidence:H.confidence,similarity:H.similarity}),this.finish(n,r,H.record.answer,"semantic",s,a,c,ar(),cr(),H.ageMs,H.confidence,void 0,void 0,void 0,
1470
1475
  this.informeDeCascada(d,{servedModel:n.model}),void 0,void 0,void 0,{semantico:H});c.record("semantic-cache","miss",m?{calibration:m.reason,score:m.score}:void 0);}let g=i.router===false,b=g?ar():this.deps.
1471
1476
  router.classify(r);c.record("router",b.executionClass,{confidence:b.confidence,reason:b.reason});let y=this.planearBusquedaNativa(n,i,b.executionClass,g,d,a,c),v=y?y.seleccion:g?this.deps.toolSelector.
1472
1477
  passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,b.executionClass,r.toolsetHash);if(y||(this.avisarDeHerramientasPodadas(n,i,v,b.executionClass,g,d,a),this.avisarDeCatalogoGrande(
1473
- n,i,v,d,a)),s.actualTools=v.tools.length,v.droppedIds.length){let I=new Set(v.droppedIds),L=(n.tools??[]).filter(U=>I.has(U.id)).reduce((U,H)=>U+this.tokensFor(ur(H),n),0);s.eliminate(L),c.record("too\
1478
+ n,i,v,d,a)),s.actualTools=v.tools.length,v.droppedIds.length){let _=new Set(v.droppedIds),L=(n.tools??[]).filter(U=>_.has(U.id)).reduce((U,H)=>U+this.tokensFor(ur(H),n),0);s.eliminate(L),c.record("too\
1474
1479
  l-selector",v.reason,{dropped:v.droppedIds,eliminatedTokens:L});}s.baselineRetrieval=this.config.retriever?b.rounds:0;let x=await Mr({execution:b.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.
1475
1480
  maxRounds??b.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});s.actualRetrieval=
1476
- x.rounds,x.retrievedCount>0&&c.record("retrieval",`kept ${x.keptCount}/${x.retrievedCount}`,{rounds:x.rounds});let E=cr(),S=[...n.messages],C=Ia(n.messages),A=false,T=x.docs.length>0?{role:"system",content:`\
1481
+ x.rounds,x.retrievedCount>0&&c.record("retrieval",`kept ${x.keptCount}/${x.retrievedCount}`,{rounds:x.rounds});let E=cr(),S=[...n.messages],C=_a(n.messages),A=false,T=x.docs.length>0?{role:"system",content:`\
1477
1482
  Retrieved context \u2014 answer using only this evidence and cite sources by [id]:
1478
1483
 
1479
- `+x.docs.map((I,L)=>`[${I.source??I.id??`doc${L+1}`}]
1480
- ${I.text}`).join(`
1484
+ `+x.docs.map((_,L)=>`[${_.source??_.id??`doc${L+1}`}]
1485
+ ${_.text}`).join(`
1481
1486
 
1482
1487
  `)}:null,R=lr(n),M=G(n),w=M!=null?Math.floor(M*3.2):null,P=this.contratosQueIncumplen.has(R)?Pa(n.response?.schema,"",w):"";if(P&&dr(S,{role:"system",content:`JSON limits (not API-enforced): ${P}`}),n.
1483
- structuredData!==void 0){let I=JSON.stringify(n.structuredData),L=this.tokensFor(I,n);if(i.serialization!==false){E=this.deps.formatSelector.choose(n.structuredData,{model:n.model,...n.tokenizer?{tokenizer:n.
1488
+ structuredData!==void 0){let _=JSON.stringify(n.structuredData),L=this.tokensFor(_,n);if(i.serialization!==false){E=this.deps.formatSelector.choose(n.structuredData,{model:n.model,...n.tokenizer?{tokenizer:n.
1484
1489
  tokenizer}:{}});let U=this.tokensFor(E.encoded+E.instruction,n);s.compress(L,U),dr(S,{role:"system",content:(E.instruction?E.instruction+`
1485
- `:"")+E.encoded}),c.record("serialization",E.chosen,{reason:E.reason,jsonTokens:L,chosenTokens:U});}else dr(S,{role:"system",content:I}),c.record("serialization","json-compact",{reason:"format selector\
1486
- disabled; sent compact JSON"});}if(T&&dr(S,T),(i.compression===true||i.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let I=this.config.compressionEconomics??
1487
- {},L=No(n.model,I),U={compressorCostTokens:I.compressorCostTokens??0,...I.minimumContextTokens!=null?{minimumContextTokens:I.minimumContextTokens}:{},...I.minimumNetTokens!=null?{minimumNetTokens:I.minimumNetTokens}:
1490
+ `:"")+E.encoded}),c.record("serialization",E.chosen,{reason:E.reason,jsonTokens:L,chosenTokens:U});}else dr(S,{role:"system",content:_}),c.record("serialization","json-compact",{reason:"format selector\
1491
+ disabled; sent compact JSON"});}if(T&&dr(S,T),(i.compression===true||i.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let _=this.config.compressionEconomics??
1492
+ {},L=No(n.model,_),U={compressorCostTokens:_.compressorCostTokens??0,..._.minimumContextTokens!=null?{minimumContextTokens:_.minimumContextTokens}:{},..._.minimumNetTokens!=null?{minimumNetTokens:_.minimumNetTokens}:
1488
1493
  {}},H=0,re=0;for(let fe of S)fe.role==="system"?H+=1:re+=this.tokensFor(fe.content,n);let ot=this.tokensFor(this.assemblePromptText(S,v.tools),n),pe=zn({...U,contextTokens:re,projectedEliminable:re}),
1489
- ue=0,Z=0,Me=false,Ie=pe.reason;if(pe.compress){let fe=[];for(let te of S){if(te.role==="system"){fe.push(te);continue}let Pn=this.tokensFor(te.content,n),In=await this.config.compressor.compress({text:te.
1490
- content}),Za=!In.skipped&&In.fidelityPassed&&Nc(te.content,In.compressed),Xa=Za?this.tokensFor(In.compressed,n):Pn;Za&&Xa<Pn?(fe.push({...te,content:In.compressed}),ue+=Pn,Z+=Xa):fe.push(te);}let it=this.
1491
- tokensFor(this.assemblePromptText(fe,v.tools),n),Se=zn({...U,contextTokens:re,projectedEliminable:ue-Z}),xr=xd({originalTokens:ot,compressedTokens:it,tier:L,...I.prefix?{prefix:I.prefix}:{},compressorCostTokens:U.
1492
- compressorCostTokens});Z>=ue?Ie="no fidelity-passed net reduction":Se.compress?xr.comprimir?(Me=true,Ie=xr.razon,A=fe.slice(0,C).some((te,Pn)=>te.content!==S[Pn]?.content),S=fe,s.compress(ue,Z)):Ie=xr.razon:
1493
- Ie=Se.reason;}Me||(ue=0,Z=0),c.record("compression",Me?"applied":"skipped",{reason:Ie,before:ue,after:Z,contextTokens:re,promptTokens:ot,cacheTierMinimum:L.minimumCacheTokens,protectedSystemMessages:H,
1494
- prefixRewritten:A}),s.compressionReport={originalTokens:ue,compressedTokens:Z,protectedSpans:H,fidelityPassed:true};}if(i.elision!==false&&o.allowElision&&this.entitled("tool_result_elision")){let I=yd(S);if(I.
1495
- indices.length>0){let L=this.tokensFor(ua,n),U=0;for(let H of I.indices){let re=this.tokensFor(S[H].content,n);U+=Math.max(0,re-L);}(I.indices.some(H=>H<C)&&(A=true),S=kd(S,I.indices),s.eliminate(U),
1496
- s.elididoLocal+=U),c.record("elision","applied",{elided:I.indices.length,eliminatedTokens:U,grossBytes:I.bytesOriginales,live:Ca});}else c.record("elision","skipped",{reason:"no old/large t\
1497
- ool_result over the age\xD7size threshold"});}let $=Yb(this.config.toolOutputCompaction,i.toolOutputCompaction);if($&&!this.entitled("long_context_compression")&&c.record("tool-output-compaction","degr\
1498
- aded: feature not included in this license"),$&&o.allowCompression&&this.entitled("long_context_compression")){let I=qc(S,$),L=0,U=0,H=0,re=0,ot={};if(I.compactados.length>0){let ue=S.slice();for(let Z of I.
1499
- compactados){let Me=S[Z.indice],Ie=this.tokensFor(Me.content,n),fe=this.tokensFor(Z.texto,n);ue[Z.indice]={...Me,content:Z.texto},L+=Ie,U+=fe,Z.enLaCola?H+=Math.max(0,Ie-fe):re+=Math.max(0,Ie-fe);for(let it of Z.
1500
- aplicadas)ot[it]=(ot[it]??0)+1;}S=ue,s.compress(L,U),s.compactedLocal+=Math.max(0,L-U);}let pe=No(n.model,this.config.compressionEconomics);c.record("tool-output-compaction",I.compactados.length>0?"appl\
1501
- ied":"skipped",{compacted:I.compactados.length,before:L,after:U,tailSavedTokens:H,replayedSavedTokens:re,transforms:ot,fileViewsKeptVerbatim:I.vistasDeFichero,exceptedTools:I.exceptuados,cacheWriteMultiplier:pe.
1494
+ ue=0,Z=0,Me=false,_e=pe.reason;if(pe.compress){let fe=[];for(let te of S){if(te.role==="system"){fe.push(te);continue}let Pn=this.tokensFor(te.content,n),_n=await this.config.compressor.compress({text:te.
1495
+ content}),Za=!_n.skipped&&_n.fidelityPassed&&Nc(te.content,_n.compressed),Xa=Za?this.tokensFor(_n.compressed,n):Pn;Za&&Xa<Pn?(fe.push({...te,content:_n.compressed}),ue+=Pn,Z+=Xa):fe.push(te);}let it=this.
1496
+ tokensFor(this.assemblePromptText(fe,v.tools),n),Se=zn({...U,contextTokens:re,projectedEliminable:ue-Z}),xr=xd({originalTokens:ot,compressedTokens:it,tier:L,..._.prefix?{prefix:_.prefix}:{},compressorCostTokens:U.
1497
+ compressorCostTokens});Z>=ue?_e="no fidelity-passed net reduction":Se.compress?xr.comprimir?(Me=true,_e=xr.razon,A=fe.slice(0,C).some((te,Pn)=>te.content!==S[Pn]?.content),S=fe,s.compress(ue,Z)):_e=xr.razon:
1498
+ _e=Se.reason;}Me||(ue=0,Z=0),c.record("compression",Me?"applied":"skipped",{reason:_e,before:ue,after:Z,contextTokens:re,promptTokens:ot,cacheTierMinimum:L.minimumCacheTokens,protectedSystemMessages:H,
1499
+ prefixRewritten:A}),s.compressionReport={originalTokens:ue,compressedTokens:Z,protectedSpans:H,fidelityPassed:true};}if(i.elision!==false&&o.allowElision&&this.entitled("tool_result_elision")){let _=yd(S);if(_.
1500
+ indices.length>0){let L=this.tokensFor(ua,n),U=0;for(let H of _.indices){let re=this.tokensFor(S[H].content,n);U+=Math.max(0,re-L);}(_.indices.some(H=>H<C)&&(A=true),S=kd(S,_.indices),s.eliminate(U),
1501
+ s.elididoLocal+=U),c.record("elision","applied",{elided:_.indices.length,eliminatedTokens:U,grossBytes:_.bytesOriginales,live:Ca});}else c.record("elision","skipped",{reason:"no old/large t\
1502
+ ool_result over the age\xD7size threshold"});}let $=ev(this.config.toolOutputCompaction,i.toolOutputCompaction);if($&&!this.entitled("long_context_compression")&&c.record("tool-output-compaction","degr\
1503
+ aded: feature not included in this license"),$&&o.allowCompression&&this.entitled("long_context_compression")){let _=qc(S,$),L=0,U=0,H=0,re=0,ot={};if(_.compactados.length>0){let ue=S.slice();for(let Z of _.
1504
+ compactados){let Me=S[Z.indice],_e=this.tokensFor(Me.content,n),fe=this.tokensFor(Z.texto,n);ue[Z.indice]={...Me,content:Z.texto},L+=_e,U+=fe,Z.enLaCola?H+=Math.max(0,_e-fe):re+=Math.max(0,_e-fe);for(let it of Z.
1505
+ aplicadas)ot[it]=(ot[it]??0)+1;}S=ue,s.compress(L,U),s.compactedLocal+=Math.max(0,L-U);}let pe=No(n.model,this.config.compressionEconomics);c.record("tool-output-compaction",_.compactados.length>0?"appl\
1506
+ ied":"skipped",{compacted:_.compactados.length,before:L,after:U,tailSavedTokens:H,replayedSavedTokens:re,transforms:ot,fileViewsKeptVerbatim:_.vistasDeFichero,exceptedTools:_.exceptuados,cacheWriteMultiplier:pe.
1502
1507
  cacheWriteMultiplier,cacheReadMultiplier:pe.cacheReadMultiplier,note:"counted in tokens.compressedInput only; never priced into savings or commission. each tail token saved is one token fewer written \
1503
- now and re-read on every later turn"});}let O=n.response?.schema,D=O&&i.outputCodebook===true?md(O,I=>this.tokensFor(I,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,lr(n),i.outputCodebookMeasuredOutputDeltaTokens)}):
1508
+ now and re-read on every later turn"});}let O=n.response?.schema,D=O&&i.outputCodebook===true?md(O,_=>this.tokensFor(_,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,lr(n),i.outputCodebookMeasuredOutputDeltaTokens)}):
1504
1509
  null;D&&c.record("output-codebook",D.applied?"applied":"skipped",{reason:D.reason,...D.applied?{renamedKeys:D.plan.renamedKeys,codedEnumValues:D.plan.codedEnumValues,schemaTokensOriginal:D.plan.schemaTokensOriginal,
1505
1510
  schemaTokensCompact:D.plan.schemaTokensCompact,modelledShapeSavingTokens:D.plan.modelledShapeSavingTokens,measuredOutputDeltaTokens:D.plan.measuredOutputDeltaTokens,outputDeltaProvenance:D.plan.outputDeltaProvenance,
1506
1511
  breakEvenOutputDeltaTokens:D.plan.breakEvenOutputDeltaTokens,netSavingUsd:D.plan.netSavingUsd,pricedForModel:d.modeloServido}:{}});let F=D?.applied?D.plan.compactSchema:O,j=F?zr(d.modeloServido,F,this.
1507
1512
  deps.constraintBackends):{backend:"none",reason:"no output contract"};c.record("constraints",j.backend,{reason:j.reason});let q=y?{tools:y.prefijo,setIsStable:v.setIsStable}:v,J=i.toolDiscovery===true&&
1508
- !y,Y=this.config.cacheBreakpointStore?await this.cargarEspejo(n,d.modeloServido,S,q,J):null,B=this.decidirMarcadoDeCache(n,d.modeloServido,S,q,J,A?Ia(S,true):C,c,Y),Re=this.now();if(p?.senal.aborted)throw new Te(
1513
+ !y,Y=this.config.cacheBreakpointStore?await this.cargarEspejo(n,d.modeloServido,S,q,J):null,B=this.decidirMarcadoDeCache(n,d.modeloServido,S,q,J,A?_a(S,true):C,c,Y),Re=this.now();if(p?.senal.aborted)throw new Te(
1509
1514
  e.llamadas>0);let ee=y?this.sinDescubrimientoPorBusquedaNativa(i,v.tools,c):await this.descubrirHerramientas(e,n,i,v.tools,S,s,a,c),Kt=ee.tools;s.actualTools=Kt.length;let hr={messages:S,...Kt.length?
1510
1515
  {tools:Kt}:{},...F?{schema:F}:{},...G(n)!=null?{maxOutputTokens:G(n)}:{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{},...n.reasoningEffort!=null?{reasoningEffort:n.
1511
1516
  reasoningEffort}:{},...i.deferrable?{deferrable:true}:{},...B.explicita?{explicitCacheWrites:true}:{},...y?{toolSearch:y.plan}:{},constraintBackend:j.backend},gr={model:d.modeloServido,...hr,...B.marcar?{
1512
1517
  stablePrefixMessages:B.mensajesDePrefijo,promptCacheKey:B.huella,...B.colocacion&&!B.explicita&&(B.colocacion.cola||B.colocacion.ttl!=="5m")?{cachePlacement:{tail:B.colocacion.cola,ttl:B.colocacion.ttl}}:
1513
- {},...this.config.cacheMissDiagnostics===true&&B.colocacion?{cacheDiagnostics:{previousMessageId:B.colocacion.coincidencia?.idDelProveedor??null}}:{}}:{}},_,Ha=false,Mp={...e};try{_=p?await this.llamarProveedorEnStream(
1514
- gr,e,p):await this.llamarProveedor(gr,e);}catch(I){if(!this.respaldaFaltaDeCapacidad(i,I,p))throw I;Object.assign(e,Mp),Ha=true,c.record("deferred-tier","capacity-fallback",{error:I instanceof Error?I.message.
1515
- slice(0,200):String(I),reason:'the cheaper tier had no capacity; repeated once at the standard tier and price, as configured with priceLevers.onCapacityError: "standard"'});let{deferrable:L,...U}=gr;_=
1516
- await this.llamarProveedor(U,e);}let $p=Gr(_),Np=_.servedServiceTier;y&&c.record("tool-search","provider",{searches:_.toolSearch?.searches??null,loaded:_.toolSearch?.loaded??[],errors:_.toolSearch?.errors??
1517
- 0,resentResults:_.toolSearch?.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 counte\
1518
- r and credited to no ledger":"the adapter did not report what the search did"}),s.actualLlm+=1;let oi=I=>{if(!D?.applied)return I;let L=et(I);return L.ok?JSON.stringify(D.plan.expand(L.value)):I},he=oi(
1519
- _.text),qe=_.usage,jp=_.unbilledRefusal===true,Wa={..._.providerMessageId?{id:_.providerMessageId}:{},..._.cacheDiagnostics?{diagnostico:_.cacheDiagnostics}:{}},nt=false;if(d.enruta){let I=na({texto:he,schema:O,
1520
- finishReason:_.finishReason,pidioHerramientas:(_.toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!I.acepta),c.record("model-cascade",I.acepta?"accepted":"escalating",{servedModel:d.modeloServido,
1521
- reason:I.motivo,checks:I.comprobaciones}),I.acepta||(nt=true,s.cascadeAttempt(_.usage,_.unbilledRefusal===true?{inputPer1k:0,outputPer1k:0,cachedInputPer1k:0}:d.precioBarato??a,B.marcar&&B.cacheWriteMultiplier>
1522
- 1?1:Fn(d.modeloServido)),s.actualLlm+=1,_=await this.llamarProveedor({model:n.model,...hr},e),he=oi(_.text));}let Le=nt?n.model:d.modeloServido,En=nt?this.costModelFor(n.model,h):a;s.actualInput+=_.usage.
1523
- inputTokens,s.actualOutput+=_.usage.outputTokens,_.unbilledRefusal===true&&s.unbilledCall(_.usage);let Bp=_.usage,zp=_.servedServiceTier,Fp=_.structuredNatively===true,br=Gr(_),qp=ol(this.config.provider),
1524
- Ga;D?.applied&&c.record("output-codebook",et(_.text).ok?"expanded":"not-expanded (response was not JSON)",et(_.text).ok?{localOutputTokensCompact:this.tokensFor(_.text,n),localOutputTokensExpanded:this.
1525
- tokensFor(he,n),creditedLedger:"none",note:"local count of the served answer in both shapes; not credited to any ledger"}:{}),O&&j.backend==="provider-native"&&_.structuredNatively===false&&(j={backend:"\
1518
+ {},...this.config.cacheMissDiagnostics===true&&B.colocacion?{cacheDiagnostics:{previousMessageId:B.colocacion.coincidencia?.idDelProveedor??null}}:{}}:{}},I,Ha=false,Np={...e};try{I=p?await this.llamarProveedorEnStream(
1519
+ gr,e,p):await this.llamarProveedor(gr,e);}catch(_){if(!this.respaldaFaltaDeCapacidad(i,_,p))throw _;Object.assign(e,Np),Ha=true,c.record("deferred-tier","capacity-fallback",{error:_ instanceof Error?_.message.
1520
+ slice(0,200):String(_),reason:'the cheaper tier had no capacity; repeated once at the standard tier and price, as configured with priceLevers.onCapacityError: "standard"'});let{deferrable:L,...U}=gr;I=
1521
+ await this.llamarProveedor(U,e);}let jp=Gr(I),Bp=I.servedServiceTier;y&&c.record("tool-search","provider",{searches:I.toolSearch?.searches??null,loaded:I.toolSearch?.loaded??[],errors:I.toolSearch?.errors??
1522
+ 0,resentResults:I.toolSearch?.resent?.results??0,resentTools:I.toolSearch?.resent?.tools??[],reason:I.toolSearch?"what the provider's tool search did in this call; its cost is in the provider's counte\
1523
+ r and credited to no ledger":"the adapter did not report what the search did"}),s.actualLlm+=1;let oi=_=>{if(!D?.applied)return _;let L=et(_);return L.ok?JSON.stringify(D.plan.expand(L.value)):_},he=oi(
1524
+ I.text),qe=I.usage,zp=I.unbilledRefusal===true,Wa={...I.providerMessageId?{id:I.providerMessageId}:{},...I.cacheDiagnostics?{diagnostico:I.cacheDiagnostics}:{}},nt=false;if(d.enruta){let _=na({texto:he,schema:O,
1525
+ finishReason:I.finishReason,pidioHerramientas:(I.toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!_.acepta),c.record("model-cascade",_.acepta?"accepted":"escalating",{servedModel:d.modeloServido,
1526
+ reason:_.motivo,checks:_.comprobaciones}),_.acepta||(nt=true,s.cascadeAttempt(I.usage,I.unbilledRefusal===true?{inputPer1k:0,outputPer1k:0,cachedInputPer1k:0}:d.precioBarato??a,B.marcar&&B.cacheWriteMultiplier>
1527
+ 1?1:Fn(d.modeloServido)),s.actualLlm+=1,I=await this.llamarProveedor({model:n.model,...hr},e),he=oi(I.text));}let Le=nt?n.model:d.modeloServido,En=nt?this.costModelFor(n.model,h):a;s.actualInput+=I.usage.
1528
+ inputTokens,s.actualOutput+=I.usage.outputTokens,I.unbilledRefusal===true&&s.unbilledCall(I.usage);let Fp=I.usage,qp=I.servedServiceTier,Up=I.structuredNatively===true,br=Gr(I),Vp=ol(this.config.provider),
1529
+ Ga;D?.applied&&c.record("output-codebook",et(I.text).ok?"expanded":"not-expanded (response was not JSON)",et(I.text).ok?{localOutputTokensCompact:this.tokensFor(I.text,n),localOutputTokensExpanded:this.
1530
+ tokensFor(he,n),creditedLedger:"none",note:"local count of the served answer in both shapes; not credited to any ledger"}:{}),O&&j.backend==="provider-native"&&I.structuredNatively===false&&(j={backend:"\
1526
1531
  none",reason:"provider did not enforce the contract natively; the schema travelled in the prompt and the layer is the only validator"},c.record("constraints","none",{downgradedFrom:"provider-native",reason:j.
1527
- reason})),s.sentInputLocal=this.tokensFor(this.assemblePromptText(S,Kt),n),s.removedInputLocal=Math.max(0,u-s.sentInputLocal-s.elididoLocal-s.compactedLocal);let Up=s.sentInputLocal;s.sentInputLocal+=
1528
- ee.tokensLocalesDelSondeo,s.estimatorExact=this.estimatorEsExacto(n),_.usage.cachedInputTokens&&s.providerCached(_.usage.cachedInputTokens),_.unbilledRefusal!==true&&s.nativeCacheWrite(_.usage.cacheWriteInputTokens??
1529
- 0,_.usage.cacheWrite1hInputTokens??0),s.nativeCacheMarkedByLayer=!nt&&B.marcar;let Ka=Fn(Le),Vp=!nt&&B.marcar&&B.cacheWriteMultiplier>1;if(Ka>1&&!Vp&&_.unbilledRefusal!==true&&(_.usage.cacheWriteInputTokens??
1530
- 0)>0&&s.providerCacheWritePremium(_.usage.cacheWriteInputTokens??0,Ka,En),B.marcar&&qe.complete===false)c.record("prefix-cache","not measured: the provider reported no usage for this call");else if(B.marcar&&
1531
- jp)c.record("prefix-cache","not measured: the marked call was a refusal the provider does not bill");else if(B.marcar){let I=Math.max(0,qe.cacheWriteInputTokens??0),L=Math.min(I,Math.max(0,qe.cacheWrite1hInputTokens??
1532
- (B.colocacion?.ttl==="1h"?I:0)));s.cacheWritePremium(I-L,B.cacheWriteMultiplier,d.precioBarato??a),L>0&&s.cacheWritePremium(L,qn(d.modeloServido),d.precioBarato??a),this.verjaDeCache.registrar(B.claveDeVerja,
1532
+ reason})),s.sentInputLocal=this.tokensFor(this.assemblePromptText(S,Kt),n),s.removedInputLocal=Math.max(0,u-s.sentInputLocal-s.elididoLocal-s.compactedLocal);let Hp=s.sentInputLocal;s.sentInputLocal+=
1533
+ ee.tokensLocalesDelSondeo,s.estimatorExact=this.estimatorEsExacto(n),I.usage.cachedInputTokens&&s.providerCached(I.usage.cachedInputTokens),I.unbilledRefusal!==true&&s.nativeCacheWrite(I.usage.cacheWriteInputTokens??
1534
+ 0,I.usage.cacheWrite1hInputTokens??0),s.nativeCacheMarkedByLayer=!nt&&B.marcar;let Ka=Fn(Le),Wp=!nt&&B.marcar&&B.cacheWriteMultiplier>1;if(Ka>1&&!Wp&&I.unbilledRefusal!==true&&(I.usage.cacheWriteInputTokens??
1535
+ 0)>0&&s.providerCacheWritePremium(I.usage.cacheWriteInputTokens??0,Ka,En),B.marcar&&qe.complete===false)c.record("prefix-cache","not measured: the provider reported no usage for this call");else if(B.marcar&&
1536
+ zp)c.record("prefix-cache","not measured: the marked call was a refusal the provider does not bill");else if(B.marcar){let _=Math.max(0,qe.cacheWriteInputTokens??0),L=Math.min(_,Math.max(0,qe.cacheWrite1hInputTokens??
1537
+ (B.colocacion?.ttl==="1h"?_:0)));s.cacheWritePremium(_-L,B.cacheWriteMultiplier,d.precioBarato??a),L>0&&s.cacheWritePremium(L,qn(d.modeloServido),d.precioBarato??a),this.verjaDeCache.registrar(B.claveDeVerja,
1533
1538
  qe),c.record("prefix-cache","measured",{cacheRead:qe.cachedInputTokens??0,cacheWritePremiumTokens:qe.cacheWriteInputTokens??0,...L>0?{cacheWrite1hTokens:L}:{}});}B.colocacion?.conAlmacen?await this.apuntarEnElAlmacen(
1534
- B,qe,c,Wa):B.colocacion&&this.apuntarEnElEspejo(B,qe,c,this.espejoDeCache,Wa);let Jt=null;if(d.modo==="shadow"&&d.elegible&&d.candidato&&d.precioBarato&&Kb(l,d.tasaDeMuestreo))try{let I=await this.llamarProveedor(
1535
- {model:d.candidato,...hr},e);s.actualLlm+=1;let L=s.extraCostUsd;s.cascadeAttempt(I.usage,d.precioBarato,Fn(d.candidato));let U=oi(I.text),H=na({texto:U,schema:O,finishReason:I.finishReason,pidioHerramientas:(I.
1539
+ B,qe,c,Wa):B.colocacion&&this.apuntarEnElEspejo(B,qe,c,this.espejoDeCache,Wa);let Jt=null;if(d.modo==="shadow"&&d.elegible&&d.candidato&&d.precioBarato&&Xb(l,d.tasaDeMuestreo))try{let _=await this.llamarProveedor(
1540
+ {model:d.candidato,...hr},e);s.actualLlm+=1;let L=s.extraCostUsd;s.cascadeAttempt(_.usage,d.precioBarato,Fn(d.candidato));let U=oi(_.text),H=na({texto:U,schema:O,finishReason:_.finishReason,pidioHerramientas:(_.
1536
1541
  toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!H.acepta);let re=H.acepta?ud(U,he):null;Jt={coste:s.extraCostUsd-L,divergio:re?re.divergen:null},c.record("model-cascade",H.acepta?"sa\
1537
1542
  mple accepted":"sample escalated",{candidateModel:d.candidato,reason:H.motivo,sampleCost:Jt.coste,...re?{diverged:re.divergen,divergence:re.motivo}:{},note:"measurement only: this answer was NEVER ser\
1538
- ved. The escalation rate it feeds is a money figure, not a quality one"});}catch(I){c.record("model-cascade","sample failed (measurement only; the answer is unaffected)",{error:I instanceof Error?I.message:
1539
- String(I)});}let vr=he,Ct=true,Ue={},Tt=(_.toolCalls?.length??0)>0;if(Tt&&(Ct=null,O&&c.record("validation","n/a: model requested tool calls (the output contract applies to the final answer)")),O&&!Tt){let I=et(
1540
- he),L=I.ok?be(I.value,O):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},U=false;I.ok&&I.rescatado!=null&&L.valid&&(he=I.rescatado,U=true,c.record("validation","rescued-locally",{reason:"the model \
1541
- wrapped valid JSON in prose or a markdown fence; it was extracted locally instead of paying a repair call"})),!L.valid&&Jb(L.errors)&&this.contratosQueIncumplen.add(lr(n));let H=_.finishReason==="leng\
1542
- th",re=Ta(_),ot=!L.valid&&L.errors.some(pe=>/not a valid regular expression/.test(pe.message));if(!L.valid&&ot)c.record("validation","repair-skipped",{reason:"schema defect (uncompilable pattern); no \
1543
+ ved. The escalation rate it feeds is a money figure, not a quality one"});}catch(_){c.record("model-cascade","sample failed (measurement only; the answer is unaffected)",{error:_ instanceof Error?_.message:
1544
+ String(_)});}let vr=he,Ct=true,Ue={},Tt=(I.toolCalls?.length??0)>0;if(Tt&&(Ct=null,O&&c.record("validation","n/a: model requested tool calls (the output contract applies to the final answer)")),O&&!Tt){let _=et(
1545
+ he),L=_.ok?be(_.value,O):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},U=false;_.ok&&_.rescatado!=null&&L.valid&&(he=_.rescatado,U=true,c.record("validation","rescued-locally",{reason:"the model \
1546
+ wrapped valid JSON in prose or a markdown fence; it was extracted locally instead of paying a repair call"})),!L.valid&&Qb(L.errors)&&this.contratosQueIncumplen.add(lr(n));let H=I.finishReason==="leng\
1547
+ th",re=Ta(I),ot=!L.valid&&L.errors.some(pe=>/not a valid regular expression/.test(pe.message));if(!L.valid&&ot)c.record("validation","repair-skipped",{reason:"schema defect (uncompilable pattern); no \
1543
1548
  output can satisfy it, a retry is a wasted call",errors:L.errors}),this.avisar("esquema-roto","[bvsala] The response contract has a `pattern` that is not a valid regex, so no response can satisfy it. \
1544
1549
  NOT retried (it would be a paid call for the same failure). Fix the schema's `pattern`."),Ue.reparacion={outcome:"skipped",skipReason:"schema_defect"};else if(!L.valid&&re)c.record("validation","repai\
1545
- r-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\
1550
+ r-skipped",{reason:(I.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\
1546
1551
  same model would be refused, and may be billed, again",model:Le}),Ue.reparacion={outcome:"skipped",skipReason:"provider_refusal"};else if(!L.valid&&H){let pe=pd(O,Me=>this.tokensFor(Me,n)),ue=G(n)??null,
1547
1552
  Z=pe!==null&&ue!=null&&pe<=ue;Z&&this.contratosQueIncumplen.add(lr(n)),c.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same cap would truncate aga\
1548
- in",maxOutputTokens:G(n)??null,outputTokens:_.usage.outputTokens,model:Le,...pe!==null?{schemaAllowsTokens:pe}:{},learnedValueLimits:Z}),this.avisarDeTruncado(n,Le,_.usage.outputTokens,pe,Z),Ue.reparacion=
1553
+ in",maxOutputTokens:G(n)??null,outputTokens:I.usage.outputTokens,model:Le,...pe!==null?{schemaAllowsTokens:pe}:{},learnedValueLimits:Z}),this.avisarDeTruncado(n,Le,I.usage.outputTokens,pe,Z),Ue.reparacion=
1549
1554
  {outcome:"skipped",skipReason:"output_truncated"};}else if(!L.valid&&j.backend==="none"){let pe=L.errors.slice(0,5).map(te=>`- ${te.path}: ${te.message}`).join(`
1550
1555
  `),ue=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
1551
1556
 
@@ -1555,48 +1560,48 @@ ${he}
1555
1560
  Problems found:
1556
1561
  ${pe}
1557
1562
 
1558
- Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],Z=this.tokensFor(this.assemblePromptText(ue),n),Me=s.sentInputLocal>0?s.actualInput/s.sentInputLocal:1,Ie=Math.
1559
- round(Me*Z),fe=Math.min(_.usage.outputTokens,G(n)??Number.POSITIVE_INFINITY),it=Ie/1e3*En.inputPer1k+fe/1e3*En.outputPer1k,Se=this.config.skipRepairAboveBaseline?s.estimateCost(En):void 0;if(Se!=null&&
1563
+ Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],Z=this.tokensFor(this.assemblePromptText(ue),n),Me=s.sentInputLocal>0?s.actualInput/s.sentInputLocal:1,_e=Math.
1564
+ round(Me*Z),fe=Math.min(I.usage.outputTokens,G(n)??Number.POSITIVE_INFINITY),it=_e/1e3*En.inputPer1k+fe/1e3*En.outputPer1k,Se=this.config.skipRepairAboveBaseline?s.estimateCost(En):void 0;if(Se!=null&&
1560
1565
  Se.baselineEstimate>0&&Se.actual+it>Se.baselineEstimate&&Se!=null)c.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the invalid answer is serve\
1561
1566
  d as-is and reported as invalid",errors:L.errors,baselineUsd:Se.baselineEstimate,actualUsd:Se.actual,repairEstimateUsd:it}),this.avisar("reparacion-mas-cara-que-el-baseline",`[bvsala] The answer did n\
1562
1567
  ot satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${Se.baselineEstimate}, already spent ~$${Se.actual}, repair ~$${it.
1563
1568
  toFixed(6)}). The repair was skipped and the invalid answer is returned with \`constraints.structurallyValid: false\` \u2014 check it before using it. This combination is usually a request carrying both tool\
1564
1569
  s and an output contract; see the adapter warning for the cheaper shapes.`),Ue.reparacion={outcome:"skipped",skipReason:"would_cost_more_than_no_layer"};else {s.retries=1,c.record("validation","repair-\
1565
- attempt",{errors:L.errors}),_=await this.llamarProveedor({model:Le,messages:ue,schema:O,...G(n)!=null?{maxOutputTokens:G(n)}:{}},e),Ga=_.usage,s.actualLlm+=1,s.actualInput+=_.usage.inputTokens,s.actualOutput+=
1566
- _.usage.outputTokens,s.repairOutput+=_.usage.outputTokens,s.repairInput+=_.usage.inputTokens,_.unbilledRefusal===true&&s.unbilledCall(_.usage),s.sentInputLocal+=Z,he=_.text;let te=et(he);L=te.ok?be(te.value,
1567
- O):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},te.ok&&(vr=te.value,te.rescatado!=null&&L.valid&&(he=te.rescatado)),Ue.reparacion={outcome:L.valid?"repaired":"still_invalid"};}}else I.ok&&(vr=
1568
- I.value);Ct=L.valid,!L.valid&&Ue.reparacion===void 0&&(Ue.reparacion={outcome:"skipped",skipReason:"decode_time_constraint"}),Ue.validacion={resultado:L.valid?"passed":"failed",errores:L.errors.length,
1569
- desenvuelto:U},c.record("validation",Ct?"valid":"invalid");}let Hp=this.now()-Re,Wp=Vb(vr),Yt={text:he,data:vr,rendered:Wp,storedAtMs:this.now()},ge=this.informeDeDiferido(i,_,Le,Ha),Pe=this.informeDeEscrituras(
1570
- i,$p,qe,Np,d.modeloServido,B.marcar,B.explicitaPorColocador);Pe&&c.record("cache-writes",Pe.mode,{breakpoints:Pe.breakpoints,...Pe.avoidedWritePremium?{avoidedWritePremium:Pe.avoidedWritePremium.amount,
1570
+ attempt",{errors:L.errors}),I=await this.llamarProveedor({model:Le,messages:ue,schema:O,...G(n)!=null?{maxOutputTokens:G(n)}:{}},e),Ga=I.usage,s.actualLlm+=1,s.actualInput+=I.usage.inputTokens,s.actualOutput+=
1571
+ I.usage.outputTokens,s.repairOutput+=I.usage.outputTokens,s.repairInput+=I.usage.inputTokens,I.unbilledRefusal===true&&s.unbilledCall(I.usage),s.sentInputLocal+=Z,he=I.text;let te=et(he);L=te.ok?be(te.value,
1572
+ O):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},te.ok&&(vr=te.value,te.rescatado!=null&&L.valid&&(he=te.rescatado)),Ue.reparacion={outcome:L.valid?"repaired":"still_invalid"};}}else _.ok&&(vr=
1573
+ _.value);Ct=L.valid,!L.valid&&Ue.reparacion===void 0&&(Ue.reparacion={outcome:"skipped",skipReason:"decode_time_constraint"}),Ue.validacion={resultado:L.valid?"passed":"failed",errores:L.errors.length,
1574
+ desenvuelto:U},c.record("validation",Ct?"valid":"invalid");}let Gp=this.now()-Re,Kp=Kb(vr),Yt={text:he,data:vr,rendered:Kp,storedAtMs:this.now()},ge=this.informeDeDiferido(i,I,Le,Ha),Pe=this.informeDeEscrituras(
1575
+ i,jp,qe,Bp,d.modeloServido,B.marcar,B.explicitaPorColocador);Pe&&c.record("cache-writes",Pe.mode,{breakpoints:Pe.breakpoints,...Pe.avoidedWritePremium?{avoidedWritePremium:Pe.avoidedWritePremium.amount,
1571
1576
  basis:"estimated"}:{},creditedLedger:"none",reason:Pe.reason}),ge&&c.record("deferred-tier",ge.credited?"credited":"not-credited",{...ge.requestedTier?{requestedTier:ge.requestedTier}:{},...ge.servedTier?
1572
- {servedTier:ge.servedTier}:{},creditedLedger:"none",reason:ge.reason});let Gp=ee.aplicado,ii=_.finishReason==="length",yr=_.replayable===false,kr=Ta(_),Cn=kr||Tt?null:ir(he),Tn=o.sensitiveTopic,Zt=Ct!==false&&
1573
- !Tt&&!Gp&&!ii&&!yr&&!kr&&Cn===null&&Tn===null,Ja=this.generateId(),ye;try{ye=Pd({contadorSimulado:Ui(this.config.provider),origen:qp,usoPrimario:Bp,usoReparacion:Ga,tierServido:zp,eliminatedInput:s.eliminatedInput,
1574
- compressedInput:s.compressedInput,elididoLocal:s.elididoLocal,sentLocalSinSondeo:Up,baselineInput:u,codebookAplicado:D?.applied===!0,tokensDelSondeo:ee.tokensLocalesDelSondeo,sondeoAplicado:ee.aplicado,
1575
- busquedaNativa:y!==null,hayEsquema:O!=null,esquemaNativo:Fp,esquemaEnFormatoNativo:br?.esquemaEnFormatoNativo===!0&&F===O,esquemaEstricto:br?.esquemaEstricto===!0,esquemaPorPrompt:br?.esquemaPorPrompt===
1577
+ {servedTier:ge.servedTier}:{},creditedLedger:"none",reason:ge.reason});let Jp=ee.aplicado,ii=I.finishReason==="length",yr=I.replayable===false,kr=Ta(I),Cn=kr||Tt?null:ir(he),Tn=o.sensitiveTopic,Zt=Ct!==false&&
1578
+ !Tt&&!Jp&&!ii&&!yr&&!kr&&Cn===null&&Tn===null,Ja=this.generateId(),ye;try{ye=Pd({contadorSimulado:Ui(this.config.provider),origen:Vp,usoPrimario:Fp,usoReparacion:Ga,tierServido:qp,eliminatedInput:s.eliminatedInput,
1579
+ compressedInput:s.compressedInput,elididoLocal:s.elididoLocal,sentLocalSinSondeo:Hp,baselineInput:u,codebookAplicado:D?.applied===!0,tokensDelSondeo:ee.tokensLocalesDelSondeo,sondeoAplicado:ee.aplicado,
1580
+ busquedaNativa:y!==null,hayEsquema:O!=null,esquemaNativo:Up,esquemaEnFormatoNativo:br?.esquemaEnFormatoNativo===!0&&F===O,esquemaEstricto:br?.esquemaEstricto===!0,esquemaPorPrompt:br?.esquemaPorPrompt===
1576
1581
  !0,piezasDelAdaptador:br?.piezasDelAdaptador??0,modeloPedido:n.model,modeloServido:Le,cacheable:Zt,mensajesDeLaCapa:S.length-n.messages.length,requestId:Ja,at:this.now(),textoServido:he,huella:()=>ma(
1577
1582
  n)});}catch{ye="fingerprint-failed";}let Ya=Zt&&o.allowExactCache&&i.exactCache!==false;typeof ye=="object"?c.record("reference","written",{inputTokens:ye.inputTokens,outputTokens:ye.outputTokens,layerInsertions:ye.
1578
1583
  layerInsertions,...ye.reasoningTokens!==void 0?{reasoningTokens:ye.reasoningTokens}:{},exactCache:Ya}):c.record("reference","not-written",{reason:ye});try{Zt||c.record("cache-write",Tt?"skipped: tool-\
1579
1584
  call turn (an action request must not be replayed from cache)":Ct===!1?"skipped: response fails its output contract":ii?'skipped: answer cut off by the output cap (finish_reason "length"); replaying h\
1580
1585
  alf an answer would bill it as a 100% avoided call':yr?"skipped: the provider answer carries content this layer cannot replay":kr?'skipped: the provider refused (stop_reason "refusal" / finish_reason \
1581
- "content_filter" / a refusal message'+(_.finishReasonDetail!==void 0?`; provider reason: ${_.finishReasonDetail}`:"")+"); a refusal is not an answer, and replaying it would credit an avoided call the \
1586
+ "content_filter" / a refusal message'+(I.finishReasonDetail!==void 0?`; provider reason: ${I.finishReasonDetail}`:"")+"); a refusal is not an answer, and replaying it would credit an avoided call the \
1582
1587
  provider may not have billed":Cn!==null?Cn==="redirection"?"skipped: the answer redirects to professional or crisis help instead of answering (text_refusal, redirection); it was measured and served as\
1583
1588
  usual, but it is not an answer to replay or to credit as an avoided call":"skipped: the answer reads as a refusal written as text (text_refusal); it was measured and served as usual, but a refusal is\
1584
1589
  not an answer to replay or to credit as an avoided call":Tn!==null?`skipped: the request touches a sensitive topic (sensitive_topic, ${Tn}); it was measured and served as usual, but it is not replaye\
1585
1590
  d from a cache or credited as an avoided call`:"skipped: answered with a reduced tool view (tool discovery), so it must not be replayed",!Tt&&Ct!==!1&&!ii&&!yr&&!kr?Cn!==null?{skipReason:"text_refusal",
1586
- rule:Cn}:Tn!==null?{skipReason:"sensitive_topic",category:Tn}:void 0:void 0);let I=nt?rn(r,{servedModel:Le}):l;if(Ya){let U=this.config.exactCacheTtlMs??864e5,H=o.maxCacheAgeMs==null?U:Math.min(U,o.maxCacheAgeMs);
1587
- await this.deps.exactCache.set(I,typeof ye=="object"?{...Yt,meta:{...Yt.meta??{},reference:{...ye,cacheKey:I}}}:Yt,H);}let L=Le!==n.model;Zt&&!L&&o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache?
1591
+ rule:Cn}:Tn!==null?{skipReason:"sensitive_topic",category:Tn}:void 0:void 0);let _=nt?rn(r,{servedModel:Le}):l;if(Ya){let U=this.config.exactCacheTtlMs??864e5,H=o.maxCacheAgeMs==null?U:Math.min(U,o.maxCacheAgeMs);
1592
+ await this.deps.exactCache.set(_,typeof ye=="object"?{...Yt,meta:{...Yt.meta??{},reference:{...ye,cacheKey:_}}}:Yt,H);}let L=Le!==n.model;Zt&&!L&&o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache?
1588
1593
  await this.deps.semanticCache.store(r,Yt):Zt&&L&&i.semanticCache&&c.record("cache-write","semantic write skipped: a cheaper model answered, and this cache keys on the model the caller asked for"),m&&this.
1589
1594
  deps.semanticCache&&(Zt&&!L&&o.allowSemanticCache&&i.semanticCache?(c.record("semantic-calibration","label requested",{reason:m.reason,score:m.score}),this.deps.semanticCache.observe(m,Yt)):c.record("\
1590
- semantic-calibration","no label: the cache would not store this answer"));}catch(I){c.record("cache-write","failed (non-fatal; answer already served)",{error:I instanceof Error?I.message:String(I)});}s.
1591
- callsWithoutUsage=e.sinContador;let Rn=_.unbilledRefusal===true;Rn&&(s.servedUnbilledRefusal=true,c.record("cost","unbilled refusal: measured at 0, no saving credited",{reason:"the provider documents a re\
1592
- fusal before any output in this category as not billed; its tokens stay counted, priced at 0, and nothing is credited against a request that cost nothing"}));let Kp=Rn&&ge?.credited?{...ge.requestedTier?
1595
+ semantic-calibration","no label: the cache would not store this answer"));}catch(_){c.record("cache-write","failed (non-fatal; answer already served)",{error:_ instanceof Error?_.message:String(_)});}s.
1596
+ callsWithoutUsage=e.sinContador;let Rn=I.unbilledRefusal===true;Rn&&(s.servedUnbilledRefusal=true,c.record("cost","unbilled refusal: measured at 0, no saving credited",{reason:"the provider documents a re\
1597
+ fusal before any output in this category as not billed; its tokens stay counted, priced at 0, and nothing is credited against a request that cost nothing"}));let Yp=Rn&&ge?.credited?{...ge.requestedTier?
1593
1598
  {requestedTier:ge.requestedTier}:{},...ge.servedTier?{servedTier:ge.servedTier}:{},credited:false,creditedLedger:"none",latency:ge.latency,reason:"the provider did not bill this call (a refusal it docume\
1594
- nts as not billed), so no tier discount is credited"}:ge,Jp=Rn&&Pe?.avoidedWritePremium?{mode:Pe.mode,breakpoints:Pe.breakpoints,reason:Pe.reason}:Pe,rt=this.finish(n,r,Yt,"miss",s,En,c,b,E,void 0,void 0,
1595
- Ct,j.backend,Hp,this.informeDeCascada(d,{servedModel:Le,...d.enruta?{escalated:nt}:{},...d.elegible&&d.precioBarato&&!Rn?{estimatedSwapSaving:Gb(s,nt,d.precioBarato,this.costModelFor(n.model,h))}:{},...Jt?
1599
+ nts as not billed), so no tier discount is credited"}:ge,Zp=Rn&&Pe?.avoidedWritePremium?{mode:Pe.mode,breakpoints:Pe.breakpoints,reason:Pe.reason}:Pe,rt=this.finish(n,r,Yt,"miss",s,En,c,b,E,void 0,void 0,
1600
+ Ct,j.backend,Gp,this.informeDeCascada(d,{servedModel:Le,...d.enruta?{escalated:nt}:{},...d.elegible&&d.precioBarato&&!Rn?{estimatedSwapSaving:Zb(s,nt,d.precioBarato,this.costModelFor(n.model,h))}:{},...Jt?
1596
1601
  {sampled:true,sampleCost:Ht(Jt.coste),...Jt.divergio!==null?{divergedOnSample:Jt.divergio}:{}}:{},...s.cascadeInput>0||s.cascadeOutput>0?{cascadeInputTokens:s.cascadeInput,cascadeOutputTokens:s.cascadeOutput}:
1597
- {}}),Kp,Ja,Jp,{...Ue,final:{..._.finishReason!==void 0?{finishReason:_.finishReason}:{},..._.finishReasonDetail!==void 0?{finishReasonDetail:_.finishReasonDetail}:{},...G(n)!=null?{topeDelLlamante:G(n)}:
1598
- {}}});return typeof ye=="object"&&this.referenciasDeLider.set(rt,ye),yr&&this.noReproducibles.add(rt),Rn&&this.negativasSinCobro.add(rt),Tt&&(rt.toolCalls=_.toolCalls),_.finishReason!==void 0&&(rt.finishReason=
1599
- _.finishReason),_.finishReasonDetail!==void 0&&(rt.finishReasonDetail=_.finishReasonDetail),_.refusal!==void 0&&(rt.refusal=_.refusal),rt}planearBusquedaNativa(e,n,r,o,i,s,a){let c=_i(n.toolSearch),l=e.
1602
+ {}}),Yp,Ja,Zp,{...Ue,final:{...I.finishReason!==void 0?{finishReason:I.finishReason}:{},...I.finishReasonDetail!==void 0?{finishReasonDetail:I.finishReasonDetail}:{},...G(n)!=null?{topeDelLlamante:G(n)}:
1603
+ {}}});return typeof ye=="object"&&this.referenciasDeLider.set(rt,ye),yr&&this.noReproducibles.add(rt),Rn&&this.negativasSinCobro.add(rt),Tt&&(rt.toolCalls=I.toolCalls),I.finishReason!==void 0&&(rt.finishReason=
1604
+ I.finishReason),I.finishReasonDetail!==void 0&&(rt.finishReasonDetail=I.finishReasonDetail),I.refusal!==void 0&&(rt.refusal=I.refusal),rt}planearBusquedaNativa(e,n,r,o,i,s,a){let c=Ii(n.toolSearch),l=e.
1600
1605
  tools??[];if(c.modo==="off"||l.length===0)return null;let{candidatas:u,decision:d}=this.decidirBusquedaParaEstaPeticion(e,c,r,o,i,s);if(a.record("tool-search",d.aplicar?"native":"selector",{mode:c.modo,
1601
1606
  variant:d.variante,reason:d.razon,deferred:d.diferidas,deferredTokens:d.tokensDiferidos,alwaysLoaded:d.siempreCargadas,...d.ahorroDelPrefijo!=null?{prefixSavingPerRequest:d.ahorroDelPrefijo}:{},...d.costeDeUnaBusqueda!=
1602
1607
  null?{worstCaseSearchCost:d.costeDeUnaBusqueda}:{}}),!d.aplicar)return null;let p=new Set(u.map(m=>m.id)),h=new Set(d.siempreCargadas),f=c.siempreCargadas.filter(m=>l.some(g=>g.id===m));return {seleccion:{
@@ -1606,7 +1611,7 @@ schema!=null,cascadaActiva:i.modo!=="off",precio:s,lecturaDeCache:this.lecturaDe
1606
1611
  cacheReadMultiplier??1,o=n.cachedInputPer1k!=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===
1607
1612
  true&&r.record("tool-discovery","skipped (native 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 cach\
1608
1613
  ed prefix"}),{tools:n,tokensLocalesDelSondeo:0,aplicado:false}}avisarDeHerramientasPodadas(e,n,r,o,i,s,a){let c=e.tools??[],l="herramientas-podadas-por-el-selector";if(r.droppedIds.length===0||this.config.
1609
- silenceWarnings||Qc(l))return;let u=_i(n.toolSearch),d=f=>this.decidirBusquedaParaEstaPeticion(e,{...u,modo:f},o,i,s,a).decision,p=d("auto"),h="";p.aplicar?h=' This provider and model also support nat\
1614
+ silenceWarnings||Qc(l))return;let u=Ii(n.toolSearch),d=f=>this.decidirBusquedaParaEstaPeticion(e,{...u,modo:f},o,i,s,a).decision,p=d("auto"),h="";p.aplicar?h=' This provider and model also support nat\
1610
1615
  ive tool search, and it would pay here: `savings: { toolSearch: "auto" }` sends every tool deferred and lets the model search, without breaking the prompt cache.':d("always").aplicar&&(p.ahorroDelPrefijo!=
1611
1616
  null&&p.costeDeUnaBusqueda!=null?h=` Native tool search is available here, but \`toolSearch: "auto"\` would keep the selector for this request: deferring the catalogue saves about $${p.ahorroDelPrefijo.
1612
1617
  toFixed(6)} per request with a warm cache, less than one worst-case search ($${p.costeDeUnaBusqueda.toFixed(6)}). \`toolSearch: "always"\` makes every tool reachable anyway, at up to $${(p.costeDeUnaBusqueda-
@@ -1614,7 +1619,7 @@ p.ahorroDelPrefijo).toFixed(6)} more per request that searches.`:Jr(this.config.
1614
1619
  keep the selector; if your proxy forwards the tool search blocks, `toolSearch: "always"` sends every tool deferred and lets the model search.')),this.avisar(l,`[bv-sala] The tool selector sent ${r.tools.
1615
1620
  length} of ${c.length} tools, chosen by the \`intents\`/\`risk\` your tools declare: the model cannot call the other ${r.droppedIds.length} in that request (they are listed in the report's \`tool-selec\
1616
1621
  tor\` trace). A catalogue with no \`intents\` and no \`risk\`, or \`savings: { router: false }\`, is sent whole.`+h);}catalogoGrandeAvisado=false;avisarDeCatalogoGrande(e,n,r,o,i){if(this.catalogoGrandeAvisado||
1617
- this.config.silenceWarnings||n.toolSearch!==void 0||r.tools.length<Ar.herramientas)return;let s=Jr(this.config.provider);s===void 0||!Ii(o.modeloServido)||!Ai({opciones:{modo:"auto",siempreCargadas:[],
1622
+ this.config.silenceWarnings||n.toolSearch!==void 0||r.tools.length<Ar.herramientas)return;let s=Jr(this.config.provider);s===void 0||!_i(o.modeloServido)||!Ai({opciones:{modo:"auto",siempreCargadas:[],
1618
1623
  variante:"bm25"},capacidad:s,modelo:o.modeloServido,herramientas:r.tools.map(c=>({id:c.id,tokens:this.tokensFor(ur(c),e)})),hayContrato:e.response?.schema!=null,cascadaActiva:o.modo!=="off",precio:i,lecturaDeCache:this.
1619
1624
  lecturaDeCacheDe(o.modeloServido,i)}).aplicar||(this.catalogoGrandeAvisado=true,this.avisar("catalogo-grande-con-busqueda-nativa",`[bv-sala] This request sent all ${r.tools.length} of its tools in the p\
1620
1625
  rompt: since 0.4.33 tools are pruned by relevance only if you set \`new ToolSelector({ maxTools })\`. This provider and model support native tool search, and it would pay off here: \`savings: { toolSearc\
@@ -1636,7 +1641,7 @@ the cheaper tier had no capacity (HTTP 429 or 503), so, as configured with price
1636
1641
  not counted as a call and nothing is credited'};let c=n.requestedServiceTier,l={...c?{requestedTier:c}:{},...a?{servedTier:a}:{},credited:false,creditedLedger:"none",latency:Yc(c,s),reason:""};if(!c)return {
1637
1642
  ...l,reason:Jc};let u=this.precioDelCliente(r),d=Hr({modelo:r,uso:n.usage,tierServido:a,origen:s,...i?.tierLeidoDe?{tierLeidoDe:i.tierLeidoDe}:{},...u?{precioDelCliente:u}:{},ahoraMs:this.now()});if(!d.
1638
1643
  ok){let p=d.motivo==="no-tier-price"&&s==="openai"&&Kc(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\
1639
- ()":"";return {...l,reason:Wb(d.motivo,c,a)+p}}return {...l,credited:true,discountRate:sr(d.factorEfectivo),estimatedTierSaving:d.importe,tierSaving:{amount:d.importe,basis:d.basis,standardCost:Ht(d.costeEstandar),
1644
+ ()":"";return {...l,reason:Yb(d.motivo,c,a)+p}}return {...l,credited:true,discountRate:sr(d.factorEfectivo),estimatedTierSaving:d.importe,tierSaving:{amount:d.importe,basis:d.basis,standardCost:Ht(d.costeEstandar),
1640
1645
  appliedCost:Ht(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}\
1641
1646
  " 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){
1642
1647
  if(e.standalone!==true&&!a)return;let c=n?.cacheExplicita;if(!c){let g=$t(this.config.provider),b="the provider chose where to write its prompt cache, as it does by default";return {mode:"provider-defaul\
@@ -1666,8 +1671,8 @@ baselineTools:o.baselineTools,actualTools:o.actualTools,retries:o.retries},token
1666
1671
  baselineOutput:o.publishedBaselineOutput,actualOutput:o.actualOutput,eliminatedOutput:o.eliminatedOutput,...o.providerCachedInput?{providerCachedInput:o.providerCachedInput}:{}},cache:{result:r,...u!==
1667
1672
  void 0?{confidence:u}:{},...l!==void 0?{ageMs:l}:{},...o.reference?{reference:{...o.reference}}:{},...o.referenceRejected?{referenceRejected:o.referenceRejected}:{}},routing:{executionClass:a.executionClass,
1668
1673
  confidence:a.confidence,rounds:o.actualRetrieval,reason:a.reason},serialization:{chosen:c.chosen,candidateTokens:c.candidateTokens,instructionOverheadTokens:c.instructionOverheadTokens},...o.compressionReport?
1669
- {compression:o.compressionReport}:{},constraints:{backend:p,schemaVersion:n.schemaVersion,...d===null?{}:{structurallyValid:d}},qualityStatus:Hb(r,d,S),qualityLedger:Dd({cacheResult:r,structurallyValid:d,
1670
- backend:p,hayEsquema:e.response?.schema!=null,ageMs:l,cascada:f,hechos:y}),...f?{modelCascade:f}:{},...m?{deferred:m}:{},...b?{cacheWrites:b}:{},...x?{nativeSavings:x}:{},quality:{...r!=="miss"?{freshnessPassed:!It(
1674
+ {compression:o.compressionReport}:{},constraints:{backend:p,schemaVersion:n.schemaVersion,...d===null?{}:{structurallyValid:d}},qualityStatus:Jb(r,d,S),qualityLedger:Dd({cacheResult:r,structurallyValid:d,
1675
+ backend:p,hayEsquema:e.response?.schema!=null,ageMs:l,cascada:f,hechos:y}),...f?{modelCascade:f}:{},...m?{deferred:m}:{},...b?{cacheWrites:b}:{},...x?{nativeSavings:x}:{},quality:{...r!=="miss"?{freshnessPassed:!_t(
1671
1676
  n).requiresFreshData}:{},...r==="semantic"&&y?.semantico?{semanticScore:y.semantico.similarity}:{}},cost:v,latencyMs:{total:E,preprocessing:Math.max(0,E-h),provider:h},traces:s.all()}}async failOpenDirect(e,n){
1672
1677
  let r=new pt(this.now);return r.record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",{error:n instanceof Error?n.message:String(n)}),(await this.llamadaDirecta(e,r,{
1673
1678
  origen:"fail_open"})).result}async llamadaDirecta(e,n,r){let o=r.origen==="measure",i=new at,s=this.costModelFor(e.model),a;try{a=nn(e);}catch{a={schemaVersion:e.response?.version??e.response?.contractId??
@@ -1688,7 +1693,7 @@ ck of capacity, and trading availability for a discount on a last-resort call is
1688
1693
  changed on the direct fail-open path, so the provider chose where to write its prompt cache, as it does by default"}:void 0,b);return {result:{requestId:v.requestId,data:m,text:p.text,...y?{toolCalls:p.
1689
1694
  toolCalls}:{},...p.finishReason!==void 0?{finishReason:p.finishReason}:{},...p.finishReasonDetail!==void 0?{finishReasonDetail:p.finishReasonDetail}:{},...p.refusal!==void 0?{refusal:p.refusal}:{},report:v},
1690
1695
  response:p}}enSombra(){try{return this.config.licenseGate?.plan?.()==="measure"}catch{return false}}async generarEnSombra(e,n,r){this.avisar("licencia-medir",Ld);let o=new pt(this.now);o.record("measure",
1691
- "shadow mode (Measure license): the request goes to the provider unchanged and nothing is served from cache");let i=e.savings??{},s=null,a=null,c=null;try{let S=nn(e);s=It(S),s.allowExactCache&&i.exactCache!==
1696
+ "shadow mode (Measure license): the request goes to the provider unchanged and nothing is served from cache");let i=e.savings??{},s=null,a=null,c=null;try{let S=nn(e);s=_t(S),s.allowExactCache&&i.exactCache!==
1692
1697
  !1&&(a=rn(S)),s.allowSingleflight&&i.singleflight!==!1&&(c=An(S,{deferrable:i.deferrable===!0,toolDiscovery:i.toolDiscovery===!0,...G(e)!=null?{maxOutputTokens:G(e)}:{}}));}catch{o.record("measure","no\
1693
1698
  shadow estimate: the request could not be keyed");}let l=this.now(),u=a!==null&&this.memoriaDeSombra.vista(a,l),d=!u&&c!==null&&this.memoriaDeSombra.hayEnVuelo(c),p=c!==null&&!r;p&&this.memoriaDeSombra.
1694
1699
  entrar(c);let h;try{h=await this.llamadaDirecta(e,o,{origen:"measure",testigo:n,sumidero:r});}finally{p&&this.memoriaDeSombra.salir(c);}let{result:f,response:m}=h,g=(m.toolCalls?.length??0)>0,b=Ta(m);if(a!==
@@ -1701,7 +1706,7 @@ u=this.diferidoSinLlamada(i),d=u?{deferred:u}:{},p=this.escriturasSinLlamada(i),
1701
1706
  ...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:a.baselineInput,actualInput:a.actualInput,eliminatedInput:a.eliminatedInput,compressedInput:a.compressedInput,baselineOutput:a.publishedBaselineOutput,
1702
1707
  actualOutput:a.actualOutput,eliminatedOutput:a.eliminatedOutput,...a.providerCachedInput?{providerCachedInput:a.providerCachedInput}:{}},cache:{result:"singleflight",...a.reference?{reference:{...a.reference}}:
1703
1708
  a.referenceRejected?{referenceRejected:a.referenceRejected}:{}},...d,...p?{cacheWrites:p}:{},qualityLedger:Ad(e.report.qualityLedger),cost:c}}}creditoPorReferencia(e,n){if(typeof e=="string")return {ok:false,
1704
- reason:e};let r;try{r=n.calidad();}catch{r=false;}try{return _d(e,{ahoraMs:this.now(),modeloPedido:n.request.model,modeloServido:n.cascada.modeloServido,huella:n.huella(),textoServidoSha256:X(n.texto),claveLeida:n.
1709
+ reason:e};let r;try{r=n.calidad();}catch{r=false;}try{return Id(e,{ahoraMs:this.now(),modeloPedido:n.request.model,modeloServido:n.cascada.modeloServido,huella:n.huella(),textoServidoSha256:X(n.texto),claveLeida:n.
1705
1710
  claveLeida,calidadOk:r,precio:this.precioDocumentado(n.request.model),determinista:Rd(n.request),salidaDelModelo:Ku(n.request.model),topeDeSalida:G(n.request),diferible:n.toggles.deferrable===!0})}catch{
1706
1711
  return {ok:false,reason:"different-request"}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,r){let o=e.map(i=>i.content);r!==void 0&&
1707
1712
  o.push(JSON.stringify(r));for(let i of n??[])o.push(ur(i));return o.join(`
@@ -1710,80 +1715,80 @@ try{return n.resolve({...e.tokenizer?{tokenizer:e.tokenizer}:{},model:e.model}).
1710
1715
  e)}precioConocido(e,n=this.now()){return this.precioDelCliente(e)??Xt(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.
1711
1716
  slice(o+1)];if(i)return i}}precioDocumentado(e){return this.precioDelCliente(e)??st(e,this.now())}costModelFor(e,n=this.now()){let r=this.precioConocido(e,n);return r||(this.config.defaultCostModel?this.
1712
1717
  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. \
1713
- Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),Gu))}};function Fb(t,e){if((e.toolCalls?.length??0)>0||!t.schema)return "none";let n=et(typeof e.text=="string"?e.text:"");return n.ok&&be(
1714
- n.value,t.schema).valid?"met":"missed"}function et(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of qb(t))try{return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function qb(t){
1715
- 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=Ub(t,o);i&&
1716
- e.push(i);}return e}function Ub(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===
1717
- n)o+=1;else if(c===r&&(o-=1,o===0))return t.slice(e,a+1)}}function Vb(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function Hb(t,e,n=false){if(e===false)return "rejected";if(n)return "bounded_degra\
1718
- dation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "not_verified"}}function Wb(t,e,n){switch(t){case "no-served-tier":return `asked the \
1718
+ Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),Gu))}};function Hb(t,e){if((e.toolCalls?.length??0)>0||!t.schema)return "none";let n=et(typeof e.text=="string"?e.text:"");return n.ok&&be(
1719
+ n.value,t.schema).valid?"met":"missed"}function et(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of Wb(t))try{return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function Wb(t){
1720
+ 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=Gb(t,o);i&&
1721
+ e.push(i);}return e}function Gb(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===
1722
+ n)o+=1;else if(c===r&&(o-=1,o===0))return t.slice(e,a+1)}}function Kb(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function Jb(t,e,n=false){if(e===false)return "rejected";if(n)return "bounded_degra\
1723
+ dation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "not_verified"}}function Yb(t,e,n){switch(t){case "no-served-tier":return `asked the \
1719
1724
  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\
1720
1725
  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\
1721
1726
  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\
1722
1727
  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\
1723
1728
  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\
1724
1729
  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 sr(t){return Math.
1725
- round(t*1e6)/1e6}function Ht(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Gb(t,e,n,r){if(e)return Ht(-t.extraCostUsd);let o=i=>t.actualInput/1e3*i.inputPer1k+t.actualOutput/1e3*i.outputPer1k;
1726
- return Ht(o(r)-o(n))}function Kb(t,e){if(!(e>0))return false;if(e>=1)return true;let n=X(`${t}:cascade-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function up(t,e){if(!e.isAgentic||e.allowSemanticCache)
1727
- return false;let n=t.original;return It({...t,original:{...n,savings:{...n.savings??{},semanticCache:"include-agentic"}}}).allowSemanticCache}function ar(){return {executionClass:"NO_RETRIEVAL",confidence:1,
1730
+ round(t*1e6)/1e6}function Ht(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Zb(t,e,n,r){if(e)return Ht(-t.extraCostUsd);let o=i=>t.actualInput/1e3*i.inputPer1k+t.actualOutput/1e3*i.outputPer1k;
1731
+ return Ht(o(r)-o(n))}function Xb(t,e){if(!(e>0))return false;if(e>=1)return true;let n=X(`${t}:cascade-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function pp(t,e){if(!e.isAgentic||e.allowSemanticCache)
1732
+ return false;let n=t.original;return _t({...t,original:{...n,savings:{...n.savings??{},semanticCache:"include-agentic"}}}).allowSemanticCache}function ar(){return {executionClass:"NO_RETRIEVAL",confidence:1,
1728
1733
  reason:"n/a (short-circuited)",rounds:0}}function cr(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,reason:"no structured payload"}}function Pa(t,e="",n=null){
1729
1734
  if(t==null||typeof t!="object")return "";let r=t,o=[],i=e||"the value",s=f=>typeof r[f]=="number"?r[f]:null,a=s("maxLength"),c=s("minLength"),l=s("maxItems"),u=s("minItems"),d=s("maximum"),p=s("minimum");
1730
1735
  if(a!=null){let f=n!=null?Math.min(a,n):a;o.push(`${i}<=${f}ch`);}c!=null&&o.push(`${i}>=${c}ch`),l!=null&&o.push(`${i}<=${l} items`),u!=null&&o.push(`${i}>=${u} items`),d!=null&&o.push(`${i}<=${d}`),p!=
1731
1736
  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[f,m]of Object.entries(h)){let g=Pa(m,e?`${e}.${f}`:f,n);
1732
1737
  g&&o.push(g);}if(r.items!==void 0){let f=Pa(r.items,`${i} entries`,n);f&&o.push(f);}return o.join("; ")}function lr(t){let e=t.response;return e?e.contractId??e.version??JSON.stringify(e.schema??{}).slice(
1733
- 0,200):""}function Ta(t){return fl(t.finishReason)||typeof t.refusal=="string"&&t.refusal!==""}function Jb(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.
1738
+ 0,200):""}function Ta(t){return fl(t.finishReason)||typeof t.refusal=="string"&&t.refusal!==""}function Qb(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.
1734
1739
  test(e.message))}function ur(t){return JSON.stringify({type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function dr(t,e){
1735
- for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}function Yb(t,e){if(e===false)return null;let n=typeof t=="object"&&t!==null?t:{};return e===true||t?n:null}function Ia(t,e=false){
1736
- 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 Ia(t,true)}function Zb(t){let e=-1;for(let r=t.length-1;r>=0;r--)if(t[r].
1737
- role==="user"){e=r;break}if(e<0)return false;if(e<t.length-1)return true;let n=0;for(let r=0;r<e;r++)t[r].role==="user"&&(n+=1);return n>=2}function dp(t){return t instanceof Error?t.name:typeof t}function Ra(t,e){
1738
- let n=No(t,e);return n.cacheReadMultiplier<1?n:null}var hp={anthropic:{peticiones:1e5,bytes:256e6},openai:{peticiones:5e4,bytes:2e8}},Xb=/^[A-Za-z0-9_-]{1,64}$/,gp="/v1/chat/completions",Qb=new Set(["completed","failed","expired","cancelled"]);function bp(t){
1739
- return {submit:(e,n)=>ev(t,e,n??{}),status:(e,n)=>av(t,e,n?.signal),results:(e,n)=>dv(t,e,n?.signal),cancel:(e,n)=>uv(t,e,n?.signal)}}function Ko(t){let e=dl(t.provider);if(!e)throw new Error("[bvsala]\
1740
+ for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}function ev(t,e){if(e===false)return null;let n=typeof t=="object"&&t!==null?t:{};return e===true||t?n:null}function _a(t,e=false){
1741
+ 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 _a(t,true)}function tv(t){let e=-1;for(let r=t.length-1;r>=0;r--)if(t[r].
1742
+ role==="user"){e=r;break}if(e<0)return false;if(e<t.length-1)return true;let n=0;for(let r=0;r<e;r++)t[r].role==="user"&&(n+=1);return n>=2}function fp(t){return t instanceof Error?t.name:typeof t}function Ra(t,e){
1743
+ let n=No(t,e);return n.cacheReadMultiplier<1?n:null}var bp={anthropic:{peticiones:1e5,bytes:256e6},openai:{peticiones:5e4,bytes:2e8}},nv=/^[A-Za-z0-9_-]{1,64}$/,vp="/v1/chat/completions",rv=new Set(["completed","failed","expired","cancelled"]);function yp(t){
1744
+ return {submit:(e,n)=>ov(t,e,n??{}),status:(e,n)=>dv(t,e,n?.signal),results:(e,n)=>hv(t,e,n?.signal),cancel:(e,n)=>mv(t,e,n?.signal)}}function Ko(t){let e=dl(t.provider);if(!e)throw new Error("[bvsala]\
1740
1745
  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===
1741
1746
  "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\
1742
- ini's own Files API). Nothing was sent.");return e}async function ev(t,e,n){t.exigirLicencia(),t.exigirPalancas?.();let r=Ko(t);tv(e);let o=nv(n.maxRequestsPerBatch,r.protocolo),i=n.cacheSharedPrefix===
1743
- true&&r.protocolo==="anthropic",s=new TextEncoder,a=e.map(({customId:f,request:m})=>{let g;try{g=r.cuerpo(rv(m,i));}catch(v){throw new TypeError(`[bvsala] batch request "${f}": ${Ho(v)}`)}let b=r.protocolo===
1744
- "anthropic"?{custom_id:f,params:g}:{custom_id:f,method:"POST",url:gp,body:g},y=JSON.stringify(b);return {customId:f,linea:b,bytes:s.encode(y).length,modelo:typeof g.model=="string"?g.model:m.model}}),c=ov(
1747
+ ini's own Files API). Nothing was sent.");return e}async function ov(t,e,n){t.exigirLicencia(),t.exigirPalancas?.();let r=Ko(t);iv(e);let o=sv(n.maxRequestsPerBatch,r.protocolo),i=n.cacheSharedPrefix===
1748
+ true&&r.protocolo==="anthropic",s=new TextEncoder,a=e.map(({customId:f,request:m})=>{let g;try{g=r.cuerpo(av(m,i));}catch(v){throw new TypeError(`[bvsala] batch request "${f}": ${Ho(v)}`)}let b=r.protocolo===
1749
+ "anthropic"?{custom_id:f,params:g}:{custom_id:f,method:"POST",url:vp,body:g},y=JSON.stringify(b);return {customId:f,linea:b,bytes:s.encode(y).length,modelo:typeof g.model=="string"?g.model:m.model}}),c=cv(
1745
1750
  a,r.protocolo,o),l=[],u=new Map,d=new Map;c.forEach((f,m)=>f.forEach(g=>d.set(g.customId,m)));let p=e.map(({customId:f,request:m})=>{let g=m.response?.schema,b;if(g){let y=JSON.stringify(g);b=u.get(y),
1746
1751
  b===void 0&&(b=l.length,l.push(g),u.set(y,b));}return {customId:f,model:m.model,batch:d.get(f),...b!==void 0?{schema:b}:{}}}),h={kind:"bvsala.batch",version:1,provider:r.protocolo,endpoint:r.endpoint,batchIds:[],
1747
- submittedAt:new Date(t.now()).toISOString(),requests:p,schemas:l};for(let f=0;f<c.length;f++)try{let m=r.protocolo==="anthropic"?await iv(r,c[f],n.signal):await sv(r,c[f],n.signal);h.batchIds.push(m);}catch(m){
1752
+ submittedAt:new Date(t.now()).toISOString(),requests:p,schemas:l};for(let f=0;f<c.length;f++)try{let m=r.protocolo==="anthropic"?await lv(r,c[f],n.signal):await uv(r,c[f],n.signal);h.batchIds.push(m);}catch(m){
1748
1753
  let g=h.batchIds.length,b={...h,batchIds:[...h.batchIds],requests:h.requests.filter(v=>v.batch<g)},y=h.requests.filter(v=>v.batch>=g).map(v=>v.customId);throw new Po(g===0?`[bvsala] batch submission f\
1749
1754
  ailed before any provider batch was created: ${Ho(m)}.`:`[bvsala] batch submission failed after ${g} of ${c.length} provider batches were created: ${Ho(m)}. The created batches run and are billed; err\
1750
- or.job holds them.`,b,y,{cause:m})}return h}function tv(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;
1751
- for(let[n,r]of t.entries()){let o=r?.customId;if(typeof o!="string"||!Xb.test(o))throw new TypeError(`[bvsala] batch request #${n}: customId must be 1 to 64 letters, digits, "_" or "-" (got ${JSON.stringify(
1755
+ or.job holds them.`,b,y,{cause:m})}return h}function iv(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;
1756
+ for(let[n,r]of t.entries()){let o=r?.customId;if(typeof o!="string"||!nv.test(o))throw new TypeError(`[bvsala] batch request #${n}: customId must be 1 to 64 letters, digits, "_" or "-" (got ${JSON.stringify(
1752
1757
  o)}).`);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(
1753
1758
  i.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(`[\
1754
1759
  bvsala] 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(`[bvsal\
1755
- a] batch request "${o}": structuredData is serialized by the layer's pipeline, which batches skip. Put the payload in the messages instead.`)}}function nv(t,e){let n=hp[e].peticiones;if(t===void 0)return n;
1756
- 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 rv(t,e){let n=0;for(;n<t.messages.length&&
1760
+ a] batch request "${o}": structuredData is serialized by the layer's pipeline, which batches skip. Put the payload in the messages instead.`)}}function sv(t,e){let n=bp[e].peticiones;if(t===void 0)return n;
1761
+ 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 av(t,e){let n=0;for(;n<t.messages.length&&
1757
1762
  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}:{},...G(t)!=null?{maxOutputTokens:G(
1758
- t)}:{},...t.temperature!=null?{temperature:t.temperature}:{},...t.seed!=null?{seed:t.seed}:{},...t.reasoningEffort!=null?{reasoningEffort:t.reasoningEffort}:{},...e&&n>0?{stablePrefixMessages:n}:{}}}function ov(t,e,n){
1759
- let r=hp[e],o=new Map;for(let a of t){let c=e==="openai"?a.modelo:"",l=o.get(c);l?l.push(a):o.set(c,[a]);}let i=e==="anthropic"?15:0,s=[];for(let a of o.values()){let c=[],l=i;for(let u of a){let d=u.bytes+
1763
+ t)}:{},...t.temperature!=null?{temperature:t.temperature}:{},...t.seed!=null?{seed:t.seed}:{},...t.reasoningEffort!=null?{reasoningEffort:t.reasoningEffort}:{},...e&&n>0?{stablePrefixMessages:n}:{}}}function cv(t,e,n){
1764
+ let r=bp[e],o=new Map;for(let a of t){let c=e==="openai"?a.modelo:"",l=o.get(c);l?l.push(a):o.set(c,[a]);}let i=e==="anthropic"?15:0,s=[];for(let a of o.values()){let c=[],l=i;for(let u of a){let d=u.bytes+
1760
1765
  1;if(i+d>r.bytes)throw new TypeError(`[bvsala] batch request "${u.customId}" is ${u.bytes} bytes, larger than a whole ${e} batch may be. Send it with generate() instead.`);c.length>0&&(c.length>=n||l+
1761
- d>r.bytes)&&(s.push(c),c=[],l=i),c.push(u),l+=d;}c.length>0&&s.push(c);}return s}async function iv(t,e,n){let r=await pr(t,"/messages/batches",{method:"POST",json:{requests:e.map(o=>o.linea)},...n?{signal:n}:
1762
- {}});return Aa(r,"Message Batch")}async function sv(t,e,n){let r=e.map(a=>JSON.stringify(a.linea)).join(`
1766
+ d>r.bytes)&&(s.push(c),c=[],l=i),c.push(u),l+=d;}c.length>0&&s.push(c);}return s}async function lv(t,e,n){let r=await pr(t,"/messages/batches",{method:"POST",json:{requests:e.map(o=>o.linea)},...n?{signal:n}:
1767
+ {}});return Aa(r,"Message Batch")}async function uv(t,e,n){let r=e.map(a=>JSON.stringify(a.linea)).join(`
1763
1768
  `)+`
1764
1769
  `,o=new FormData;o.append("purpose","batch"),o.append("file",new Blob([r],{type:"application/jsonl"}),"bvsala-batch.jsonl");let i=await pr(t,"/files",{method:"POST",form:o,...n?{signal:n}:{}}),s=await pr(
1765
- t,"/batches",{method:"POST",json:{input_file_id:Aa(i,"file"),endpoint:gp,completion_window:"24h"},...n?{signal:n}:{}});return Aa(s,"batch")}async function av(t,e,n){t.exigirLicencia(),t.exigirPalancas?.();
1766
- let r=Ko(t);Oa(e,r);let o=await Wo(r,e,n);return vp(e,o)}async function Wo(t,e,n){let r=[];for(let[o,i]of e.batchIds.entries()){let s=await pr(t,La(t,i),{method:"GET",...n?{signal:n}:{}}),a=e.requests.
1767
- filter(c=>c.batch===o).length;r.push(t.protocolo==="anthropic"?cv(i,s):lv(i,s,a));}return r}function cv(t,e){let n=le(e),r=typeof n.processing_status=="string"?n.processing_status:"unknown",o=le(n.request_counts);
1770
+ t,"/batches",{method:"POST",json:{input_file_id:Aa(i,"file"),endpoint:vp,completion_window:"24h"},...n?{signal:n}:{}});return Aa(s,"batch")}async function dv(t,e,n){t.exigirLicencia(),t.exigirPalancas?.();
1771
+ let r=Ko(t);Oa(e,r);let o=await Wo(r,e,n);return kp(e,o)}async function Wo(t,e,n){let r=[];for(let[o,i]of e.batchIds.entries()){let s=await pr(t,La(t,i),{method:"GET",...n?{signal:n}:{}}),a=e.requests.
1772
+ filter(c=>c.batch===o).length;r.push(t.protocolo==="anthropic"?pv(i,s):fv(i,s,a));}return r}function pv(t,e){let n=le(e),r=typeof n.processing_status=="string"?n.processing_status:"unknown",o=le(n.request_counts);
1768
1773
  return {id:t,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)}}}
1769
- function lv(t,e,n){let r=le(e),o=typeof r.status=="string"?r.status:"unknown",i=le(r.request_counts),s=St(i.total)||n,a=St(i.completed),c=St(i.failed),l=Math.max(0,s-a-c),u=Qb.has(o),d=o==="failed"?{processing:0,
1774
+ function fv(t,e,n){let r=le(e),o=typeof r.status=="string"?r.status:"unknown",i=le(r.request_counts),s=St(i.total)||n,a=St(i.completed),c=St(i.failed),l=Math.max(0,s-a-c),u=rv.has(o),d=o==="failed"?{processing:0,
1770
1775
  succeeded:0,errored:s,canceled:0,expired:0}:{processing:u?0:l,succeeded:a,errored:c+(o==="completed"?l:0),canceled:o==="cancelled"?l:0,expired:o==="expired"?l:0},p=Array.isArray(le(r.errors).data)?le(
1771
1776
  r.errors).data.map(h=>le(h).message).filter(h=>typeof h=="string"):[];return {id:t,estado:o,terminado:u,cancelando:o==="cancelling",cuentas:d,...typeof r.output_file_id=="string"&&r.output_file_id!==""?
1772
1777
  {salida:r.output_file_id}:{},...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"}:{}}}
1773
- function vp(t,e){let n={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+=
1778
+ function kp(t,e){let n={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+=
1774
1779
  o.cuentas.canceled,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=>({
1775
- id:o.id,status:o.estado}))}}async function uv(t,e,n){t.exigirLicencia(),t.exigirPalancas?.();let r=Ko(t);Oa(e,r);let o=await Wo(r,e,n);for(let i of o)i.terminado||i.cancelando||await pr(r,`${La(r,i.id)}\
1776
- /cancel`,{method:"POST",...n?{signal:n}:{}});return vp(e,await Wo(r,e,n))}async function dv(t,e,n){t.exigirLicencia(),t.exigirPalancas?.();let r=Ko(t);Oa(e,r);let o=await Wo(r,e,n),i=new Map;for(let l of o)
1777
- if(l.terminado)if(r.protocolo==="anthropic"){let u=await Da(r,`${La(r,l.id)}/results`,{method:"GET",...n?{signal:n}:{}});for await(let d of mp(u))pv(i,d);}else for(let u of [l.salida,l.errores]){if(!u)continue;
1778
- let d=await Da(r,`/files/${encodeURIComponent(u)}/content`,{method:"GET",...n?{signal:n}:{}});for await(let p of mp(d))fv(i,p);}let s=Math.max(t.now(),Date.parse(e.submittedAt)||0),a=[],c=0;for(let l of e.
1779
- requests){let u=o[l.batch];if(!u.terminado){c+=1;continue}let d=l.schema!==void 0?e.schemas[l.schema]:void 0;a.push(mv(t,r,l,d,i.get(l.customId),u,s));}return {ended:o.every(l=>l.terminado),items:a,summary:bv(
1780
- e,a,c)}}function pv(t,e){let n=le(e),r=n.custom_id;if(typeof r!="string"||t.has(r))return;let o=le(n.result);switch(o.type){case "succeeded":t.set(r,{tipo:"ok",cuerpo:o.message});return;case "errored":{
1780
+ id:o.id,status:o.estado}))}}async function mv(t,e,n){t.exigirLicencia(),t.exigirPalancas?.();let r=Ko(t);Oa(e,r);let o=await Wo(r,e,n);for(let i of o)i.terminado||i.cancelando||await pr(r,`${La(r,i.id)}\
1781
+ /cancel`,{method:"POST",...n?{signal:n}:{}});return kp(e,await Wo(r,e,n))}async function hv(t,e,n){t.exigirLicencia(),t.exigirPalancas?.();let r=Ko(t);Oa(e,r);let o=await Wo(r,e,n),i=new Map;for(let l of o)
1782
+ if(l.terminado)if(r.protocolo==="anthropic"){let u=await Da(r,`${La(r,l.id)}/results`,{method:"GET",...n?{signal:n}:{}});for await(let d of gp(u))gv(i,d);}else for(let u of [l.salida,l.errores]){if(!u)continue;
1783
+ let d=await Da(r,`/files/${encodeURIComponent(u)}/content`,{method:"GET",...n?{signal:n}:{}});for await(let p of gp(d))bv(i,p);}let s=Math.max(t.now(),Date.parse(e.submittedAt)||0),a=[],c=0;for(let l of e.
1784
+ requests){let u=o[l.batch];if(!u.terminado){c+=1;continue}let d=l.schema!==void 0?e.schemas[l.schema]:void 0;a.push(vv(t,r,l,d,i.get(l.customId),u,s));}return {ended:o.every(l=>l.terminado),items:a,summary:xv(
1785
+ e,a,c)}}function gv(t,e){let n=le(e),r=n.custom_id;if(typeof r!="string"||t.has(r))return;let o=le(n.result);switch(o.type){case "succeeded":t.set(r,{tipo:"ok",cuerpo:o.message});return;case "errored":{
1781
1786
  let i=le(le(o.error).error);t.set(r,{tipo:"errored",error:{type:typeof i.type=="string"?i.type:"error",message:typeof i.message=="string"?i.message:"the provider reported an error"}});return}case "canc\
1782
- eled":t.set(r,{tipo:"canceled"});return;case "expired":t.set(r,{tipo:"expired"});return;default:return}}function fv(t,e){let n=le(e),r=n.custom_id;if(typeof r!="string"||t.has(r))return;let o=n.error;if(o!=
1787
+ eled":t.set(r,{tipo:"canceled"});return;case "expired":t.set(r,{tipo:"expired"});return;default:return}}function bv(t,e){let n=le(e),r=n.custom_id;if(typeof r!="string"||t.has(r))return;let o=n.error;if(o!=
1783
1788
  null){let l=le(o),u=typeof l.code=="string"?l.code:"error";if(u==="batch_expired"){t.set(r,{tipo:"expired"});return}if(u==="batch_cancelled"||u==="batch_canceled"){t.set(r,{tipo:"canceled"});return}t.
1784
1789
  set(r,{tipo:"errored",error:{type:u,message:typeof l.message=="string"?l.message:"the provider reported an error"}});return}let i=le(n.response),s=i.status_code,a=i.body;if(typeof s=="number"&&s>=200&&
1785
1790
  s<300&&a!==void 0){t.set(r,{tipo:"ok",cuerpo:a});return}let c=le(le(a).error);t.set(r,{tipo:"errored",error:{type:typeof c.type=="string"?c.type:`http_${typeof s=="number"?s:"error"}`,message:typeof c.
1786
- message=="string"?c.message:"the provider reported an error"}});}function mv(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,
1791
+ message=="string"?c.message:"the provider reported an error"}});}function vv(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,
1787
1792
  outcome:"errored",reason:`the provider rejected the whole batch before running it: ${i.fallo??"no reason given"}`,error:{type:"batch_failed",message:i.fallo??"the provider rejected the batch"}}:i.estado===
1788
1793
  "expired"?{...a,outcome:"expired",reason:"the batch expired before this request ran: no answer and no usage"}:i.estado==="cancelled"?{...a,outcome:"canceled",reason:"the batch was canceled before this\
1789
1794
  request ran: no answer and no usage"}:{...a,outcome:"missing",reason:"the provider returned no result line for this request; nothing is assumed about it"};switch(o.tipo){case "errored":return {...a,outcome:"\
@@ -1791,77 +1796,77 @@ errored",reason:`the provider could not run this request (${o.error.type}: ${o.e
1791
1796
  ...a,outcome:"canceled",reason:c?"canceled before 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:"\
1792
1797
  expired",reason:c?"the batch reached its 24-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 exp\
1793
1798
  ired: no answer and no usage"};}let l={model:n.model,messages:[],...r?{schema:r}:{}},u;try{u=e.leer(o.cuerpo,l);}catch(y){return {...a,outcome:"succeeded",reason:`the provider ran this req\
1794
- uest but its answer could not be read (${Ho(y)}): nothing is credited`}}let d=hv(u,r),p=c?u.servedServiceTier:"batch",h=e.origen==="anthropic"||e.origen==="openai"?e.origen:null,f=vv(t.costModels,n.model),
1799
+ uest but its answer could not be read (${Ho(y)}): nothing is credited`}}let d=yv(u,r),p=c?u.servedServiceTier:"batch",h=e.origen==="anthropic"||e.origen==="openai"?e.origen:null,f=wv(t.costModels,n.model),
1795
1800
  m=Hr({modelo:n.model,uso:u.usage,tierServido:p,origen:h,tierLeidoDe:c?"cuerpo":"lote",...f?{precioDelCliente:f}:{},ahoraMs:s}),g={...a,outcome:"succeeded",text:u.text,...d,...u.toolCalls&&u.toolCalls.
1796
- length>0?{toolCalls:u.toolCalls}:{},...u.finishReason?{finishReason:u.finishReason}:{},usage:u.usage,...p?{servedTier:p}:{}};if(!m.ok)return {...g,reason:gv(m.motivo,p)};let b={amount:m.importe,basis:m.
1801
+ length>0?{toolCalls:u.toolCalls}:{},...u.finishReason?{finishReason:u.finishReason}:{},usage:u.usage,...p?{servedTier:p}:{}};if(!m.ok)return {...g,reason:kv(m.motivo,p)};let b={amount:m.importe,basis:m.
1797
1802
  basis,standardCost:Go(m.costeEstandar),appliedCost:Go(m.costeAplicado),pricesCheckedOn:m.consultado,basisReason:m.motivoBasis};return {...g,tierSaving:b,reason:`billed at the "${p}" tier; this request'\
1798
- s usage was priced at the standard and at the batch published rate cards, component by component (${(m.factorEfectivo*100).toFixed(1)}% of standard)`}}function hv(t,e){if(!e||(t.toolCalls?.length??0)>
1799
- 0)return {};let n=et(typeof t.text=="string"?t.text:"");return n.ok?be(n.value,e).valid?{data:n.value,contract:"met"}:{contract:"missed"}:{contract:"missed"}}function gv(t,e){switch(t){case "no-served-t\
1803
+ s usage was priced at the standard and at the batch published rate cards, component by component (${(m.factorEfectivo*100).toFixed(1)}% of standard)`}}function yv(t,e){if(!e||(t.toolCalls?.length??0)>
1804
+ 0)return {};let n=et(typeof t.text=="string"?t.text:"");return n.ok?be(n.value,e).valid?{data:n.value,contract:"met"}:{contract:"missed"}:{contract:"missed"}}function kv(t,e){switch(t){case "no-served-t\
1800
1805
  ier":return "the provider reported no service tier for this 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\
1801
1806
  this result, a tier this layer has no published rate for: nothing is credited`;case "standard-rate-tier":return `the provider reports the "${e}" tier for this result, which is not billed below the stan\
1802
1807
  dard rate: nothing is credited`;case "no-tier-price":return "there is no published batch price for this model from this provider (or it has expired): nothing is credited";case "no-standard-price":return "\
1803
1808
  this model has no list price of its own here, so there is no standard rate card to price the difference against: nothing is credited";case "incomplete-usage":return "the provider's usage for this result\
1804
- is incomplete, so the difference cannot be priced: nothing is credited";case "no-difference":return "this result's usage costs the same at both published rate cards: nothing is credited"}}var fp=1e10;function bv(t,e,n){
1809
+ is incomplete, so the difference cannot be priced: nothing is credited";case "no-difference":return "this result's usage costs the same at both published rate cards: nothing is credited"}}var hp=1e10;function xv(t,e,n){
1805
1810
  let r=0,o=0,i=0,s=0,a=0,c=0,l=0,u=0n,d=0,p=0,h;for(let g of e){g.outcome==="succeeded"?r+=1:g.outcome==="errored"?o+=1:g.outcome==="canceled"?i+=1:g.outcome==="expired"?s+=1:a+=1;let b=g.tierSaving;b&&
1806
- (c+=1,b.basis==="measured"&&(l+=1),u+=BigInt(Math.round(b.amount*fp)),d+=b.standardCost,p+=b.appliedCost,(!h||b.pricesCheckedOn<h)&&(h=b.pricesCheckedOn));}let f=c===0?"none":l===c?"measured":"estimate\
1811
+ (c+=1,b.basis==="measured"&&(l+=1),u+=BigInt(Math.round(b.amount*hp)),d+=b.standardCost,p+=b.appliedCost,(!h||b.pricesCheckedOn<h)&&(h=b.pricesCheckedOn));}let f=c===0?"none":l===c?"measured":"estimate\
1807
1812
  d",m=`${r} of ${t.requests.length} requests succeeded`+(n>0?` (${n} still running)`:"")+`; ${c} were valued at the provider's standard and batch published rate cards`+(f==="none"?"":` (${f})`)+". Repo\
1808
1813
  rted only: batch requests are not metered and 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,
1809
- expired:s,missing:a,pending:n,credited:c,tierSaving:Number(u)/fp,standardCost:Go(d),appliedCost:Go(p),basis:f,...h?{pricesCheckedOn:h}:{},creditedLedger:"none",reason:m}}function Oa(t,e){let n=t;if(!n||
1814
+ expired:s,missing:a,pending:n,credited:c,tierSaving:Number(u)/hp,standardCost:Go(d),appliedCost:Go(p),basis:f,...h?{pricesCheckedOn:h}:{},creditedLedger:"none",reason:m}}function Oa(t,e){let n=t;if(!n||
1810
1815
  n.kind!=="bvsala.batch"||n.version!==1||!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.
1811
1816
  length))throw new TypeError("[bvsala] 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\
1812
1817
  ${n.provider} at ${n.endpoint}; this layer's provider is ${e.protocolo} at ${e.endpoint}. Read it with a layer configured like the one that submitted it.`)}function La(t,e){return t.protocolo==="anth\
1813
1818
  ropic"?`/messages/batches/${encodeURIComponent(e)}`:`/batches/${encodeURIComponent(e)}`}async function Da(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(
1814
1819
  `provider ${r.status}: ${o}`)}return r}async function pr(t,e,n){return await(await Da(t,e,n)).json()}function Aa(t,e){let n=le(t).id;if(typeof n!="string"||n==="")throw new Error(`the provider returne\
1815
- d no ${e} id`);return n}async function*mp(t){let e=t.body;if(!e||typeof e.getReader!="function"){for(let s of (await t.text()).split(`
1816
- `)){let a=_a(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(`
1817
- `);for(;c>=0;){let l=_a(o.slice(0,c));l!==void 0&&(yield l),o=o.slice(c+1),c=o.indexOf(`
1818
- `);}}o+=r.decode();let i=_a(o);i!==void 0&&(yield i);}function _a(t){let e=t.trim();if(e!=="")try{return JSON.parse(e)}catch{return}}function vv(t,e){if(!t)return;let n=t[e];if(n)return n;let r=e.indexOf(
1820
+ d no ${e} id`);return n}async function*gp(t){let e=t.body;if(!e||typeof e.getReader!="function"){for(let s of (await t.text()).split(`
1821
+ `)){let a=Ia(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(`
1822
+ `);for(;c>=0;){let l=Ia(o.slice(0,c));l!==void 0&&(yield l),o=o.slice(c+1),c=o.indexOf(`
1823
+ `);}}o+=r.decode();let i=Ia(o);i!==void 0&&(yield i);}function Ia(t){let e=t.trim();if(e!=="")try{return JSON.parse(e)}catch{return}}function wv(t,e){if(!t)return;let n=t[e];if(n)return n;let r=e.indexOf(
1819
1824
  "/");return r>=0?t[e.slice(r+1)]:void 0}function le(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 Ho(t){return t instanceof
1820
- Error?t.message:String(t)}function Go(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function yv(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.hash="",e.toString()}catch{return "the configured licenseServerUrl"}}var kv=36e5,xv=7*86400,wv=3e4,Jo=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;credencialAvisada=new Set;currentExpiresAt;currentOrg;currentPlan;currentJti;constructor(e){
1821
- this.opts=e,this.pollIntervalMs=e.pollIntervalMs??kv,this.refreshLeadSeconds=e.refreshLeadSeconds??xv;let n=kt(yt(e.initialToken),e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.
1825
+ Error?t.message:String(t)}function Go(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Sv(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.hash="",e.toString()}catch{return "the configured licenseServerUrl"}}var Ev=36e5,Cv=7*86400,Tv=3e4,Jo=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;credencialAvisada=new Set;currentExpiresAt;currentOrg;currentPlan;currentJti;constructor(e){
1826
+ this.opts=e,this.pollIntervalMs=e.pollIntervalMs??Ev,this.refreshLeadSeconds=e.refreshLeadSeconds??Cv;let n=kt(yt(e.initialToken),e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.
1822
1827
  expires_at:0,this.currentOrg=n.signatureValid?n.payload?.org_id:void 0,this.currentPlan=n.signatureValid?n.payload?.plan:void 0,this.currentJti=n.signatureValid?n.payload?.jti:void 0;}start(){this.timer||
1823
1828
  (this.checkNow(),this.timer=setInterval(()=>{this.checkNow();},this.pollIntervalMs),this.timer.unref?.());}stop(){this.parado=true,this.timer&&clearInterval(this.timer),this.timer=null,this.controller?.abort(),
1824
1829
  this.controller=null;}avisarCredencialRechazada(e){this.credencialAvisada.has(e)||(this.credencialAvisada.add(e),console.warn(`[bv-sala] automatic pickup of the renewed license is failing with HTTP ${e}\
1825
- at ${yv(this.opts.url)}. Check 'serviceAccountKey' (rotated? from another organization?) and 'licenseServerUrl': until this works, the token will NOT renew itself and the SDK will stop operating when\
1830
+ at ${Sv(this.opts.url)}. Check 'serviceAccountKey' (rotated? from another organization?) and 'licenseServerUrl': until this works, the token will NOT renew itself and the SDK will stop operating when\
1826
1831
  the grace period ends. (This warning is not muted by 'silenceWarnings'.)`));}nowSeconds(){return Math.floor((this.opts.now?this.opts.now():Date.now())/1e3)}async checkNow(){if(this.enVuelo||this.parado)
1827
1832
  return false;let e=this.currentJti!==void 0&&this.opts.revocados?.snapshot().has(this.currentJti)===true;if(this.currentPlan!=="measure"&&!e&&this.currentExpiresAt-this.nowSeconds()>this.refreshLeadSeconds)
1828
- return false;this.enVuelo=true;let n=new AbortController;this.controller=n;let r=setTimeout(()=>n.abort(),this.opts.requestTimeoutMs??wv);r.unref?.();try{let i=await(this.opts.fetchImpl??globalThis.fetch.bind(
1833
+ return false;this.enVuelo=true;let n=new AbortController;this.controller=n;let r=setTimeout(()=>n.abort(),this.opts.requestTimeoutMs??Tv);r.unref?.();try{let i=await(this.opts.fetchImpl??globalThis.fetch.bind(
1829
1834
  globalThis))(this.opts.url,{signal:n.signal,headers:{authorization:`Bearer ${this.opts.serviceAccountKey}`,accept:"application/json"}});if(!i.ok)return (i.status===401||i.status===403||i.status===404)&&
1830
1835
  this.avisarCredencialRechazada(i.status),!1;this.credencialAvisada.clear();let s=await i.json();if(typeof s.token!="string")return !1;let a=yt(s.token),c=kt(a,this.opts.publicKey);if(!c.signatureValid||
1831
1836
  !c.payload)return !1;let l=this.currentPlan==="measure"&&c.payload.plan!=="measure",u=e&&c.payload.jti!==this.currentJti;return !l&&!u&&c.payload.expires_at<=this.currentExpiresAt||this.currentOrg&&c.payload.
1832
1837
  org_id!==this.currentOrg||this.opts.revocados?.snapshot().has(c.payload.jti)||this.parado?!1:(this.currentExpiresAt=c.payload.expires_at,this.currentOrg=c.payload.org_id,this.currentPlan=c.payload.plan,
1833
- this.currentJti=c.payload.jti,this.opts.onNewToken(a),!0)}catch{return false}finally{clearTimeout(r),this.controller===n&&(this.controller=null),this.enVuelo=false;}}};var yp=2e3,kp=200,Sv=200,Ev=10,Cv=1e7,Tv=5,Rv=48*3600*1e3,Ma=/^[A-Za-z0-9._:/-]{1,128}$/,wn=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,fr=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=
1834
- 1e3;function Pv(t,e={}){if(!Ma.test(t.requestId)||!Ma.test(t.requestedModel)||!Ma.test(t.servedModel)||typeof t.at!="number"||!Number.isFinite(t.at)||t.at<1e12)return null;let n=typeof e?.ahora=="numb\
1835
- er"?e.ahora:Date.now();if(t.at>n+Rv)return null;let r=t.optimized;if(!fr(r.cost)||!wn(r.inputTokens)||!wn(r.cachedInputTokens)||!wn(r.outputTokens))return null;let o=t.prices;if(!fr(o.inputPer1k)||!fr(
1838
+ this.currentJti=c.payload.jti,this.opts.onNewToken(a),!0)}catch{return false}finally{clearTimeout(r),this.controller===n&&(this.controller=null),this.enVuelo=false;}}};var xp=2e3,wp=200,Rv=200,Pv=10,_v=1e7,Iv=5,Dv=48*3600*1e3,Ma=/^[A-Za-z0-9._:/-]{1,128}$/,wn=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,fr=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=
1839
+ 1e3;function Av(t,e={}){if(!Ma.test(t.requestId)||!Ma.test(t.requestedModel)||!Ma.test(t.servedModel)||typeof t.at!="number"||!Number.isFinite(t.at)||t.at<1e12)return null;let n=typeof e?.ahora=="numb\
1840
+ er"?e.ahora:Date.now();if(t.at>n+Dv)return null;let r=t.optimized;if(!fr(r.cost)||!wn(r.inputTokens)||!wn(r.cachedInputTokens)||!wn(r.outputTokens))return null;let o=t.prices;if(!fr(o.inputPer1k)||!fr(
1836
1841
  o.outputPer1k)||o.cachedInputPer1k!==void 0&&!fr(o.cachedInputPer1k))return null;let i={basis:"verification",requestId:t.requestId,at:Math.floor(t.at),stratum:t.stratum,outcome:t.outcome,requestedModel:t.
1837
1842
  requestedModel,servedModel:t.servedModel,cacheResult:t.cacheResult,optimizedCost:r.cost,optimizedInputTokens:r.inputTokens,optimizedCachedInputTokens:Math.min(r.cachedInputTokens,r.inputTokens),optimizedOutputTokens:r.
1838
1843
  outputTokens,inputPer1k:o.inputPer1k,...o.cachedInputPer1k!==void 0?{cachedInputPer1k:o.cachedInputPer1k}:{},outputPer1k:o.outputPer1k};if(t.outcome==="paired"){let s=t.naive;if(!s||!fr(s.cost)||!wn(s.
1839
1844
  inputTokens)||!wn(s.cachedInputTokens)||!wn(s.outputTokens)||s.cachedInputTokens>s.inputTokens)return null;if(i.naiveCost=s.cost,i.naiveInputTokens=s.inputTokens,i.naiveCachedInputTokens=s.cachedInputTokens,
1840
1845
  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 Yo=class{o;flushIntervalMs;pendientes=[];conteos=new Map;reintentos=[];inflight=null;timer;fallosSeguidos=0;ultimoFallo=Number.
1841
- 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=Pv(e,{ahora:this.ahora()});}catch{n=null;}n&&(this.pendientes.
1842
- push(n),this.pendientes.length>yp&&this.pendientes.splice(0,this.pendientes.length-yp),this.pendientes.length>=kp&&this.flushSiToca());}flushSiToca(){return this.reintentos.length>0&&this.ahora()-this.
1846
+ 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=Av(e,{ahora:this.ahora()});}catch{n=null;}n&&(this.pendientes.
1847
+ push(n),this.pendientes.length>xp&&this.pendientes.splice(0,this.pendientes.length-xp),this.pendientes.length>=wp&&this.flushSiToca());}flushSiToca(){return this.reintentos.length>0&&this.ahora()-this.
1843
1848
  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();},
1844
1849
  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();
1845
1850
  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;
1846
- if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,kp),r=[];for(let[o,i]of this.conteos){if(r.length>=Sv)break;let[s="",a=""]=o.split("|"),c=Math.min(i,Cv);
1851
+ if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,wp),r=[];for(let[o,i]of this.conteos){if(r.length>=Rv)break;let[s="",a=""]=o.split("|"),c=Math.min(i,_v);
1847
1852
  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??Pt)(),samples:n,counts:r}}async hacerFlush(){let e=this.o.fetchImpl??globalThis.
1848
- fetch;if(e)for(let n=0;n<Tv&&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:`\
1853
+ fetch;if(e)for(let n=0;n<Iv&&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:`\
1849
1854
  Bearer ${this.o.serviceAccountKey}`,"content-type":"application/json",[wr]:`sdk/${Ve}`},body:JSON.stringify(n)});return r.ok?(this.fallosSeguidos=0,!0):r.status>=500?(this.fallosSeguidos++,this.ultimoFallo=
1850
1855
  this.ahora(),this.reencolar(n),this.avisarDeFallo(`the server responded ${r.status}`),!1):r.status===401||r.status===403?(this.o.silenceWarnings||Ee(`verification-auth-${r.status}`,`[bvsala] verificat\
1851
1856
  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):
1852
1857
  (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 \
1853
1858
  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.
1854
- reintentos.unshift(e);this.reintentos.length>Ev;)this.reintentos.pop();}avisarDeFallo(e){if(this.o.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.warn(`[bvsala] verificatio\
1859
+ reintentos.unshift(e);this.reintentos.length>Pv;)this.reintentos.pop();}avisarDeFallo(e){if(this.o.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.warn(`[bvsala] verificatio\
1855
1860
  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,
1856
- conteos:this.conteos.size,reintentos:this.reintentos.length}}};var $a=72*3600,Iv,xp=new Set(Object.values(Sr).flatMap(t=>t.flatMap(e=>[e,`openai/${e}`]))),wp="[bvsala] `gpt-tokenizer` is not installed, so token counts for OpenAI models are ESTIMATED with a built-\
1861
+ conteos:this.conteos.size,reintentos:this.reintentos.length}}};var $a=72*3600,Ov,Sp=new Set(Object.values(Sr).flatMap(t=>t.flatMap(e=>[e,`openai/${e}`]))),Ep="[bvsala] `gpt-tokenizer` is not installed, so token counts for OpenAI models are ESTIMATED with a built-\
1857
1862
  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 \
1858
- (`npm i gpt-tokenizer`) and the SDK loads it automatically.";function FC(t){let e=(f,m)=>{t.silenceWarnings!==true&&Ee(f,m);},n=(f,m)=>{el()||e(f,m);};t.semanticCache!==void 0&&n("semanticCache-renombrado",
1863
+ (`npm i gpt-tokenizer`) and the SDK loads it automatically.";function HC(t){let e=(f,m)=>{t.silenceWarnings!==true&&Ee(f,m);},n=(f,m)=>{el()||e(f,m);};t.semanticCache!==void 0&&n("semanticCache-renombrado",
1859
1864
  "[bvsala] `createSavingsLayer({ semanticCache })` is deprecated: pass the store as `semanticCacheStore` (same value; `savings.semanticCache` on a request does not change). The old name is removed in 0\
1860
1865
  .5."+(t.semanticCacheStore!==void 0&&t.semanticCacheStore!==t.semanticCache?" Both were given and they differ: `semanticCacheStore` is the one in use.":""));t.licensePublicKey!==void 0&&n(
1861
1866
  "licensePublicKey-obsoleto","[bvsala] `createSavingsLayer({ licensePublicKey })` is deprecated and ignored: the published package always verifies `licenseKey` against BiVelio's embedded public key. Th\
1862
1867
  e option is removed in 0.5; delete it from your config."),t.licenseGate&&(e("licenseGate-ignorado","[bvsala] Ignoring the injected `licenseGate`: in the published package a license is only accepted\
1863
1868
  as a `licenseKey` verified against BiVelio's embedded public key, and the `licenseGate` option is removed in 0.5. Get yours at https://savings.bivelio.com/dashboard/install"),t={...t,licenseGate:void 0});
1864
- let o={...t,tokenizer:t.tokenizer??di},i=t.tokenizer==null&&t.exactTokenizer!==false?Iv??=fi(di).catch(()=>false):Promise.resolve(true),s,a;if(t.licenseKey&&!t.licenseGate){let f=So;if(t.
1869
+ let o={...t,tokenizer:t.tokenizer??di},i=t.tokenizer==null&&t.exactTokenizer!==false?Ov??=fi(di).catch(()=>false):Promise.resolve(true),s,a;if(t.licenseKey&&!t.licenseGate){let f=So;if(t.
1865
1870
  licenseServerUrl){let m=new xt,g=v=>mn(v,f,{revocation:m,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??$a}),b=g(t.licenseKey);o.licenseGate={isEntitled:v=>b.isEntitled(
1866
1871
  v),isActive:()=>b.isActive(),status:()=>b.status(),reason:()=>b.reason(),plan:()=>b.plan?.()};let y=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;s=new gn({url:y,publicKeyPem:f,snapshot:m,
1867
1872
  getRefreshAfter:()=>b.refreshAfter?.(),...t.now?{nowSeconds:()=>Math.floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.
@@ -1870,98 +1875,98 @@ url:`${t.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,serviceAccoun
1870
1875
  licenseFetch}:{},...t.now?{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.
1871
1876
  leadSeconds}:{}}),a.start());}else o.licenseGate=Co(t.licenseKey,f,t.now);}t.cacheBreakpointStore&&t.cacheBreakpoints!=="auto"&&e("almacen-de-colocacion-sin-auto",'[bv-sala] `cacheBreakpointStore` was g\
1872
1877
  iven but `cacheBreakpoints` is not "auto", so the store is never read or written: it only holds the measurement of `cacheBreakpoints: "auto"`. Set `cacheBreakpoints: "auto"` to use it, or remove it.');
1873
- let c=qo(t.verification);!c.activo&&c.motivo==="invalido"&&e("verificacion-invalida",Qd(t.verification));let l,u;if(c.activo){let f;if(t.serviceAccountKey&&t.metering?.enabled!==false)if(t.meteringUrl){let m=/^(.*)\/api\/metering\/usage\/?$/.
1878
+ let c=qo(t.verification);!c.activo&&c.motivo==="invalido"&&e("verificacion-invalida",tp(t.verification));let l,u;if(c.activo){let f;if(t.serviceAccountKey&&t.metering?.enabled!==false)if(t.meteringUrl){let m=/^(.*)\/api\/metering\/usage\/?$/.
1874
1879
  exec(t.meteringUrl);m&&(f=`${m[1]}/api/metering/verification`);}else t.licenseServerUrl&&(f=`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/verification`);if(!f&&!c.onCheck)e("verificacion-sin-d\
1875
- estino",ep);else {f&&t.serviceAccountKey&&(l=new Yo({url:f,serviceAccountKey:t.serviceAccountKey,...t.meteringFetch?{fetchImpl:t.meteringFetch}:t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.
1880
+ estino",np);else {f&&t.serviceAccountKey&&(l=new Yo({url:f,serviceAccountKey:t.serviceAccountKey,...t.meteringFetch?{fetchImpl:t.meteringFetch}:t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.
1876
1881
  now}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}}),l.start());let m=l;u={encolar:g=>m?.encolar(
1877
- g),...m?{contar:(g,b)=>m.contar(g,b)}:{},enReposo:()=>m?.flushSiToca()},e(`verificacion-activa:${c.tasa}`,Xd(c.tasa));}}let d=new Vo(o,u?{verificacion:u}:{}),p;if(t.serviceAccountKey&&t.metering?.enabled!==
1882
+ g),...m?{contar:(g,b)=>m.contar(g,b)}:{},enReposo:()=>m?.flushSiToca()},e(`verificacion-activa:${c.tasa}`,ep(c.tasa));}}let d=new Vo(o,u?{verificacion:u}:{}),p;if(t.serviceAccountKey&&t.metering?.enabled!==
1878
1883
  false){let f=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/usage`:void 0);if(f||e("clave-de-servicio-sin-servidor",'[bvsala] `serviceAccountKey` is set but the\
1879
1884
  re is no `licenseServerUrl` (or `meteringUrl`): seat metering and automatic license renewal are OFF, so nothing will reach your dashboard and a renewed license will not be picked up. Add `licenseServe\
1880
1885
  rUrl: "https://savings.bivelio.com"` \u2014 or drop `serviceAccountKey` for a zero-network deployment.'),f){p=new Ft({url:f,serviceAccountKey:t.serviceAccountKey,surface:"sdk",...t.metering?.orgId?{orgId:t.
1881
1886
  metering.orgId}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.metering?.maxBatch!=null?{maxBatch:t.metering.maxBatch}:{},...t.metering?.maxBuffer!=null?{
1882
1887
  maxBuffer:t.metering.maxBuffer}:{},...t.meteringFetch?{fetchImpl:t.meteringFetch}:t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.
1883
1888
  silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let m=t.metering?.ci??tr();if(t.metering?.seatId)p.setSeat(t.metering.seatId,m);else {let g=p;nr(t.serviceAccountKey).then(b=>g.setSeat(b,
1884
- m)).catch(()=>{});}p.start();}}return {batches:bp({provider:o.provider,...o.costModels?{costModels:o.costModels}:{},exigirLicencia:()=>d.exigirLicencia(),exigirPalancas:()=>d.exigirPalancas(),now:o.now??
1885
- Date.now}),generate:async f=>{let m=await i,g=await d.generate(f);if(!m&&xp.has(f.model)&&e("tokenizador-exacto-ausente",wp),p)try{p.record(g.report);}catch{}return g},generateStream:(f,m)=>{let g=d.generateStream(
1886
- f,m??{},i);return g.result.then(async b=>{if(p)try{p.record(b.report);}catch{}!await i&&xp.has(f.model)&&e("tokenizador-exacto-ausente",wp);},()=>{}),g},close:()=>{d.cerrarVerificacion(),l?.stop(),s?.stop(),
1889
+ m)).catch(()=>{});}p.start();}}return {batches:yp({provider:o.provider,...o.costModels?{costModels:o.costModels}:{},exigirLicencia:()=>d.exigirLicencia(),exigirPalancas:()=>d.exigirPalancas(),now:o.now??
1890
+ Date.now}),generate:async f=>{let m=await i,g=await d.generate(f);if(!m&&Sp.has(f.model)&&e("tokenizador-exacto-ausente",Ep),p)try{p.record(g.report);}catch{}return g},generateStream:(f,m)=>{let g=d.generateStream(
1891
+ f,m??{},i);return g.result.then(async b=>{if(p)try{p.record(b.report);}catch{}!await i&&Sp.has(f.model)&&e("tokenizador-exacto-ausente",Ep);},()=>{}),g},close:()=>{d.cerrarVerificacion(),l?.stop(),s?.stop(),
1887
1892
  a?.stop(),p?.stop();}}}function Na(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.
1888
- toFixed(10).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return e==="-0"?"0":e}function Sp(t,e){if(t==null)return "";if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`[bvsala] toCsv: \
1893
+ toFixed(10).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return e==="-0"?"0":e}function Cp(t,e){if(t==null)return "";if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`[bvsala] toCsv: \
1889
1894
  column "${e}" holds a non-finite number`);return Na(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\
1890
- 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 _v(t,e){
1891
- 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=>Sp(o,o)).join(",")];for(let o of t)r.push(n.map(
1892
- i=>Sp(o[i],i)).join(","));return r.map(o=>`${o}\r
1893
- `).join("")}var Ep={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:"\
1894
- 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 Cp(t){let e=t.
1895
- indexOf("/");return e>0?t.slice(0,e):void 0}function ja(t){let e=Cp(t)?.toLowerCase();return e!==void 0&&Object.hasOwn(Ep,e)?Ep[e]:void 0}function Tp(t){return ja(t)?.otel??Cp(t)}function Rp(t){return ja(
1895
+ 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 Lv(t,e){
1896
+ 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=>Cp(o,o)).join(",")];for(let o of t)r.push(n.map(
1897
+ i=>Cp(o[i],i)).join(","));return r.map(o=>`${o}\r
1898
+ `).join("")}var Tp={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:"\
1899
+ 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 Rp(t){let e=t.
1900
+ indexOf("/");return e>0?t.slice(0,e):void 0}function ja(t){let e=Rp(t)?.toLowerCase();return e!==void 0&&Object.hasOwn(Tp,e)?Tp[e]:void 0}function Pp(t){return ja(t)?.otel??Rp(t)}function _p(t){return ja(
1896
1901
  t)?.nombre}function Wt(t){return ja(t)?t.slice(t.indexOf("/")+1):t}var me={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.\
1897
1902
  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\
1898
- 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"},Pp="error.type",W="com.bivelio.",Ip=`${W}stream.\
1899
- request_sent`;function tt(t){return t==="measured"||t==="reference"||t==="estimated"}function Sn(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function _p(t){return Sn(t.cost.baselineEstimate-t.cost.
1903
+ 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"},Ip="error.type",W="com.bivelio.",Dp=`${W}stream.\
1904
+ request_sent`;function tt(t){return t==="measured"||t==="reference"||t==="estimated"}function Sn(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Ap(t){return Sn(t.cost.baselineEstimate-t.cost.
1900
1905
  actual)}function V(t,e,n){(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))&&(t[e]=n);}function Ba(t,e){let{cost:n,tokens:r,calls:o,cache:i}=t,s={bivelio_request_id:t.requestId,
1901
- bivelio_basis:n.basis,bivelio_currency:e};tt(n.basis)&&(s.bivelio_baseline_cost=n.baselineEstimate,s.bivelio_actual_cost=n.actual,s[`bivelio_saved_${n.basis}`]=_p(t),s.bivelio_net_savings_ratio=n.netSavings),
1906
+ bivelio_basis:n.basis,bivelio_currency:e};tt(n.basis)&&(s.bivelio_baseline_cost=n.baselineEstimate,s.bivelio_actual_cost=n.actual,s[`bivelio_saved_${n.basis}`]=Ap(t),s.bivelio_net_savings_ratio=n.netSavings),
1902
1907
  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=
1903
1908
  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];
1904
1909
  return s}function za(t){let e={};return V(e,me.modeloRespuesta,Wt(t.model)),tt(t.cost.basis)&&(V(e,me.entrada,t.tokens.actualInput),V(e,me.salida,t.tokens.actualOutput),t.tokens.providerCachedInput!==
1905
1910
  void 0&&V(e,me.lecturaDeCache,t.tokens.providerCachedInput)),e}function Zo(t,e){let n=e?.currency??"USD",{cost:r,tokens:o,calls:i,cache:s}=t,a={};V(a,`${W}request_id`,t.requestId),V(a,`${W}sdk.version`,
1906
1911
  Ve),V(a,`${W}model.id`,t.model),V(a,`${W}model.requested_id`,t.modelCascade?.requestedModel),V(a,`${W}cost.basis`,r.basis),V(a,`${W}cost.currency`,n),tt(r.basis)&&(V(a,`${W}cost.baseline`,r.baselineEstimate),
1907
- V(a,`${W}cost.actual`,r.actual),V(a,`${W}cost.saved.${r.basis}`,_p(t)),V(a,`${W}cost.net_savings_ratio`,r.netSavings),V(a,`${W}cost.eliminated_input_floor`,r.eliminatedInputFloorCost)),V(a,`${W}calls.\
1912
+ V(a,`${W}cost.actual`,r.actual),V(a,`${W}cost.saved.${r.basis}`,Ap(t)),V(a,`${W}cost.net_savings_ratio`,r.netSavings),V(a,`${W}cost.eliminated_input_floor`,r.eliminatedInputFloorCost)),V(a,`${W}calls.\
1908
1913
  baseline`,i.baselineLlm),V(a,`${W}calls.actual`,i.actualLlm),V(a,`${W}calls.avoided`,i.avoidedLlm),V(a,`${W}calls.retries`,i.retries),V(a,`${W}tokens.baseline_input`,o.baselineInput),V(a,`${W}tokens.a\
1909
1914
  ctual_input`,o.actualInput),V(a,`${W}tokens.eliminated_input`,o.eliminatedInput),V(a,`${W}tokens.compressed_input`,o.compressedInput),V(a,`${W}tokens.provider_cached_input`,o.providerCachedInput),V(a,
1910
1915
  `${W}tokens.baseline_output`,o.baselineOutput),V(a,`${W}tokens.actual_output`,o.actualOutput),V(a,`${W}tokens.eliminated_output`,o.eliminatedOutput),V(a,`${W}cache.result`,s.result),V(a,`${W}cache.ref\
1911
1916
  erence_request_id`,s.reference?.requestId),V(a,`${W}cache.reference_rejected`,s.referenceRejected),V(a,`${W}quality.status`,t.qualityStatus),V(a,`${W}latency.preprocessing_ms`,t.latencyMs?.preprocessing),
1912
1917
  V(a,`${W}latency.provider_ms`,t.latencyMs?.provider);let l=e?.langfuse?.metadata||e?.datadog?.metadata?Ba(t,n):void 0;if(l&&e?.langfuse?.metadata)for(let[u,d]of Object.entries(l))a[`langfuse.observati\
1913
1918
  on.metadata.${u}`]=typeof d=="number"?Na(d):d;if(e?.langfuse?.cost&&n==="USD"&&tt(r.basis)&&Number.isFinite(r.actual)&&(a["langfuse.observation.cost_details"]=JSON.stringify({total:r.actual})),l&&e?.datadog?.
1914
- metadata){let u={};for(let[d,p]of Object.entries(l))u[d.replace(/^bivelio_/,"")]=p;a["_dd.ml_obs.metadata"]=JSON.stringify({bivelio:u});}return a}var Dv=2,Av=2,Ov="@bivelio/savings-layer";function Lv(t,e,n){try{if(t.isRecording?.()===!1)return;let r=Zo(e,n);n?.genAi&&Object.assign(r,za(e)),t.setAttributes(r);}catch{}}function Fa(t){return typeof t==
1915
- "function"}function Mv(t){let e=t;if(e&&Fa(e.startActiveSpan))return e;if(e&&Fa(e.getTracer)){let n=e.getTracer(Ov,Ve);if(n&&Fa(n.startActiveSpan))return n}throw new TypeError("[bvsala] instrumentSavi\
1916
- ngsLayer: `tracer` must be an OpenTelemetry Tracer, a TracerProvider or the `trace` object of the OpenTelemetry API")}function $v(t){let e=t?.name;return typeof e=="string"&&/^[A-Za-z_$][\w$.-]{0,127}$/.
1917
- test(e)?e:"_OTHER"}function Nv(t,e,n){let r={[me.operacion]:"chat"},o=n??Tp(t.model);typeof o=="string"&&o!==""&&(r[me.proveedor]=o),r[me.modeloPedido]=Wt(t.model);let i=(a,c)=>{typeof c=="number"&&Number.
1919
+ metadata){let u={};for(let[d,p]of Object.entries(l))u[d.replace(/^bivelio_/,"")]=p;a["_dd.ml_obs.metadata"]=JSON.stringify({bivelio:u});}return a}var Mv=2,$v=2,Nv="@bivelio/savings-layer";function jv(t,e,n){try{if(t.isRecording?.()===!1)return;let r=Zo(e,n);n?.genAi&&Object.assign(r,za(e)),t.setAttributes(r);}catch{}}function Fa(t){return typeof t==
1920
+ "function"}function Bv(t){let e=t;if(e&&Fa(e.startActiveSpan))return e;if(e&&Fa(e.getTracer)){let n=e.getTracer(Nv,Ve);if(n&&Fa(n.startActiveSpan))return n}throw new TypeError("[bvsala] instrumentSavi\
1921
+ ngsLayer: `tracer` must be an OpenTelemetry Tracer, a TracerProvider or the `trace` object of the OpenTelemetry API")}function zv(t){let e=t?.name;return typeof e=="string"&&/^[A-Za-z_$][\w$.-]{0,127}$/.
1922
+ test(e)?e:"_OTHER"}function Fv(t,e,n){let r={[me.operacion]:"chat"},o=n??Pp(t.model);typeof o=="string"&&o!==""&&(r[me.proveedor]=o),r[me.modeloPedido]=Wt(t.model);let i=(a,c)=>{typeof c=="number"&&Number.
1918
1923
  isFinite(c)&&(r[a]=c);};i(me.temperatura,t.temperature),i(me.semilla,t.seed),i(me.maxTokens,G(t)),e&&(r[me.stream]=true);let s=t.context?.sessionId;return typeof s=="string"&&s!==""&&(r[me.conversacion]=
1919
- s),r}function Dp(t,e,n){try{if(t.isRecording?.()!==!1){let r=e.report,o={...za(r),...Zo(r,n)};typeof e.finishReason=="string"&&e.finishReason!==""&&(o[me.motivosDeFin]=[e.finishReason]);let i=r.streaming;
1924
+ s),r}function Op(t,e,n){try{if(t.isRecording?.()!==!1){let r=e.report,o={...za(r),...Zo(r,n)};typeof e.finishReason=="string"&&e.finishReason!==""&&(o[me.motivosDeFin]=[e.finishReason]);let i=r.streaming;
1920
1925
  i?.delivery==="live"&&typeof i.firstEventMs=="number"&&Number.isFinite(i.firstEventMs)&&(o[me.primerTrozo]=i.firstEventMs/1e3),t.setAttributes(o);}}catch{}finally{try{t.end();}catch{}}}function qa(t,e){
1921
- try{if(t.isRecording?.()!==!1){let n={[Pp]:$v(e)};e instanceof Te&&(n[Ip]=e.requestSent),t.setAttributes(n),t.setStatus?.({code:Av});}}catch{}finally{try{t.end();}catch{}}}function jv(t,e){let n=Mv(e?.tracer);
1926
+ try{if(t.isRecording?.()!==!1){let n={[Ip]:zv(e)};e instanceof Te&&(n[Dp]=e.requestSent),t.setAttributes(n),t.setStatus?.({code:$v});}}catch{}finally{try{t.end();}catch{}}}function qv(t,e){let n=Bv(e?.tracer);
1922
1927
  if(e.currency!==void 0&&!/^[A-Z]{3}$/.test(e.currency))throw new TypeError(`[bvsala] instrumentSavingsLayer: currency must be an ISO 4217 code such as "USD" (got "${e.currency}")`);let r={...e.currency!==
1923
- void 0?{currency:e.currency}:{},...e.langfuse?{langfuse:e.langfuse}:{},...e.datadog?{datadog:e.datadog}:{}},o=e.providerName;function i(s,a,c,l){let u,d,p=false,h;try{h=Nv(s,a,o);}catch{h=void 0;}let f=`ch\
1924
- at ${Bv(s)}`;try{n.startActiveSpan(f,{kind:Dv,...h?{attributes:h}:{}},m=>{if(u)return u.valor;if(d)throw d.error;if(p){try{m.end();}catch{}return}let g;try{g=c();}catch(b){throw d={error:b},qa(m,b),b}try{
1928
+ void 0?{currency:e.currency}:{},...e.langfuse?{langfuse:e.langfuse}:{},...e.datadog?{datadog:e.datadog}:{}},o=e.providerName;function i(s,a,c,l){let u,d,p=false,h;try{h=Fv(s,a,o);}catch{h=void 0;}let f=`ch\
1929
+ at ${Uv(s)}`;try{n.startActiveSpan(f,{kind:Mv,...h?{attributes:h}:{}},m=>{if(u)return u.valor;if(d)throw d.error;if(p){try{m.end();}catch{}return}let g;try{g=c();}catch(b){throw d={error:b},qa(m,b),b}try{
1925
1930
  u={valor:l(m,g)};}catch{u={valor:g};try{m.end();}catch{}}return u.valor});}catch{}if(d)throw d.error;return u?u.valor:(p=true,c())}return {batches:t.batches,generate(s){return i(s,false,()=>t.generate(s),(a,c)=>c.
1926
- then(l=>(Dp(a,l,r),l),l=>{throw qa(a,l),l}))},generateStream(s,a){return i(s,true,()=>t.generateStream(s,a),(c,l)=>(l.result.then(u=>Dp(c,u,r),u=>qa(c,u)),l))},close(){t.close();}}}function Bv(t){try{return typeof t.
1927
- model=="string"?Wt(t.model):""}catch{return ""}}function zv(t,e){let n=e?.currency??"USD",r={model:Wt(t.model),metadata:Ba(t,n)};if(tt(t.cost.basis)){let{actualInput:o,actualOutput:i,providerCachedInput:s}=t.tokens,a={input:Math.max(0,o-(s??0)),output:i};
1928
- 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 Ap=["measured","reference","estimated","unmeasured"],Ua=36e5,Op=24*Ua;function Xo(t,e){if(t===void 0)return "day";if(t==="hour"||t==="day")return t;throw new TypeError(`[bvsala] ${e}: granularity m\
1931
+ then(l=>(Op(a,l,r),l),l=>{throw qa(a,l),l}))},generateStream(s,a){return i(s,true,()=>t.generateStream(s,a),(c,l)=>(l.result.then(u=>Op(c,u,r),u=>qa(c,u)),l))},close(){t.close();}}}function Uv(t){try{return typeof t.
1932
+ model=="string"?Wt(t.model):""}catch{return ""}}function Vv(t,e){let n=e?.currency??"USD",r={model:Wt(t.model),metadata:Ba(t,n)};if(tt(t.cost.basis)){let{actualInput:o,actualOutput:i,providerCachedInput:s}=t.tokens,a={input:Math.max(0,o-(s??0)),output:i};
1933
+ 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 Lp=["measured","reference","estimated","unmeasured"],Ua=36e5,Mp=24*Ua;function Xo(t,e){if(t===void 0)return "day";if(t==="hour"||t==="day")return t;throw new TypeError(`[bvsala] ${e}: granularity m\
1929
1934
  ust be "hour" or "day"`)}function Qo(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 "\
1930
- USD"`)}function Fv(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(`\
1931
- [bvsala] ${e}: invalid "at" for request ${String(t.report?.requestId)}: expected an ISO 8601 string, epoch milliseconds or a valid Date`);return r}function qv(t,e){let n=e==="hour"?Ua:Op;return Math.floor(
1932
- t/n)*n}function Uv(t,e){return t+(e==="hour"?Ua:Op)}function Et(t){return new Date(t).toISOString().replace(/\.\d{3}Z$/,"Z")}function xe(t,e,n,r){if(typeof t=="number"&&Number.isFinite(t))return t;throw new TypeError(
1935
+ USD"`)}function Hv(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(`\
1936
+ [bvsala] ${e}: invalid "at" for request ${String(t.report?.requestId)}: expected an ISO 8601 string, epoch milliseconds or a valid Date`);return r}function Wv(t,e){let n=e==="hour"?Ua:Mp;return Math.floor(
1937
+ t/n)*n}function Gv(t,e){return t+(e==="hour"?Ua:Mp)}function Et(t){return new Date(t).toISOString().replace(/\.\d{3}Z$/,"Z")}function xe(t,e,n,r){if(typeof t=="number"&&Number.isFinite(t))return t;throw new TypeError(
1933
1938
  `[bvsala] ${r}: report ${n} has no finite number in ${e}`)}function ei(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\
1934
- la] ${n}: every record must be { at, report }`);let a=s.report,c=a.cost?.basis;if(c==="shadow")continue;if(!Ap.includes(c))throw new TypeError(`[bvsala] ${n}: report ${String(a.requestId)} has an unkn\
1935
- own cost basis`);let l=c,u=qv(Fv(s,n),e),{clave:d,extra:p}=r(s,u),h=JSON.stringify([u,a.model,l,d]),f=o.get(h);f||(f={inicio:u,fin:Uv(u,e),modelo:a.model,basis:l,clave:d,extra:p,peticiones:0,llamadas:0,
1939
+ la] ${n}: every record must be { at, report }`);let a=s.report,c=a.cost?.basis;if(c==="shadow")continue;if(!Lp.includes(c))throw new TypeError(`[bvsala] ${n}: report ${String(a.requestId)} has an unkn\
1940
+ own cost basis`);let l=c,u=Wv(Hv(s,n),e),{clave:d,extra:p}=r(s,u),h=JSON.stringify([u,a.model,l,d]),f=o.get(h);f||(f={inicio:u,fin:Gv(u,e),modelo:a.model,basis:l,clave:d,extra:p,peticiones:0,llamadas:0,
1936
1941
  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}},
1937
1942
  o.set(h,f));let m=String(a.requestId);f.peticiones+=1,f.llamadas+=xe(a.calls?.actualLlm,"calls.actualLlm",m,n),f.evitadas+=xe(a.calls?.avoidedLlm,"calls.avoidedLlm",m,n);let g=a.tokens;if(f.tokens.baselineInput+=
1938
1943
  xe(g?.baselineInput,"tokens.baselineInput",m,n),f.tokens.actualInput+=xe(g?.actualInput,"tokens.actualInput",m,n),f.tokens.eliminatedInput+=xe(g?.eliminatedInput,"tokens.eliminatedInput",m,n),f.tokens.
1939
1944
  compressedInput+=xe(g?.compressedInput,"tokens.compressedInput",m,n),f.tokens.baselineOutput+=xe(g?.baselineOutput,"tokens.baselineOutput",m,n),f.tokens.actualOutput+=xe(g?.actualOutput,"tokens.actual\
1940
1945
  Output",m,n),f.tokens.eliminatedOutput+=xe(g?.eliminatedOutput,"tokens.eliminatedOutput",m,n),g.providerCachedInput!==void 0&&(f.tokens.providerCachedInput=(f.tokens.providerCachedInput??0)+xe(g.providerCachedInput,
1941
1946
  "tokens.providerCachedInput",m,n)),tt(l)){let b=xe(a.cost.baselineEstimate,"cost.baselineEstimate",m,n),y=xe(a.cost.actual,"cost.actual",m,n);f.baseline+=b,f.actual+=y,f.ahorro+=b-y,a.cost.eliminatedInputFloorCost!==
1942
- void 0&&(f.suelo=(f.suelo??0)+xe(a.cost.eliminatedInputFloorCost,"cost.eliminatedInputFloorCost",m,n));}}let i=s=>Ap.indexOf(s);return [...o.values()].sort((s,a)=>s.inicio-a.inicio||(s.modelo<a.modelo?-1:
1947
+ void 0&&(f.suelo=(f.suelo??0)+xe(a.cost.eliminatedInputFloorCost,"cost.eliminatedInputFloorCost",m,n));}}let i=s=>Lp.indexOf(s);return [...o.values()].sort((s,a)=>s.inicio-a.inicio||(s.modelo<a.modelo?-1:
1943
1948
  s.modelo>a.modelo?1:0)||i(s.basis)-i(a.basis)||(s.clave<a.clave?-1:s.clave>a.clave?1:0))}function ti(t){let e=tt(t.basis),n=Sn(t.ahorro);return {baseline:e?Sn(t.baseline):null,actual:e?Sn(t.actual):null,
1944
1949
  measured:t.basis==="measured"?n:null,reference:t.basis==="reference"?n:null,estimated:t.basis==="estimated"?n:null,suelo:e&&t.suelo!==void 0?Sn(t.suelo):null}}function ni(t){return JSON.stringify(Object.
1945
1950
  keys(t).sort().map(e=>[e,t[e]]))}function ri(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[
1946
- 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 Vv=new Set(["periodStart","periodEnd","date","model","basis","currency","requests","providerCalls","avoidedCalls","baselineCost","actualCost","measuredSavings","referenceSavings","estimatedSavings",
1951
+ 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 Kv=new Set(["periodStart","periodEnd","date","model","basis","currency","requests","providerCalls","avoidedCalls","baselineCost","actualCost","measuredSavings","referenceSavings","estimatedSavings",
1947
1952
  "eliminatedInputFloorCost","baselineInputTokens","actualInputTokens","eliminatedInputTokens","compressedInputTokens","providerCachedInputTokens","baselineOutputTokens","actualOutputTokens","eliminated\
1948
- OutputTokens","dimensions"]),mr="toSavingsSeries";function Hv(t,e){let n=Xo(e?.granularity,mr),r=Qo(e?.currency,mr),o=e?.dimensions;return ei(t,n,mr,s=>{let a=o?ri(o(s),"dimensions",mr):{};for(let c of Object.
1949
- keys(a))if(Vv.has(c))throw new TypeError(`[bvsala] ${mr}: dimension "${c}" repeats a column of the series`);return {clave:ni(a),extra:a}}).map(s=>{let a=ti(s),c=Et(s.inicio);return {periodStart:c,periodEnd:Et(
1953
+ OutputTokens","dimensions"]),mr="toSavingsSeries";function Jv(t,e){let n=Xo(e?.granularity,mr),r=Qo(e?.currency,mr),o=e?.dimensions;return ei(t,n,mr,s=>{let a=o?ri(o(s),"dimensions",mr):{};for(let c of Object.
1954
+ keys(a))if(Kv.has(c))throw new TypeError(`[bvsala] ${mr}: dimension "${c}" repeats a column of the series`);return {clave:ni(a),extra:a}}).map(s=>{let a=ti(s),c=Et(s.inicio);return {periodStart:c,periodEnd:Et(
1950
1955
  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,
1951
1956
  referenceSavings:a.reference,estimatedSavings:a.estimated,eliminatedInputFloorCost:a.suelo,baselineInputTokens:s.tokens.baselineInput,actualInputTokens:s.tokens.actualInput,eliminatedInputTokens:s.tokens.
1952
1957
  eliminatedInput,compressedInputTokens:s.tokens.compressedInput,providerCachedInputTokens:s.tokens.providerCachedInput??null,baselineOutputTokens:s.tokens.baselineOutput,actualOutputTokens:s.tokens.actualOutput,
1953
- eliminatedOutputTokens:s.tokens.eliminatedOutput,dimensions:Object.freeze({...s.extra})}})}var we="toFocusRows",Wv="BV-SALA savings ledger",Lp="bivelio/";function Gt(t){return typeof t=="string"&&t.trim()!==""}function Va(t,e,n,r){let o=typeof t=="function"?t(n):t??e;if(Gt(o))return o;throw new TypeError(
1954
- `[bvsala] ${we}: cannot determine the FOCUS ${r} for model "${n}". FOCUS allows no placeholder there: pass it in the options.`)}function Gv(t,e,n){if(!n){let s=new Date(t);return {start:Date.UTC(s.getUTCFullYear(),
1958
+ eliminatedOutputTokens:s.tokens.eliminatedOutput,dimensions:Object.freeze({...s.extra})}})}var we="toFocusRows",Yv="BV-SALA savings ledger",$p="bivelio/";function Gt(t){return typeof t=="string"&&t.trim()!==""}function Va(t,e,n,r){let o=typeof t=="function"?t(n):t??e;if(Gt(o))return o;throw new TypeError(
1959
+ `[bvsala] ${we}: cannot determine the FOCUS ${r} for model "${n}". FOCUS allows no placeholder there: pass it in the options.`)}function Zv(t,e,n){if(!n){let s=new Date(t);return {start:Date.UTC(s.getUTCFullYear(),
1955
1960
  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;
1956
1961
  if(!Number.isFinite(o)||!Number.isFinite(i)||o>=i)throw new TypeError(`[bvsala] ${we}: billingPeriod must return valid Dates with start before end`);if(t<o||e>i)throw new TypeError(`[bvsala] ${we}: bi\
1957
- llingPeriod must contain the charge period it is given`);return {start:o,end:i}}function Kv(t,e){if(!e||typeof e!="object")throw new TypeError(`[bvsala] ${we}: options with a billingAccountId are requi\
1962
+ llingPeriod must contain the charge period it is given`);return {start:o,end:i}}function Xv(t,e){if(!e||typeof e!="object")throw new TypeError(`[bvsala] ${we}: options with a billingAccountId are requi\
1958
1963
  red`);let n=Xo(e.granularity,we),r=Qo(e.currency,we),{billingAccountId:o,billingAccountName:i,subAccount:s,tags:a}=e;if(typeof o!="function"&&!Gt(o))throw new TypeError(`[bvsala] ${we}: billingAccount\
1959
- Id must be a non-empty string or a function`);let c=e.serviceName??Wv;if(!Gt(c))throw new TypeError(`[bvsala] ${we}: serviceName must be a non-empty string`);return ei(t,n,we,u=>{let d=typeof o=="func\
1964
+ Id must be a non-empty string or a function`);let c=e.serviceName??Yv;if(!Gt(c))throw new TypeError(`[bvsala] ${we}: serviceName must be a non-empty string`);return ei(t,n,we,u=>{let d=typeof o=="func\
1960
1965
  tion"?o(u):o;if(!Gt(d))throw new TypeError(`[bvsala] ${we}: billingAccountId returned no id for request ${String(u.report.requestId)}`);let p=typeof i=="function"?i(u):i,h=s?s(u):void 0;if(h!==void 0&&
1961
1966
  (!Gt(h?.id)||!Gt(h?.name)))throw new TypeError(`[bvsala] ${we}: subAccount must return { id, name } as non-empty strings, or undefined`);let f=ri(a?a(u):void 0,"tags",we);for(let g of Object.keys(f))if(g.
1962
- startsWith(Lp))throw new TypeError(`[bvsala] ${we}: tag "${g}" uses the reserved "${Lp}" prefix`);let m={id:d,nombre:Gt(p)?p:null,subId:h?h.id:null,subNombre:h?h.name:null,tags:f};return {clave:JSON.stringify(
1963
- [m.id,m.nombre,m.subId,m.subNombre,ni(f)]),extra:m}}).map(u=>{let d=u.modelo,p=Va(e.serviceProviderName,Rp(d),d,"ServiceProviderName"),h=Va(e.invoiceIssuerName,p,d,"InvoiceIssuerName"),f=Va(e.hostProviderName,
1964
- p,d,"HostProviderName"),m=Gv(u.inicio,u.fin,e.billingPeriod),g=ti(u),b=u.extra,y={"bivelio/basis":u.basis,"bivelio/model":d};for(let v of Object.keys(b.tags).sort())y[v]=b.tags[v];return {BilledCost:0,
1967
+ startsWith($p))throw new TypeError(`[bvsala] ${we}: tag "${g}" uses the reserved "${$p}" prefix`);let m={id:d,nombre:Gt(p)?p:null,subId:h?h.id:null,subNombre:h?h.name:null,tags:f};return {clave:JSON.stringify(
1968
+ [m.id,m.nombre,m.subId,m.subNombre,ni(f)]),extra:m}}).map(u=>{let d=u.modelo,p=Va(e.serviceProviderName,_p(d),d,"ServiceProviderName"),h=Va(e.invoiceIssuerName,p,d,"InvoiceIssuerName"),f=Va(e.hostProviderName,
1969
+ p,d,"HostProviderName"),m=Zv(u.inicio,u.fin,e.billingPeriod),g=ti(u),b=u.extra,y={"bivelio/basis":u.basis,"bivelio/model":d};for(let v of Object.keys(b.tags).sort())y[v]=b.tags[v];return {BilledCost:0,
1965
1970
  EffectiveCost:0,ListCost:0,ContractedCost:0,BillingCurrency:r,BillingAccountId:b.id,BillingAccountName:b.nombre,BillingPeriodStart:Et(m.start),BillingPeriodEnd:Et(m.end),ChargePeriodStart:Et(u.inicio),
1966
1971
  ChargePeriodEnd:Et(u.fin),ChargeCategory:"Adjustment",ChargeClass:null,ChargeDescription:`BV-SALA savings ledger for ${d} (basis: ${u.basis}). Not a charge: cost columns are 0 by design.`,ChargeFrequency:"\
1967
1972
  Usage-Based",InvoiceIssuerName:h,ServiceProviderName:p,HostProviderName:f,ServiceName:c,ServiceCategory:"AI and Machine Learning",ServiceSubcategory:"Generative AI",PricingQuantity:null,PricingUnit:null,
@@ -1969,8 +1974,8 @@ SubAccountId:b.subId,SubAccountName:b.subNombre,Tags:JSON.stringify(y),x_BiVelio
1969
1974
  evitadas,x_BiVelioBaselineCost:g.baseline,x_BiVelioActualCost:g.actual,x_BiVelioMeasuredSavings:g.measured,x_BiVelioReferenceSavings:g.reference,x_BiVelioEstimatedSavings:g.estimated,x_BiVelioEliminatedInputFloorCost:g.
1970
1975
  suelo,x_BiVelioBaselineInputTokens:u.tokens.baselineInput,x_BiVelioActualInputTokens:u.tokens.actualInput,x_BiVelioEliminatedInputTokens:u.tokens.eliminatedInput,x_BiVelioCompressedInputTokens:u.tokens.
1971
1976
  compressedInput,x_BiVelioProviderCachedInputTokens:u.tokens.providerCachedInput??null,x_BiVelioBaselineOutputTokens:u.tokens.baselineOutput,x_BiVelioActualOutputTokens:u.tokens.actualOutput,x_BiVelioEliminatedOutputTokens:u.
1972
- tokens.eliminatedOutput}})}var Jv=nn,Yv=Dn,Zv=tn,Xv=X,Qv=de,ey=rn,ty=An,ny=So,ry=gn,oy=xt,iy=Bs,sy=er,ay=Co,cy=js,ly=Xn,uy=mn,dy=yt,py=Vu,fy=Qn,my=kt,hy=Eo,gy=Ft,by=nr,vy=tr,yy=$a,ky=Ro,xy=2592e6,wy=8,Sy=.95,Ey=at,Cy=pt,Ty=Mi,Ry=Li,
1973
- Py=Mr,Iy=Ci,_y=Ti,Dy=jn,Ay=At,Oy=_t,Ly=Dt,My=Nn,$y=Pi,Ny=It,jy=Be,By=Tc,zy=zr,Fy=zn,qy=$c,Uy=sn,Vy=Pt;var FT=Rt,qT=Xt,UT=_n,VT=Rt,HT=Xt,WT=_n;/*! Bundled license information:
1977
+ tokens.eliminatedOutput}})}var Qv=nn,ey=Dn,ty=tn,ny=X,ry=de,oy=rn,iy=An,sy=So,ay=gn,cy=xt,ly=Bs,uy=er,dy=Co,py=js,fy=Xn,my=mn,hy=yt,gy=Vu,by=Qn,vy=kt,yy=Eo,ky=Ft,xy=nr,wy=tr,Sy=$a,Ey=Ro,Cy=2592e6,Ty=8,Ry=.95,Py=at,_y=pt,Iy=Mi,Dy=Li,
1978
+ Ay=Mr,Oy=Ci,Ly=Ti,My=jn,$y=At,Ny=It,jy=Dt,By=Nn,zy=Pi,Fy=_t,qy=Be,Uy=Tc,Vy=zr,Hy=zn,Wy=$c,Gy=sn,Ky=Pt;var HT=Rt,WT=Xt,GT=In,KT=Rt,JT=Xt,YT=In;/*! Bundled license information:
1974
1979
 
1975
1980
  @noble/curves/utils.js:
1976
1981
  @noble/curves/abstract/modular.js:
@@ -1978,4 +1983,4 @@ Py=Mr,Iy=Ci,_y=Ti,Dy=jn,Ay=At,Oy=_t,Ly=Dt,My=Nn,$y=Pi,Ny=It,jy=Be,By=Tc,zy=zr,Fy
1978
1983
  @noble/curves/abstract/edwards.js:
1979
1984
  @noble/curves/ed25519.js:
1980
1985
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
1981
- */export{Dl as AnthropicProvider,Ve as BV_SALA_VERSION,Po as BatchSubmitError,VT as CATALOGO,qi as COMPACTION_TRANSFORMS,lm as COMPACT_ROWS_INSTRUCTION,_e as CalibrationStateError,Gu as DEFAULT_COST_MODEL,yy as DEFAULT_MAX_STALENESS_SECONDS,vm as DEFAULT_MIN_SAVED_CHARS,ny as EMBEDDED_PUBLIC_KEY,pi as ExactTokenizer,Dr as ExecutionRouter,jr as FormatSelector,Hl as GoogleProvider,li as HeuristicEstimator,yc as InMemoryCacheBreakpointStore,Er as InMemoryExactCache,vc as InMemorySemanticCache,Oi as InMemoryToolSetFreezer,$f as LOCAL_EMBEDDING_THRESHOLD,Ke as LicenseError,lk as MODELOS_POR_CODIFICACION,Sr as MODELS_BY_ENCODING,Vi as MockProvider,bl as OpenAICompatibleProvider,WT as PRECIOS_AL_DIA,UT as PRICES_AS_OF,FT as PRICE_CATALOG,Yy as QUALITY_STATUSES,xy as REFERENCE_MAX_AGE_MS,wy as REFERENCE_MESSAGE_ALLOWANCE,Sy as REFERENCE_OUTPUT_SHARE,Ri as ResolverRegistry,ry as RevocationPoller,oy as RevocationSnapshot,Ey as SavingsLedger,Br as SchemaRegistry,Cr as Singleflight,Te as StreamAbortedError,ui as TokenizerRegistry,Lr as ToolSelector,Cy as TraceCollector,gc as UMBRAL_LOCAL,gy as UsageEmitter,Ty as adaptiveK,Uf as arithmeticResolver,ey as buildExactKey,ty as buildInflightKey,Mk as calibrateSemanticFloor,Jv as canonicalize,Ac as compactRowsSerializer,Fc as compactToolOutput,Nc as compresionFiel,iy as computeNextDelay,Iy as cosine,um as createCompactRowsSerializer,kc as createDefaultResolvers,Xy as createHandoff,Qx as createMockProvider,FC as createSavingsLayer,Lc as csvSerializer,Pc as decodeCompactRows,Ry as dedupe,di as defaultTokenizerRegistry,by as deriveSeatId,sy as deriveStatus,vy as detectCi,hc as embebedorLocal,fx as emptyState,sm as encodeCompactRows,$y as evalArithmetic,Ny as evaluatePolicy,Py as executeRetrievalPlan,ay as gateFromKey,en as heuristicEstimator,jv as instrumentSavingsLayer,cy as isKeyset,jy as isStrictCompatible,Rc as jsonCompactSerializer,_y as keyTokensMatch,ly as licenseKeyShape,qT as listPrice,uy as liveGateFromKey,jk as localEmbedding,mx as mergeDelta,Yv as modelFamilyOf,Dy as multisetEqual,Ay as negationCount,Vx as noopCompressor,dy as normalizeLicenseKey,Zv as normalizeText,Oy as numericTokens,HT as precioDeLista,By as projectContext,Nx as providerNativeBackend,es as quitarPrefijoDeProveedor,Vy as randomId,Lv as recordSavingsOnSpan,fi as registerExactTokenizer,uk as registrarTokenizadorExacto,em as renderState,zy as resolveConstraintBackend,ky as resolveDependencies,py as resolveLicense,My as sameAnswer,Zo as savingsSpanAttributes,Xv as sha256,Fy as shouldCompress,Qv as stableStringify,_v as toCsv,Kv as toFocusRows,zv as toLangfuseGeneration,Hv as toSavingsSeries,Uy as uniformColumns,be as validateAgainstSchema,mc as vectorLocal,fy as verifyCompactSignature,my as verifyLicenseToken,hy as verifyRevocationList,qy as withProtectedSpans,Ly as words};
1986
+ */export{Dl as AnthropicProvider,Ve as BV_SALA_VERSION,Po as BatchSubmitError,KT as CATALOGO,qi as COMPACTION_TRANSFORMS,dm as COMPACT_ROWS_INSTRUCTION,Ie as CalibrationStateError,Gu as DEFAULT_COST_MODEL,Sy as DEFAULT_MAX_STALENESS_SECONDS,km as DEFAULT_MIN_SAVED_CHARS,sy as EMBEDDED_PUBLIC_KEY,pi as ExactTokenizer,Dr as ExecutionRouter,jr as FormatSelector,Hl as GoogleProvider,li as HeuristicEstimator,yc as InMemoryCacheBreakpointStore,Er as InMemoryExactCache,vc as InMemorySemanticCache,Oi as InMemoryToolSetFreezer,jf as LOCAL_EMBEDDING_THRESHOLD,Ke as LicenseError,fk as MODELOS_POR_CODIFICACION,Sr as MODELS_BY_ENCODING,Vi as MockProvider,bl as OpenAICompatibleProvider,YT as PRECIOS_AL_DIA,GT as PRICES_AS_OF,HT as PRICE_CATALOG,ek as QUALITY_STATUSES,Cy as REFERENCE_MAX_AGE_MS,Ty as REFERENCE_MESSAGE_ALLOWANCE,Ry as REFERENCE_OUTPUT_SHARE,Ri as ResolverRegistry,ay as RevocationPoller,cy as RevocationSnapshot,Py as SavingsLedger,Br as SchemaRegistry,Cr as Singleflight,Te as StreamAbortedError,ui as TokenizerRegistry,Lr as ToolSelector,_y as TraceCollector,gc as UMBRAL_LOCAL,ky as UsageEmitter,Iy as adaptiveK,Hf as arithmeticResolver,oy as buildExactKey,iy as buildInflightKey,Bk as calibrateSemanticFloor,Qv as canonicalize,Ac as compactRowsSerializer,Fc as compactToolOutput,Nc as compresionFiel,ly as computeNextDelay,Oy as cosine,pm as createCompactRowsSerializer,kc as createDefaultResolvers,nk as createHandoff,rw as createMockProvider,HC as createSavingsLayer,Lc as csvSerializer,Pc as decodeCompactRows,Dy as dedupe,di as defaultTokenizerRegistry,xy as deriveSeatId,uy as deriveStatus,wy as detectCi,hc as embebedorLocal,bx as emptyState,cm as encodeCompactRows,zy as evalArithmetic,Fy as evaluatePolicy,Ay as executeRetrievalPlan,dy as gateFromKey,en as heuristicEstimator,qv as instrumentSavingsLayer,py as isKeyset,qy as isStrictCompatible,Rc as jsonCompactSerializer,Ly as keyTokensMatch,fy as licenseKeyShape,WT as listPrice,my as liveGateFromKey,qk as localEmbedding,vx as mergeDelta,ey as modelFamilyOf,My as multisetEqual,$y as negationCount,Kx as noopCompressor,hy as normalizeLicenseKey,ty as normalizeText,Ny as numericTokens,JT as precioDeLista,Uy as projectContext,Fx as providerNativeBackend,es as quitarPrefijoDeProveedor,Ky as randomId,jv as recordSavingsOnSpan,fi as registerExactTokenizer,mk as registrarTokenizadorExacto,nm as renderState,Vy as resolveConstraintBackend,Ey as resolveDependencies,gy as resolveLicense,By as sameAnswer,Zo as savingsSpanAttributes,ny as sha256,Hy as shouldCompress,ry as stableStringify,Lv as toCsv,Xv as toFocusRows,Vv as toLangfuseGeneration,Jv as toSavingsSeries,Gy as uniformColumns,be as validateAgainstSchema,mc as vectorLocal,by as verifyCompactSignature,vy as verifyLicenseToken,yy as verifyRevocationList,Wy as withProtectedSpans,jy as words};