@bivelio/savings-layer 0.4.3 → 0.4.4
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/gateway/bin.js +92 -5
- package/dist/index.d.ts +35 -2
- package/dist/index.js +774 -20
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -1,24 +1,687 @@
|
|
|
1
|
-
var zs="2026-08-24",sn={"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},"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,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},"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},"gpt-5.1-codex-max":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gpt-5.1-codex-mini":{inputPer1k:25e-5,outputPer1k:.002,cachedInputPer1k:25e-6},"gpt-5.1-thinking":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gpt-5.2":{inputPer1k:.00175,outputPer1k:.014,cachedInputPer1k:175e-6},"gpt-5.2-codex":{inputPer1k:.00175,outputPer1k:.014,cachedInputPer1k:175e-6},"gpt-5.3-codex":{inputPer1k:.00175,outputPer1k:.014,cachedInputPer1k:175e-6},"gpt-5.4":{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},"gpt-5.4-mini":{inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:75e-6},"gpt-5.4-nano":{inputPer1k:2e-4,outputPer1k:.00125,cachedInputPer1k:2e-5},"gpt-5.5":{inputPer1k:.005,outputPer1k:.03,cachedInputPer1k:5e-4},"gpt-5.6-luna":{inputPer1k:2e-4,outputPer1k:.0012,cachedInputPer1k:2e-5},"gpt-5.6-sol":{inputPer1k:.004,outputPer1k:.02,cachedInputPer1k:4e-4},"gpt-5.6-terra":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"claude-opus-4-5":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4-6":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4-7":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4-8":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-5":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"claude-sonnet-4-5":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-4-6":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-5":{inputPer1k:.002,outputPer1k:.01,cachedInputPer1k:2e-4},"claude-fable-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-sonnet-4":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-haiku-4-5":{inputPer1k:.001,outputPer1k:.005,cachedInputPer1k:1e-4},"claude-3-5-sonnet":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-3-5-haiku":{inputPer1k:8e-4,outputPer1k:.004,cachedInputPer1k:8e-5},"claude-3-opus":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"claude-3-haiku":{inputPer1k:25e-5,outputPer1k:.00125,cachedInputPer1k:3e-5},"gemini-3.7-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5},"gemini-3.1-pro-preview":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}};function an(t,e,n){if(!n)return;let r=t[n];if(r)return r;let o=n.lastIndexOf("/"),s=o>=0?n.slice(o+1):n,i=t[s];if(i)return i;for(let a of e)if(s.startsWith(a)){let c=s.charAt(a.length);if(c===""||c==="-"||c==="."||c==="_")return t[a]}}function cn(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var Vs=cn(sn);function mt(t){return an(sn,Vs,t)}var Us=0;function ln(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++Us,o=Date.now?Date.now():0;for(let s=0;s<16;s++)e[s]=(s<6?r>>>s*8:o>>>(s-6)*8)&255;}e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=[];for(let r=0;r<16;r++)n.push(e[r].toString(16).padStart(2,"0"));return `${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}-${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var Dc=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function Pc(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 un=class{id;exact=false;constructor(e="heuristic"){this.id=e;}count(e){if(e.length===0)return 0;let n=e.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],r=0;for(let o of n){let s=o[0];if(/\s/.test(s)){let i=(o.match(/\n/g)??[]).length;r+=i+Math.floor(Math.max(0,o.length-1)/2);}else /[A-Za-z]/.test(s)?r+=Math.max(1,Math.ceil(o.length/4)):/\d/.test(s)?r+=Math.max(1,Math.ceil(o.length/2)):r+=1;}return Math.max(r,Math.ceil(e.length/4))}},je=new un;var dn=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=je){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){return this.modelToTokenizer.set(e,n),this}resolve(e){let n=e.tokenizer?this.estimators.get(e.tokenizer):void 0;if(n)return n;if(e.model){let r=this.modelToTokenizer.get(e.model);if(r){let o=this.estimators.get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},Rr=new dn;var pn=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}},Cr={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","o1","o1-mini","o3","o3-mini","o4-mini"],cl100k_base:["gpt-4","gpt-4-turbo","gpt-3.5-turbo","text-embedding-3-small","text-embedding-3-large"]};async function qs(t,e={}){let n=e.codificaciones??["o200k_base","cl100k_base"],r=false;for(let o of n){let s;try{s=await import(`gpt-tokenizer/encoding/${o}`);}catch{continue}if(typeof s.encode=="function"){t.register(new pn(o,s)),r=true;for(let i of Cr[o]??[])t.mapModel(i,o),t.mapModel(`openai/${i}`,o);}}return r}var zc=Cr,Vc=qs;var Ne=class{avoidedLlm=0;baselineLlm=1;actualLlm=0;baselineRetrieval=0;actualRetrieval=0;baselineTools=0;actualTools=0;retries=0;baselineInput=0;actualInput=0;eliminatedInput=0;compressedInput=0;baselineOutput=0;actualOutput=0;eliminatedOutput=0;providerCachedInput=0;sentInputLocal=0;removedInputLocal=0;estimatorExact=false;repairOutput=0;repairInput=0;discoveryInput=0;discoveryOutput=0;extraCostUsd=0;cascadeInput=0;cascadeOutput=0;cascadeAttempt(e,n){this.cascadeInput+=Math.max(0,e.inputTokens),this.cascadeOutput+=Math.max(0,e.outputTokens),this.extraCostUsd+=Math.max(0,e.inputTokens)/1e3*n.inputPer1k+Math.max(0,e.outputTokens)/1e3*n.outputPer1k;}compressionReport=void 0;eliminate(e){this.eliminatedInput+=Math.max(0,e);}compress(e,n){this.compressedInput+=Math.max(0,e-n);}providerCached(e){this.providerCachedInput+=Math.max(0,e);}avoidCall(e,n){this.avoidedLlm+=1,this.actualLlm=0,this.baselineInput=e,this.baselineOutput=n;}get publishedBaselineOutput(){return this.avoidedLlm===0?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):this.baselineOutput}estimateCost(e){let n=this.avoidedLlm===0,r="estimated";if(n)if(this.actualInput>0&&this.sentInputLocal>0){let d=this.actualInput/this.sentInputLocal,p=Math.max(0,this.actualInput-this.repairInput-this.discoveryInput);this.baselineInput=p+Math.round(d*this.removedInputLocal),r=this.removedInputLocal===0?"measured":"estimated";}else this.actualInput>0?(this.baselineInput=this.actualInput,r="measured"):(this.baselineInput=0,r="unmeasured");let o=n?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):this.baselineOutput,s=e.cachedInputPer1k??e.inputPer1k,i=Math.min(this.providerCachedInput,this.actualInput),a=d=>Math.max(0,d-i)/1e3*e.inputPer1k+i/1e3*s,c=a(this.baselineInput)+o/1e3*e.outputPer1k,l=a(this.actualInput)+this.actualOutput/1e3*e.outputPer1k+this.extraCostUsd,u=c===0?0:1-l/c;return {baselineEstimate:Ir(c),actual:Ir(l),netSavings:Hs(u),basis:r}}};function Ir(t){return Math.round(t*1e10)/1e10}function Hs(t){return Math.round(t*1e6)/1e6}var Ks=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Js=new TextEncoder;function se(t,e){return t>>>e|t<<32-e}function Or(t){let e=Js.encode(t),n=e.length*8,r=(e.length+8>>6)+1,o=new Uint8Array(r*64);o.set(e),o[e.length]=128;let s=new DataView(o.buffer);s.setUint32(o.length-8,Math.floor(n/4294967296)),s.setUint32(o.length-4,n>>>0);let i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let l=0;l<o.length;l+=64){for(let b=0;b<16;b++)a[b]=s.getUint32(l+b*4);for(let b=16;b<64;b++){let y=a[b-15],E=a[b-2],C=se(y,7)^se(y,18)^y>>>3,O=se(E,17)^se(E,19)^E>>>10;a[b]=a[b-16]+C+a[b-7]+O|0;}let u=i[0],d=i[1],p=i[2],f=i[3],m=i[4],g=i[5],h=i[6],x=i[7];for(let b=0;b<64;b++){let y=se(m,6)^se(m,11)^se(m,25),E=m&g^~m&h,C=x+y+E+Ks[b]+a[b]|0,O=se(u,2)^se(u,13)^se(u,22),T=u&d^u&p^d&p,D=O+T|0;x=h,h=g,g=m,m=f+C|0,f=p,p=d,d=u,u=C+D|0;}i[0]=i[0]+u|0,i[1]=i[1]+d|0,i[2]=i[2]+p|0,i[3]=i[3]+f|0,i[4]=i[4]+m|0,i[5]=i[5]+g|0,i[6]=i[6]+h|0,i[7]=i[7]+x|0;}let c="";for(let l=0;l<8;l++)c+=(i[l]>>>0).toString(16).padStart(8,"0");return c}var Gs=/\s+/g,Ws=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],Ys=/[¿?¡!;.,:'"·•]/g,Zs=/([a-z])\p{M}+/gu,Xs=/(^|\s)\p{M}+/gu,fn=/\p{L}/u;function Y(t){return t>="0"&&t<="9"}function ht(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,r]of Ws)e=e.replace(n,r);return e=e.normalize("NFD").replace(Zs,"$1").replace(Xs,"$1").normalize("NFC"),e=e.replace(Ys,(n,r,o)=>{let s=o[r-1]??"",i=o[r+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return Y(s)&&Y(i)?n:"";case "!":return Y(s)?n:"";case ".":case ",":return Y(s)&&Y(i)||Y(i)&&!Y(s)&&!fn.test(s)?n:"";case ":":return Y(s)&&Y(i)?n:"";case "'":case '"':return fn.test(s)&&fn.test(i)||Y(s)||Y(i)?n:"";default:return Y(s)||Y(i)?n:""}}),e.replace(Gs," ").trim()}function ie(t){return Or(t)}function Se(t){return JSON.stringify(mn(t))}function mn(t){if(Array.isArray(t))return t.map(mn);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=mn(t[n]);return e}return t}function hn(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function gn(t){let e=t.context??{},n=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(`
|
|
2
|
-
|
|
3
|
-
`),o=(t.tools??[]).map(s=>({id:s.id,risk:s.risk,parameters:s.parameters??null})).sort((s,i)=>s.id.localeCompare(i.id));return {model:t.model,modelFamily:hn(t.model),messages:t.messages,normalizedText:r,systemPromptHash:ie(n),toolsetHash:ie(Se(o)),structuredDataHash:t.structuredData!==void 0?ie(Se(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.contractId??"none",contractId:t.response?.contractId??null,temperature:t.temperature??null,seed:t.seed??null,tenantId:e.tenantId??"anonymous",authorizationScope:e.authorizationScope??"default",principal:e.sessionId??null,locale:e.locale??"und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var _r="n2";function bn(t,e={}){let n=e.servedModel??t.model,r=Se({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily:hn(n),model:n,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,data:t.structuredDataHash,locale:t.locale,temperature:t.temperature,seed:t.seed,knowledgeEpoch:t.knowledgeEpoch,freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${_r}:${ie(r)}`}function Dr(t,e={}){let n=Se({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,model:e.servedModel??t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,data:t.structuredDataHash,temperature:t.temperature,seed:t.seed,deferrable:e.deferrable===true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:inflight:${_r}:${ie(n)}`}var Qs=new RegExp("\\b("+["now|today|current|currently|latest|live|price|prices|stock|availability|weather|score|breaking","ahora|hoy|actual|actualmente|ultimo|\xFAltimo|precio|precios|disponibilidad|cotizacion|cotizaci\xF3n","ara|avui|preu|preus|disponibilitat|darrer","maintenant|aujourd'hui|actuel|actuelle|dernier|prix|disponibilite|disponibilit\xE9|meteo|m\xE9t\xE9o","jetzt|heute|aktuell|aktuelle|neueste|preis|preise|verfugbarkeit|verf\xFCgbarkeit|wetter|kurs","adesso|oggi|attuale|ultimo|prezzo|prezzi|disponibilita|disponibilit\xE0|meteo","agora|hoje|atual|ultimo|\xFAltimo|preco|pre\xE7o|precos|pre\xE7os|disponibilidade|cotacao|cota\xE7\xE3o","nu|vandaag|huidige|laatste|prijs|prijzen|beschikbaarheid|weer|koers","teraz|dzisiaj|dzis|dzi\u015B|aktualny|aktualna|najnowszy|cena|ceny|dostepnosc|dost\u0119pno\u015B\u0107|pogoda","simdi|\u015Fimdi|bugun|bug\xFCn|guncel|g\xFCncel|son|fiyat|fiyatlar|stok|hava","sekarang|hari ini|terkini|terbaru|harga|ketersediaan|cuaca","bay gio|b\xE2y gi\u1EDD|hom nay|h\xF4m nay|hien tai|hi\u1EC7n t\u1EA1i|moi nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),ei=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nuestro|nuestra|cuenta|factura|pedido|saldo|suscripcion|suscripci\xF3n|perfil","meu|meva|nostre|compte|factura|comanda|saldo|subscripcio|subscripci\xF3|perfil","mon|ma|mes|notre|nos|compte|solde|facture|commande|abonnement|profil","mein|meine|meinem|unser|unsere|konto|kontostand|saldo|rechnung|bestellung|abo|abonnement|profil","mio|mia|miei|nostro|nostra|conto|saldo|fattura|ordine|abbonamento|profilo","meu|minha|meus|nosso|nossa|conta|saldo|fatura|pedido|assinatura|perfil","mijn|onze|ons|rekening|saldo|factuur|bestelling|abonnement|profiel","moj|m\xF3j|moja|moje|nasz|nasza|konto|saldo|faktura|zamowienie|zam\xF3wienie|subskrypcja|profil","benim|bizim|hesap|hesabim|hesab\u0131m|bakiye|fatura|siparis|sipari\u015F|abonelik|profil","saya|kami|akun|saldo|tagihan|pesanan|langganan|profil","cua toi|c\u1EE7a t\xF4i|tai khoan|t\xE0i kho\u1EA3n|so du|s\u1ED1 d\u01B0|hoa don|h\xF3a \u0111\u01A1n|don hang|\u0111\u01A1n h\xE0ng|thue bao|thu\xEA bao"].join("|")+")\\b","i");function xn(t){let e=[],n=t.normalizedText,r=(t.original.tools??[]).some(p=>p.risk==="write"||p.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||Qs.test(n),s=ei.test(n),i=(t.temperature??0)>.3&&t.seed==null;r&&e.push("write/destructive tools present"),o&&e.push("freshness-sensitive request"),s&&e.push("personalized/account-scoped request"),i&&e.push("stochastic sampling (temp>0.3, no seed)");let a=o&&(t.freshnessBucket==null||t.freshnessBucket==="any"),c=t.freshnessBucket==="live",l=s&&t.principal==null,u=!i&&!a&&!c&&!l&&!r;r&&e.push("write/destructive tools \u2192 exact cache off (side effects must execute)"),c&&e.push("freshnessBucket=live \u2192 exact cache off (answer must be current)"),a&&e.push("freshness-sensitive without a freshness bucket \u2192 exact cache off"),l&&e.push("personalized request with no principal (context.sessionId) \u2192 exact cache off");let d=!r&&!o&&!s&&!i&&t.freshnessBucket!=="day";return {allowExactCache:u,allowSemanticCache:d,allowSingleflight:!r&&!l,allowCompression:true,requiresFreshData:o,hasSideEffects:r,isPersonalized:s,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var gt=class{store=new Map;maxEntries;now;constructor(e={}){this.maxEntries=e.maxEntries??1e4,this.now=e.now??(()=>Date.now());}async get(e){let n=this.store.get(e);return n?n.expiresAtMs!==null&&this.now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),n.value):null}async set(e,n,r){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let o=this.store.keys().next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:n,expiresAtMs:r!=null?this.now()+r:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};var bt=class{inflight=new Map;waiters=new Map;async run(e,n){let r=this.inflight.get(e);if(r)return this.waiters.set(e,(this.waiters.get(e)??1)+1),{value:await r,coalesced:true};let o=(async()=>n())();this.inflight.set(e,o),this.waiters.set(e,1);try{return {value:await o,coalesced:!1}}finally{this.inflight.delete(e),this.waiters.delete(e);}}get activeKeys(){return this.inflight.size}};function ti(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 ni(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(Boolean)}function ri(t){let e=new Array(256).fill(0),n=ni(t);if(n.length===0)return e;let r=new Map;for(let s=0;s<n.length;s++){let i=n[s];if(r.set(i,(r.get(i)??0)+1),s+1<n.length){let a=`${i}\0${n[s+1]}`;r.set(a,(r.get(a)??0)+1);}}for(let[s,i]of r){let a=ti(s),c=a%256,l=a>>>31===1?-1:1;e[c]+=l*(1+Math.log(i));}let o=0;for(let s of e)o+=s*s;if(o=Math.sqrt(o),o===0)return e;for(let s=0;s<e.length;s++)e[s]/=o;return e}function Ar(t){return ri(t)}var Pr=.72;function oi(t,e){let n=Math.min(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i++){let a=t[i],c=e[i];r+=a*c,o+=a*a,s+=c*c;}return o===0||s===0?0:r/(Math.sqrt(o)*Math.sqrt(s))}var si=new Set(["no","not","never","none","cannot","cant","without","nor","nt","isnt","arent","wasnt","werent","dont","doesnt","didnt","wont","cant","shouldnt"]),ii=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what","whats","which","who","whom","how","when","where","me","my","i","you","please","tell","give","show","find","do","does","did","be","that","this","it","with","as","at","by","from","about","into","over","than","then","s","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","estas","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","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","aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function Lr(t){return (t.match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function ai(t,e){if(t.length!==e.length)return false;let n=new Map;for(let r of t)n.set(r,(n.get(r)??0)+1);for(let r of e){let o=n.get(r);if(!o)return false;n.set(r,o-1);}return true}function Mr(t){return t.split(/\s+/).filter(Boolean)}function Br(t){return t.filter(e=>si.has(e.replace(/'/g,""))||e.endsWith("n't")).length}function ci(t,e){if(!ai(Lr(t),Lr(e)))return false;let n=Mr(t),r=Mr(e);if(Br(n)!==Br(r))return false;let o=l=>l.length>1&&!ii.has(l)&&!/^\d/.test(l),s=new Set(n.filter(o)),i=new Set(r.filter(o));if(s.size===0&&i.size===0)return true;let a=0;for(let l of s)i.has(l)&&a++;let c=s.size+i.size-a;return c===0?true:a/c>=.75}var jr=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;constructor(e={}){let n=e.embed==null;this.embed=e.embed??Ar,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??(n?Pr:.9),this.acceptThreshold=e.acceptThreshold??.85,this.ttlMs=e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now());}async find(e){if(this.records.length===0)return null;let n=await this.embed(e.normalizedText),r=null;for(let o of this.records){if(o.tenantId!==e.tenantId||o.authorizationScope!==e.authorizationScope||o.principal!==e.principal||o.knowledgeEpoch!==e.knowledgeEpoch||o.contractId!==e.contractId||o.model!==e.model||o.systemPromptHash!==e.systemPromptHash||o.structuredDataHash!==e.structuredDataHash||o.locale!==e.locale||o.schemaVersion!==e.schemaVersion||o.safetyPolicyVersion!==e.safetyPolicyVersion||this.ttlMs!=null&&this.now()-o.storedAtMs>this.ttlMs)continue;let s=oi(n,o.embedding);if(s<this.similarityThreshold||!ci(e.normalizedText,o.query))continue;let i=this.verify?await this.verify(e.normalizedText,o.query):s,a=Math.min(s,i);a<this.acceptThreshold||(!r||a>r.confidence)&&(r={record:o,similarity:s,verifierScore:i,confidence:a,ageMs:this.now()-o.storedAtMs});}return r}async store(e,n){let r=await this.embed(e.normalizedText);this.records.length>=this.maxRecords&&this.records.shift(),this.records.push({embedding:r,query:e.normalizedText,answer:n,tenantId:e.tenantId,authorizationScope:e.authorizationScope,principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.structuredDataHash,locale:e.locale,schemaVersion:e.schemaVersion,safetyPolicyVersion:e.safetyPolicyVersion,storedAtMs:this.now()});}invalidateEpoch(e){let n=0;for(let r=this.records.length-1;r>=0;r--)this.records[r].knowledgeEpoch===e&&(this.records.splice(r,1),n++);return n}get size(){return this.records.length}};var yn=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}},li={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]??ui(t.normalizedText))?.trim();if(!n)return null;let r=pi(n);return r===null||!Number.isFinite(r)?null:{text:di(r),data:{value:r},resolver:"arithmetic"}}};function ui(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function di(t){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,"*":2,"/":2,"%":2},s=a=>{let c=n.pop(),l=n.pop();if(l===void 0||c===void 0)return false;switch(a){case "+":return n.push(l+c),true;case "-":return n.push(l-c),true;case "*":return n.push(l*c),true;case "/":return c===0?false:(n.push(l/c),true);case "%":return c===0?false:(n.push(l%c),true);default:return false}},i=true;for(let a of e)if(/^\d/.test(a))n.push(Number(a)),i=false;else if(a==="(")r.push(a),i=true;else if(a===")"){for(;r.length&&r[r.length-1]!=="(";)if(!s(r.pop()))return null;if(r.pop()!=="(")return null;i=false;}else {if(i)return null;for(;r.length&&r[r.length-1]!=="("&&o[r[r.length-1]]>=o[a];)if(!s(r.pop()))return null;r.push(a),i=true;}for(;r.length;){let a=r.pop();if(a==="("||!s(a))return null}return n.length===1?n[0]:null}function Nr(){return new yn().register(li)}var fi=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,$r=/\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,mi=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,xt=class{classifier;maxRounds;constructor(e={}){this.classifier=e.classifier,this.maxRounds=e.maxRounds??2;}classify(e){let n=e.original.retrieval?.mode,r=e.normalizedText;if((e.original.tools??[]).some(i=>i.risk==="write"||i.risk==="destructive")&&/\b(create|update|delete|send|pay|book|cancel|crea|actualiza|elimina|env[ií]a|paga)\b/i.test(r))return fe("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return fe("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(mi.test(r)&&!$r.test(r))return fe("NO_RETRIEVAL",.8,"self-contained transformation",0);let s=this.classifier?.classify(r);return s&&s.confidence>=.75?fe(s.executionClass,s.confidence,"local classifier",hi(s.executionClass,this.maxRounds)):n==="single"?fe("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?fe("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):fi.test(r)?fe("MULTI_HOP_RETRIEVAL",.7,"comparison/compound question",Math.min(this.maxRounds,2)):$r.test(r)?fe("SINGLE_RETRIEVAL",.65,"single factual lookup",1):fe("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function hi(t,e){return t==="SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function fe(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var yt=class{maxTools;scoreIntentMatch;constructor(e={}){this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??gi;}passthrough(e){if(!e||e.length===0)return {tools:[],droppedIds:[],reason:"no tools provided",setIsStable:true};let n=e.slice(0,this.maxTools),r=e.slice(this.maxTools).map(o=>o.id);return {tools:n,droppedIds:r,reason:`router off: caller tools passed through unfiltered (${n.length}/${e.length}, capped at maxTools=${this.maxTools}; risk gating is the caller's responsibility while routing is off)`,setIsStable:true}}select(e,n,r){if(!n||n.length===0)return {tools:[],droppedIds:[],reason:"no tools provided",setIsStable:true};let o=r==="TOOL_ACTION",a=n.filter(u=>o||u.risk==="read").map(u=>({tool:u,score:this.scoreIntentMatch(e,u)})).filter(u=>u.score>0).sort((u,d)=>d.score-u.score).slice(0,this.maxTools).map(u=>u.tool).sort((u,d)=>u.id<d.id?-1:u.id>d.id?1:0),c=new Set(a.map(u=>u.id)),l=n.filter(u=>!c.has(u.id)).map(u=>u.id);return {tools:a,droppedIds:l,reason:`selected ${a.length}/${n.length} by intent match (writes ${o?"allowed":"blocked"})`,setIsStable:l.length===0}}};function gi(t,e){let n=ht(t),r=0;for(let o of e.intents){let s=ht(o);s&&(n.includes(s)?r+=2:s.split(/\s+/).some(i=>i.length>3&&n.includes(i))&&(r+=1));}return r}function bi(t){let e=new Set,n=[];for(let r of t){let o=r.hash??yi(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function xi(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((i,a)=>(a.score??0)-(i.score??0));if(r.length<=n)return r;let o=r[0]?.score??0;if(o<=0)return r.slice(0,e.maxDocuments);let s=[];for(let i of r){let a=(i.score??0)/o;if(s.length<n||a>=.4&&s.length<e.maxDocuments)s.push(i);else break}return s}async function Fr(t,e){if(t.execution==="NO_RETRIEVAL"||t.execution==="TOOL_ACTION"||t.execution==="NON_CACHEABLE"||!e.retriever)return {docs:[],rounds:0,retrievedCount:0,keptCount:0};let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,r=[];for(let i=0;i<n;i++){let a=await e.retriever.retrieve(t.query,t.maxDocuments*2);r.push(...a);}let o=r.length;r=bi(r),e.reranker&&(r=await e.reranker.rerank(t.query,r));let s=xi(r,{maxDocuments:t.maxDocuments});return {docs:s,rounds:n,retrievedCount:o,keptCount:s.length}}function yi(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function Ol(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function _l(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&Si(o)?Object.assign(n.userPreferences,o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let s=ki(n,r);s?s.push(...o.map(String)):n.confirmedFacts[r]=o;}for(let r of e.remove??[])delete n.confirmedFacts[r],delete n.userPreferences[r],wi(n,r);return n}function Dl(t){let e=t.rawTurns??3,n=[],r=vi(t.state);r&&n.push({role:"system",content:`Conversation state:
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
`+JSON.stringify(t)}var co=4,Fe="bvsala_contract",lo=class{id;opts;fetchImpl;constructor(e={}){this.opts=e,this.id=`anthropic:${e.baseUrl??"https://api.anthropic.com/v1"}`,this.fetchImpl=e.fetchImpl??fetch;}async generate(e){let n=this.construirCuerpo(e),r=(this.opts.baseUrl??"https://api.anthropic.com/v1").replace(/\/$/,""),o=await this.fetchImpl(`${r}/messages`,{method:"POST",headers:{"content-type":"application/json","anthropic-version":this.opts.apiVersion??"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},body:JSON.stringify(n.body)});if(!o.ok)throw new Error(`provider ${o.status}: ${await Hi(o)}`);return this.leer(o,e,n.contratoNativo)}construirCuerpo(e){let{system:n,messages:r,prefijoEnMensajes:o,prefijoEnSystem:s}=Ui(e);if(r.length===0)throw new Error("anthropic: the request has no user/assistant message. The Messages API needs at least one, and system prompts travel in the `system` field \u2014 they do not count.");let i=(e.tools??[]).map(u=>({name:u.id,...u.description?{description:u.description}:{},input_schema:u.parameters??{type:"object",properties:{}}})),a=false,c=false;if(e.schema){let u=i.length>0,d=i.some(f=>f.name===Fe),p=De(e.schema);d?(n.push({type:"text",text:ao(e.schema)}),W("anthropic-contrato-nombre-ocupado",`[bvsala] One of your tools is already named \`${Fe}\`, so the output contract cannot travel as a tool without colliding with it (duplicate tool names are a provider error). The schema is sent as prompt text instead, which is measurably more expensive on this API. Rename that tool to get the cheaper path.`)):(!p&&!u&&W("anthropic-strict-incompatible","[bvsala] El contrato de respuesta no cumple el modo `strict` (en strict, `required` debe listar TODAS las claves de `properties`, y todo objeto necesita `additionalProperties: false`). Se env\xEDa el esquema sin `strict`: el modelo sigue guiado y el layer sigue validando, pero la garant\xEDa la da el layer, no el proveedor."),a=p&&!u,i.push({name:Fe,description:u?"Return the final answer in the required shape. Use the other tools first if you need data; call this one instead of writing the answer as text.":"Return the final answer in the required shape.",input_schema:e.schema,...a?{strict:true}:{}}),u&&(c=this.opts.forceAnswerThroughTool!==false,W("anthropic-contrato-con-herramientas","[bvsala] This request carries BOTH your tools and an output contract. On Anthropic's Messages API a specific shape is only GUARANTEED by forcing that exact tool, and forcing ours would leave the model unable to call yours. The contract travels as one extra tool"+(c?' and the request is sent with `tool_choice: {type: "any"}`, so the model must answer through SOME tool \u2014 yours or the contract \u2014 and can no longer reply in prose. Your tool turn is untouched. The guarantee is still the layer\'s, not the provider\'s (`constraints.backend: "none"`), because the model may pick one of your tools and defer the final answer to the next turn.':", not forced (`forceAnswerThroughTool: false`). The guarantee is the layer's, not the provider's (`constraints.backend: \"none\"`), and if the model answers in prose the layer pays a second full call to repair it \u2014 on this API that second call re-pays the whole tool-use overhead.")+" Dropping either the tools or the contract from this request is what makes the guarantee free.")));}let l={model:e.model,max_tokens:e.maxOutputTokens??this.opts.defaultMaxOutputTokens??4096,messages:r};return n.length>0&&(l.system=n),e.temperature!=null&&(l.temperature=e.temperature),i.length>0&&(l.tools=i),a?l.tool_choice={type:"tool",name:Fe}:c&&(l.tool_choice={type:"any"}),e.deferrable===true&&W("anthropic-sin-tier-diferible","[bvsala] Esta petici\xF3n se declar\xF3 diferible, pero la API de Mensajes de Anthropic NO tiene un tier s\xEDncrono m\xE1s barato: su `service_tier` elige entre capacidad prioritaria (m\xE1s cara) y est\xE1ndar, no un flex. La petici\xF3n sale sin cambios y el informe no acredita ning\xFAn descuento. El 50% por diferir existe en la Message Batches API, que es as\xEDncrona y no cabe en una llamada de petici\xF3n/respuesta."),this.marcarCache(e,n,r,o,s),{body:l,contratoNativo:a}}marcarCache(e,n,r,o,s){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return;let i=Math.min(this.opts.maxCacheBreakpoints??co,co);if(i<=0)return;let a=s>0?n[s-1]:void 0;if(a&&(a.cache_control={type:"ephemeral"},i-=1),i>0&&o>0){let c=r[Math.min(o,r.length)-1],l=c?.content[c.content.length-1];l&&(l.cache_control={type:"ephemeral"});}}async leer(e,n,r){let o=await e.json(),s=o.content??[],i=s.filter(b=>b.type==="text").map(b=>b.text??"").join(""),a=s.filter(b=>b.type==="tool_use"&&b.name!==Fe).map(b=>({...b.id?{id:b.id}:{},name:b.name??"",arguments:JSON.stringify(b.input??{})})).filter(b=>b.name!==""),c=s.find(b=>b.type==="tool_use"&&b.name===Fe),l=c?JSON.stringify(c.input??{}):i,u=o.usage??{},d=u.cache_read_input_tokens,p=u.cache_creation_input_tokens,f=(u.input_tokens??0)+(p??0)+(d??0),m=u.output_tokens??0,g=typeof u.input_tokens!="number",h=typeof u.output_tokens!="number";if(this.opts.requireUsage&&(g||h))throw new Error(`provider returned incomplete usage (input=${u.input_tokens??"absent"}, output=${u.output_tokens??"absent"}); cannot measure cost.`);let x=typeof u.service_tier=="string"&&u.service_tier!==""?u.service_tier:void 0;return {text:l,...a.length>0?{toolCalls:a}:{},...o.stop_reason?{finishReason:qi(o.stop_reason)}:{},...x?{servedServiceTier:x}:{},usage:{inputTokens:f,outputTokens:m,...d!=null?{cachedInputTokens:d}:{},...p!=null?{cacheWriteInputTokens:p}:{}},structuredNatively:n.schema!=null&&r,raw:o}}};function Ui(t){let e=[],n=[],r=t.stablePrefixMessages??0,o=0,s=0,i=true;return t.messages.forEach((a,c)=>{if(a.role==="system"&&i){e.push({type:"text",text:a.content}),c<r&&(s=e.length);return}i=false,n.push({role:a.role==="assistant"?"assistant":"user",content:[{type:"text",text:a.content}]}),c<r&&(o=n.length);}),n.length>0&&n[0].role==="assistant"&&(n.unshift({role:"user",content:[{type:"text",text:"(continue)"}]}),o>0&&(o+=1)),{system:e,messages:n,prefijoEnMensajes:o,prefijoEnSystem:s}}function qi(t){switch(t){case "end_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "tool_calls";case "refusal":return "content_filter";default:return t}}async function Hi(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}var et=class{events=[];start;now;constructor(e=()=>Date.now()){this.now=e,this.start=e();}record(e,n,r){this.events.push({stage:e,outcome:n,...r?{detail:r}:{},atMs:this.now()-this.start});}elapsed(){return this.now()-this.start}all(){return this.events}};var Ae=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function In(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Ct(t,e=""){if(typeof t!="number"){let n=e&&`"${e}" `;throw new TypeError(`${n}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let n=e&&`"${e}" `;throw new RangeError(`${n}expected integer >= 0, got ${t}`)}}function ne(t,e,n=""){let r=In(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){let i=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return t}function On(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 po(t,e){ne(t,void 0,"digestInto() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function tt(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function It(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var fo=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ki=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ot(t){if(ne(t),fo)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Ki[t[n]];return e}var me={_0:48,_9:57,A:65,F:70,a:97,f:102};function uo(t){if(t>=me._0&&t<=me._9)return t-me._0;if(t>=me.A&&t<=me.F)return t-(me.A-10);if(t>=me.a&&t<=me.f)return t-(me.a-10)}function nt(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(fo)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){let i=uo(t.charCodeAt(s)),a=uo(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a;}return r}function _n(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];ne(o),e+=o.length;}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let s=t[r];n.set(s,o),o+=s.length;}return n}function mo(t,e={}){let n=(o,s)=>t(s).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function ho(t=32){Ct(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var go=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var _t=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(e,n,r,o){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=It(this.buffer);}update(e){On(this),ne(e);let{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=It(e);for(;o<=s-i;i+=o)this.process(c,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){On(this),po(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;n[i++]=128,tt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let d=i;d<o;d++)n[d]=0;r.setBigUint64(o-8,BigInt(this.length*8),s),this.process(r,0);let a=It(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("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s);}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};var H=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Dt=BigInt(4294967295),bo=BigInt(32);function Ji(t,e=false){return e?{h:Number(t&Dt),l:Number(t>>bo&Dt)}:{h:Number(t>>bo&Dt)|0,l:Number(t&Dt)|0}}function xo(t,e=false){let n=t.length,r=new Uint32Array(n),o=new Uint32Array(n);for(let s=0;s<n;s++){let{h:i,l:a}=Ji(t[s],e);[r[s],o[s]]=[i,a];}return [r,o]}var Dn=(t,e,n)=>t>>>n,An=(t,e,n)=>t<<32-n|e>>>n,Pe=(t,e,n)=>t>>>n|e<<32-n,Le=(t,e,n)=>t<<32-n|e>>>n,rt=(t,e,n)=>t<<64-n|e>>>n-32,ot=(t,e,n)=>t>>>n-32|e<<64-n;function ce(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var yo=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),vo=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,ko=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),wo=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,So=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),To=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0;var Eo=xo(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Wi=Eo[0],Yi=Eo[1],Te=new Uint32Array(80),Ee=new Uint32Array(80),Pn=class extends _t{constructor(e){super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:p,Gh:f,Gl:m,Hh:g,Hl:h}=this;return [e,n,r,o,s,i,a,c,l,u,d,p,f,m,g,h]}set(e,n,r,o,s,i,a,c,l,u,d,p,f,m,g,h){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=f|0,this.Gl=m|0,this.Hh=g|0,this.Hl=h|0;}process(e,n){for(let y=0;y<16;y++,n+=4)Te[y]=e.getUint32(n),Ee[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){let E=Te[y-15]|0,C=Ee[y-15]|0,O=Pe(E,C,1)^Pe(E,C,8)^Dn(E,C,7),T=Le(E,C,1)^Le(E,C,8)^An(E,C,7),D=Te[y-2]|0,R=Ee[y-2]|0,S=Pe(D,R,19)^rt(D,R,61)^Dn(D,R,6),L=Le(D,R,19)^ot(D,R,61)^An(D,R,6),v=ko(T,L,Ee[y-7],Ee[y-16]),w=wo(v,O,S,Te[y-7],Te[y-16]);Te[y]=w|0,Ee[y]=v|0;}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:p,Fh:f,Fl:m,Gh:g,Gl:h,Hh:x,Hl:b}=this;for(let y=0;y<80;y++){let E=Pe(d,p,14)^Pe(d,p,18)^rt(d,p,41),C=Le(d,p,14)^Le(d,p,18)^ot(d,p,41),O=d&f^~d&g,T=p&m^~p&h,D=So(b,C,T,Yi[y],Ee[y]),R=To(D,x,E,O,Wi[y],Te[y]),S=D|0,L=Pe(r,o,28)^rt(r,o,34)^rt(r,o,39),v=Le(r,o,28)^ot(r,o,34)^ot(r,o,39),w=r&s^r&a^s&a,_=o&i^o&c^i&c;x=g|0,b=h|0,g=f|0,h=m|0,f=d|0,m=p|0,{h:d,l:p}=ce(l|0,u|0,R|0,S|0),l=a|0,u=c|0,a=s|0,c=i|0,s=r|0,i=o|0;let P=yo(S,v,_);r=vo(P,R,L,w),o=P|0;}(({h:r,l:o}=ce(this.Ah|0,this.Al|0,r|0,o|0))),{h:s,l:i}=ce(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ce(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ce(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:p}=ce(this.Eh|0,this.El|0,d|0,p|0),{h:f,l:m}=ce(this.Fh|0,this.Fl|0,f|0,m|0),{h:g,l:h}=ce(this.Gh|0,this.Gl|0,g|0,h|0),{h:x,l:b}=ce(this.Hh|0,this.Hl|0,x|0,b|0),this.set(r,o,s,i,a,c,l,u,d,p,f,m,g,h,x,b);}roundClean(){tt(Te,Ee);}destroy(){this.destroyed=true,tt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},Ln=class extends Pn{Ah=H[0]|0;Al=H[1]|0;Bh=H[2]|0;Bl=H[3]|0;Ch=H[4]|0;Cl=H[5]|0;Dh=H[6]|0;Dl=H[7]|0;Eh=H[8]|0;El=H[9]|0;Fh=H[10]|0;Fl=H[11]|0;Gh=H[12]|0;Gl=H[13]|0;Hh=H[14]|0;Hl=H[15]|0;constructor(){super(64);}};var At=mo(()=>new Ln,go(3));var z=(t,e,n)=>ne(t,e,n),Bn=Ct,jn=Ot,le=(...t)=>_n(...t),Ro=t=>nt(t),Mt=In,Co=t=>ho(t),Lt=BigInt(0),Mn=BigInt(1);function ze(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"expected boolean, got type="+typeof t)}return t}function Zi(t){if(typeof t=="bigint"){if(!Pt(t))throw new RangeError("positive bigint expected, got "+t)}else Bn(t);return t}function he(t,e=""){if(typeof t!="number"){let n=e&&`"${e}" `;throw new TypeError(n+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let n=e&&`"${e}" `;throw new RangeError(n+"expected safe integer, got "+t)}}function Io(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Lt:BigInt("0x"+t)}function Nn(t){return Io(Ot(t))}function ge(t){return Io(Ot(st(ne(t)).reverse()))}function $n(t,e){if(Ct(e),e===0)throw new RangeError("zero length");t=Zi(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return nt(n.padStart(e*2,"0"))}function Oo(t,e){return $n(t,e).reverse()}function _o(t,e){if(t=z(t),e=z(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 st(t){return Uint8Array.from(z(t))}var Pt=t=>typeof t=="bigint"&&Lt<=t;function Xi(t,e,n){return Pt(t)&&Pt(e)&&Pt(n)&&e<=t&&t<n}function Fn(t,e,n,r){if(!Xi(e,n,r))throw new RangeError("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function zn(t){if(t<Lt)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>Lt;t>>=Mn,e+=1);return e}var Do=t=>(Mn<<BigInt(t))-Mn;function Me(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function r(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=t[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>r(a,c,i));o(e,false),o(n,true);}var Vn=()=>{throw new Error("not implemented")};var K=BigInt(0),U=BigInt(1),Be=BigInt(2),Mo=BigInt(3),Bo=BigInt(4),jo=BigInt(5),Qi=BigInt(7),No=BigInt(8),ea=BigInt(9),$o=BigInt(16);function N(t,e){if(e<=K)throw new Error("mod: expected positive modulus, got "+e);let n=t%e;return n>=K?n:e+n}function re(t,e,n){if(e<K)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >K;)r*=r,r%=n;return r}function Ao(t,e){if(t===K)throw new Error("invert: expected non-zero number");if(e<=K)throw new Error("invert: expected positive modulus, got "+e);let n=N(t,e),r=e,o=K,i=U;for(;n!==K;){let l=r/n,u=r-n*l,d=o-i*l;r=n,n=u,o=i,i=d;}if(r!==U)throw new Error("invert: does not exist");return N(o,e)}function Un(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function Fo(t,e){let n=t,r=(n.ORDER+U)/Bo,o=n.pow(e,r);return Un(n,o,e),o}function ta(t,e){let n=t,r=(n.ORDER-jo)/No,o=n.mul(e,Be),s=n.pow(o,r),i=n.mul(e,s),a=n.mul(n.mul(i,Be),s),c=n.mul(i,n.sub(a,n.ONE));return Un(n,c,e),c}function na(t){let e=$t(t),n=zo(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+Qi)/$o;return((a,c)=>{let l=a,u=l.pow(c,i),d=l.mul(u,r),p=l.mul(u,o),f=l.mul(u,s),m=l.eql(l.sqr(d),c),g=l.eql(l.sqr(p),c);u=l.cmov(u,d,m),d=l.cmov(f,p,g);let h=l.eql(l.sqr(d),c),x=l.cmov(u,d,h);return Un(l,x,c),x})}function zo(t){if(t<Mo)throw new Error("sqrt is not defined for small field");let e=t-U,n=0;for(;e%Be===K;)e/=Be,n++;let r=Be,o=$t(t);for(;Po(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Fo;let s=o.pow(r,e),i=(e+U)/Be;return function(c,l){let u=c;if(u.is0(l))return l;if(Po(u,l)!==1)throw new Error("Cannot find square root");let d=n,p=u.mul(u.ONE,s),f=u.pow(l,e),m=u.pow(l,i);for(;!u.eql(f,u.ONE);){if(u.is0(f))return u.ZERO;let g=1,h=u.sqr(f);for(;!u.eql(h,u.ONE);)if(g++,h=u.sqr(h),g===d)throw new Error("Cannot find square root");let x=U<<BigInt(d-g-1),b=u.pow(p,x);d=g,p=u.sqr(b),f=u.mul(f,p),m=u.mul(m,b);}return m}}function ra(t){return t%Bo===Mo?Fo:t%No===jo?ta:t%$o===ea?na(t):zo(t)}var be=(t,e)=>(N(t,e)&U)===U,oa=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Vo(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=oa.reduce((r,o)=>(r[o]="function",r),e);if(Me(t,n),he(t.BYTES,"BYTES"),he(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=U)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function sa(t,e,n){let r=t;if(n<K)throw new Error("invalid exponent, negatives unsupported");if(n===K)return r.ONE;if(n===U)return e;let o=r.ONE,s=e;for(;n>K;)n&U&&(o=r.mul(o,s)),s=r.sqr(s),n>>=U;return o}function Nt(t,e,n=false){let r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),s=e.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),i=r.inv(s);return e.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),i),o}function Po(t,e){let n=t,r=(n.ORDER-U)/Be,o=n.pow(e,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function ia(t,e){if(e!==void 0&&Bn(e),t<=K)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let n=zn(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 Lo=new WeakMap,jt=class{ORDER;BITS;BYTES;isLE;ZERO=K;ONE=U;_lengths;_mod;constructor(e,n={}){if(e<=U)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:true}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:s}=ia(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this);}create(e){return N(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return K<=e&&e<this.ORDER}is0(e){return e===K}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&U)===U}neg(e){return N(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return N(e*e,this.ORDER)}add(e,n){return N(e+n,this.ORDER)}sub(e,n){return N(e-n,this.ORDER)}mul(e,n){return N(e*n,this.ORDER)}pow(e,n){return sa(this,e,n)}div(e,n){return N(e*Ao(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Ao(e,this.ORDER)}sqrt(e){let n=Lo.get(this);return n||Lo.set(this,n=ra(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?Oo(e,this.BYTES):$n(e,this.BYTES)}fromBytes(e,n=false){z(e);let{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?ge(e):Nn(e);if(a&&(c=N(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Nt(this,e)}cmov(e,n,r){return ze(r,"condition"),r?n:e}};Object.freeze(jt.prototype);function $t(t,e={}){return new jt(t,e)}var Ft=BigInt(0),Jn=BigInt(1);function Uo(t,e){let n=e.negate();return t?n:e}function Vt(t,e){let n=Nt(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function Jo(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function qn(t,e){Jo(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=Do(t),i=BigInt(t);return {windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function qo(t,e,n){let{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n,a=Number(t&o),c=t>>i;a>r&&(a-=s,c+=Jn);let l=e*r,u=l+Math.abs(a)-1,d=a===0,p=a<0,f=e%2!==0;return {nextN:c,offset:u,isZero:d,isNeg:p,isNegF:f,offsetF:l}}var Hn=new WeakMap,Go=new WeakMap;function Kn(t){return Go.get(t)||1}function Ho(t){if(t!==Ft)throw new Error("invalid wNAF")}var zt=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>Ft;)n&Jn&&(r=r.add(o)),o=o.double(),n>>=Jn;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=qn(n,this.bits),s=[],i=e,a=i;for(let c=0;c<r;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double();}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=qn(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:p,offsetF:f}=qo(r,a,i);r=c,u?s=s.add(Uo(p,n[f])):o=o.add(Uo(d,n[l]));}return Ho(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.ZERO){let s=qn(e,this.bits);for(let i=0;i<s.windows&&r!==Ft;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=qo(r,i,s);if(r=a,!l){let d=n[c];o=o.add(u?d.negate():d);}}return Ho(r),o}getPrecomputes(e,n,r){let o=Hn.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Hn.set(n,o))),o}cached(e,n,r){let o=Kn(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let s=Kn(e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){Jo(n,this.bits),Go.set(e,n),Hn.delete(e);}hasCache(e){return Kn(e)!==1}};function Ko(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Vo(e),e}else return $t(t,{isLE:n})}function Wo(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of ["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Ft))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Ko(e.p,n.Fp,r),s=Ko(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.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Yo(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var Re=BigInt(0),q=BigInt(1),Gn=BigInt(2),aa=BigInt(8);function ca(t,e,n,r){let o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function Zo(t,e={}){let n=e,r=Wo("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r,i=r.CURVE,{h:a}=i;Me(n,{},{uvRatio:"function"});let c=Gn<<BigInt(s.BYTES*8)-q,l=g=>o.create(g),u=n.uvRatio===void 0?(g,h)=>{try{return {isValid:!0,value:o.sqrt(o.div(g,h))}}catch{return {isValid:false,value:Re}}}:n.uvRatio;if(!ca(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(g,h,x=false){let b=x?q:Re;return Fn("coordinate "+g,h,b,c),h}function p(g){if(!(g instanceof f))throw new Error("EdwardsPoint expected")}class f{static BASE=new f(i.Gx,i.Gy,q,l(i.Gx*i.Gy));static ZERO=new f(Re,q,q,Re);static Fp=o;static Fn=s;X;Y;Z;T;constructor(h,x,b,y){this.X=d("x",h),this.Y=d("y",x),this.Z=d("z",b,true),this.T=d("t",y),Object.freeze(this);}static CURVE(){return i}static fromAffine(h){if(h instanceof f)throw new Error("extended point not allowed");let{x,y:b}=h||{};return d("x",x),d("y",b),new f(x,b,q,l(x*b))}static fromBytes(h,x=false){let b=o.BYTES,{a:y,d:E}=i;h=st(z(h,b,"point")),ze(x,"zip215");let C=st(h),O=h[b-1];C[b-1]=O&-129;let T=ge(C),D=x?c:o.ORDER;Fn("point.y",T,Re,D);let R=l(T*T),S=l(R-q),L=l(E*R-y),{isValid:v,value:w}=u(S,L);if(!v)throw new Error("bad point: invalid y coordinate");let _=(w&q)===q,P=(O&128)!==0;if(!x&&w===Re&&P)throw new Error("bad point: x=0 and x_0=1");return P!==_&&(w=l(-w)),f.fromAffine({x:w,y:T})}static fromHex(h,x=false){return f.fromBytes(Ro(h),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,x=true){return m.createCache(this,h),x||this.multiply(Gn),this}assertValidity(){let h=this,{a:x,d:b}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:y,Y:E,Z:C,T:O}=h,T=l(y*y),D=l(E*E),R=l(C*C),S=l(R*R),L=l(T*x),v=l(R*l(L+D)),w=l(S+l(b*l(T*D)));if(v!==w)throw new Error("bad point: equation left != right (1)");let _=l(y*E),P=l(C*O);if(_!==P)throw new Error("bad point: equation left != right (2)")}equals(h){p(h);let{X:x,Y:b,Z:y}=this,{X:E,Y:C,Z:O}=h,T=l(x*O),D=l(E*y),R=l(b*O),S=l(C*y);return T===D&&R===S}is0(){return this.equals(f.ZERO)}negate(){return new f(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:h}=i,{X:x,Y:b,Z:y}=this,E=l(x*x),C=l(b*b),O=l(Gn*l(y*y)),T=l(h*E),D=x+b,R=l(l(D*D)-E-C),S=T+C,L=S-O,v=T-C,w=l(R*L),_=l(S*v),P=l(R*v),B=l(L*S);return new f(w,_,B,P)}add(h){p(h);let{a:x,d:b}=i,{X:y,Y:E,Z:C,T:O}=this,{X:T,Y:D,Z:R,T:S}=h,L=l(y*T),v=l(E*D),w=l(O*b*S),_=l(C*R),P=l((y+E)*(T+D)-L-v),B=_-w,V=_+w,I=l(v-x*L),X=l(P*B),$=l(V*I),oe=l(P*I),J=l(B*V);return new f(X,$,J,oe)}subtract(h){return p(h),this.add(h.negate())}multiply(h){if(!s.isValidNot0(h))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:b}=m.cached(this,h,y=>Vt(f,y));return Vt(f,[x,b])[0]}multiplyUnsafe(h){if(!s.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===Re?f.ZERO:this.is0()||h===q?this:m.unsafe(this,h,x=>Vt(f,x))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return m.unsafe(this,i.n).is0()}toAffine(h){let x=this,b=h,{X:y,Y:E,Z:C}=x,O=x.is0();b==null&&(b=O?aa:o.inv(C));let T=l(y*b),D=l(E*b),R=o.mul(C,b);if(O)return {x:Re,y:q};if(R!==q)throw new Error("invZ was invalid");return {x:T,y:D}}clearCofactor(){return a===q?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y:x}=this.toAffine(),b=o.toBytes(x);return b[b.length-1]|=h&q?128:0,b}toHex(){return jn(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=new zt(f,s.BITS);return s.BITS>=8&&f.BASE.precompute(8),Object.freeze(f.prototype),Object.freeze(f),f}var Ut=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e;}static fromBytes(e){Vn();}static fromHex(e){Vn();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){return this.ep.toAffine(e)}toHex(){return jn(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return true}isSmallOrder(){return false}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function Xo(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');let r=e,o=n;Me(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=t,l=r.outputLen,u=2*a.BYTES;if(l!==void 0&&(he(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=o.randomBytes===void 0?Co:o.randomBytes,p=o.adjustScalarBytes===void 0?v=>v:o.adjustScalarBytes,f=o.domain===void 0?(v,w,_)=>{if(ze(_,"phflag"),w.length||_)throw new Error("Contexts/pre-hash are not supported");return v}:o.domain;function m(v){return c.create(ge(v))}function g(v){let w=T.secretKey;z(v,T.secretKey,"secretKey");let _=z(r(v),2*w,"hashedSecretKey"),P=p(_.slice(0,w)),B=_.slice(w,2*w),V=m(P);return {head:P,prefix:B,scalar:V}}function h(v){let{head:w,prefix:_,scalar:P}=g(v),B=i.multiply(P),V=B.toBytes();return {head:w,prefix:_,scalar:P,point:B,pointBytes:V}}function x(v){return h(v).pointBytes}function b(v=Uint8Array.of(),...w){let _=le(...w);return m(r(f(_,z(v,void 0,"context"),!!s)))}function y(v,w,_={}){v=z(v,void 0,"message"),s&&(v=s(v));let{prefix:P,scalar:B,pointBytes:V}=h(w),I=b(_.context,P,v),X=i.multiply(I).toBytes(),$=b(_.context,X,V,v),oe=c.create(I+$*B);if(!c.isValid(oe))throw new Error("sign failed: invalid s");let J=le(X,c.toBytes(oe));return z(J,T.signature,"result")}let E={zip215:o.zip215};function C(v,w,_,P=E){let{context:B}=P,V=P.zip215===void 0?!!E.zip215:P.zip215,I=T.signature;v=z(v,I,"signature"),w=z(w,void 0,"message"),_=z(_,T.publicKey,"publicKey"),V!==void 0&&ze(V,"zip215"),s&&(w=s(w));let X=I/2,$=v.subarray(0,X),oe=ge(v.subarray(X,I)),J,ue,ye;try{J=t.fromBytes(_,V),ue=t.fromBytes($,V),ye=i.multiplyUnsafe(oe);}catch{return false}if(!V&&J.isSmallOrder())return false;let ve=b(B,$,_,w);return ue.add(J.multiplyUnsafe(ve)).subtract(ye).clearCofactor().is0()}let O=a.BYTES,T={secretKey:O,publicKey:O,signature:2*O,seed:O};function D(v){return v=v===void 0?d(T.seed):v,z(v,T.seed,"seed")}function R(v){return Mt(v)&&v.length===T.secretKey}function S(v,w){try{return !!t.fromBytes(v,w===void 0?E.zip215:w)}catch{return false}}let L={getExtendedPublicKey:h,randomSecretKey:D,isValidSecretKey:R,isValidPublicKey:S,toMontgomery(v){let{y:w}=t.fromBytes(v),_=T.publicKey,P=_===32;if(!P&&_!==57)throw new Error("only defined for 25519 and 448");let B=P?a.div(q+w,q-w):a.div(w-q,w+q);return a.toBytes(B)},toMontgomerySecret(v){let w=T.secretKey;z(v,w);let _=r(v.subarray(0,w));return p(_).subarray(0,w)}};return Object.freeze(T),Object.freeze(L),Object.freeze({keygen:Yo(D,x),getPublicKey:x,sign:y,verify:C,utils:L,Point:t,lengths:T})}var da=BigInt(0),xe=BigInt(1),es=BigInt(2);var pa=BigInt(5),fa=BigInt(8),Ve=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Qn={p:Ve,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:fa,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ma(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=Ve,a=t*t%s*t%s,c=re(a,es,s)*a%s,l=re(c,xe,s)*t%s,u=re(l,pa,s)*l%s,d=re(u,e,s)*u%s,p=re(d,n,s)*d%s,f=re(p,r,s)*p%s,m=re(f,o,s)*f%s,g=re(m,o,s)*f%s,h=re(g,e,s)*u%s;return {pow_p_5_8:re(h,es,s)*t%s,b2:a}}function ha(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var Yn=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function er(t,e){let n=Ve,r=N(e*e*e,n),o=N(r*r*e,n),s=ma(t*o).pow_p_5_8,i=N(t*r*s,n),a=N(e*i*i,n),c=i,l=N(i*Yn,n),u=a===t,d=a===N(-t,n),p=a===N(-t*Yn,n);return u&&(i=c),(d||p)&&(i=l),be(i,n)&&(i=N(-i,n)),{isValid:u||d,value:i}}var Ie=Zo(Qn,{uvRatio:er}),Ce=Ie.Fp,rs=Ie.Fn;function ga(t){return Xo(Ie,At,Object.assign({adjustScalarBytes:ha,zip215:true},t))}var os=ga({});var Zn=Yn;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var xa=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var ts=t=>er(xe,t),ka=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Xn=t=>Ce.create(ge(t)&ka);var Oe=class t extends Ut{static BASE=new t(Ie.BASE);static ZERO=new t(Ie.ZERO);static Fp=Ce;static Fn=rs;constructor(e){super(e);}static fromAffine(e){return new t(Ie.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoPoint expected")}init(e){return new t(e)}static fromBytes(e){ne(e,32);let{a:n,d:r}=Qn,o=Ve,s=E=>Ce.create(E),i=Xn(e);if(!_o(Ce.toBytes(i),e)||be(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(xe+n*a),l=s(xe-n*a),u=s(c*c),d=s(l*l),p=s(n*r*u-d),{isValid:f,value:m}=ts(s(p*d)),g=s(m*l),h=s(m*g*p),x=s((i+i)*g);be(x,o)&&(x=s(-x));let b=s(c*h),y=s(x*b);if(!f||be(y,o)||b===da)throw new Error("invalid ristretto255 encoding 2");return new t(new Ie(x,b,xe,y))}static fromHex(e){return t.fromBytes(nt(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,s=Ve,i=h=>Ce.create(h),a=i(i(r+n)*i(r-n)),c=i(e*n),l=i(c*c),{value:u}=ts(i(a*l)),d=i(u*a),p=i(u*c),f=i(d*p*o),m;if(be(o*f,s)){let h=i(n*Zn),x=i(e*Zn);e=h,n=x,m=i(d*xa);}else m=p;be(e*f,s)&&(n=i(-n));let g=i((r-n)*m);return be(g,s)&&(g=i(-g)),Ce.toBytes(g)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:s}=e.ep,i=l=>Ce.create(l),a=i(n*s)===i(r*o),c=i(r*s)===i(n*o);return a||c}is0(){return this.equals(t.ZERO)}};Object.freeze(Oe.BASE);Object.freeze(Oe.ZERO);Object.freeze(Oe.prototype);Object.freeze(Oe);var ss=`-----BEGIN PUBLIC KEY-----
|
|
1
|
+
var qs="2026-08-24",ln={"gpt-4.1":{inputPer1k:.002,outputPer1k:.008,cachedInputPer1k:5e-4},"gpt-4.1-mini":{inputPer1k:4e-4,outputPer1k:.0016,cachedInputPer1k:1e-4},"gpt-4.1-nano":{inputPer1k:1e-4,outputPer1k:4e-4,
|
|
2
|
+
cachedInputPer1k:25e-6},"gpt-4o":{inputPer1k:.0025,outputPer1k:.01,cachedInputPer1k:.00125},"gpt-4o-mini":{inputPer1k:15e-5,outputPer1k:6e-4,cachedInputPer1k:75e-6},"gpt-4-turbo":{inputPer1k:.01,outputPer1k:.03},
|
|
3
|
+
"gpt-4":{inputPer1k:.03,outputPer1k:.06},"gpt-3.5-turbo":{inputPer1k:5e-4,outputPer1k:.0015},"gpt-5":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gpt-5-codex":{inputPer1k:.00125,outputPer1k:.01,
|
|
4
|
+
cachedInputPer1k:125e-6},"gpt-5-mini":{inputPer1k:25e-5,outputPer1k:.002,cachedInputPer1k:25e-6},"gpt-5-nano":{inputPer1k:5e-5,outputPer1k:4e-4,cachedInputPer1k:5e-6},"gpt-5.1-codex":{inputPer1k:.00125,
|
|
5
|
+
outputPer1k:.01,cachedInputPer1k:125e-6},"gpt-5.1-codex-max":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gpt-5.1-codex-mini":{inputPer1k:25e-5,outputPer1k:.002,cachedInputPer1k:25e-6},
|
|
6
|
+
"gpt-5.1-thinking":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gpt-5.2":{inputPer1k:.00175,outputPer1k:.014,cachedInputPer1k:175e-6},"gpt-5.2-codex":{inputPer1k:.00175,outputPer1k:.014,
|
|
7
|
+
cachedInputPer1k:175e-6},"gpt-5.3-codex":{inputPer1k:.00175,outputPer1k:.014,cachedInputPer1k:175e-6},"gpt-5.4":{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},"gpt-5.4-mini":{inputPer1k:75e-5,
|
|
8
|
+
outputPer1k:.0045,cachedInputPer1k:75e-6},"gpt-5.4-nano":{inputPer1k:2e-4,outputPer1k:.00125,cachedInputPer1k:2e-5},"gpt-5.5":{inputPer1k:.005,outputPer1k:.03,cachedInputPer1k:5e-4},"gpt-5.6-luna":{inputPer1k:2e-4,
|
|
9
|
+
outputPer1k:.0012,cachedInputPer1k:2e-5},"gpt-5.6-sol":{inputPer1k:.004,outputPer1k:.02,cachedInputPer1k:4e-4},"gpt-5.6-terra":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"claude-opus-4-5":{
|
|
10
|
+
inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4-6":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4-7":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},
|
|
11
|
+
"claude-opus-4-8":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-5":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},
|
|
12
|
+
"claude-sonnet-4-5":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-4-6":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-5":{inputPer1k:.002,outputPer1k:.01,
|
|
13
|
+
cachedInputPer1k:2e-4},"claude-fable-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-sonnet-4":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-haiku-4-5":{inputPer1k:.001,
|
|
14
|
+
outputPer1k:.005,cachedInputPer1k:1e-4},"claude-3-5-sonnet":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-3-5-haiku":{inputPer1k:8e-4,outputPer1k:.004,cachedInputPer1k:8e-5},"claude\
|
|
15
|
+
-3-opus":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"claude-3-haiku":{inputPer1k:25e-5,outputPer1k:.00125,cachedInputPer1k:3e-5},"gemini-3.7-flash":{inputPer1k:75e-5,outputPer1k:.00375,
|
|
16
|
+
cachedInputPer1k:75e-6},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5},"gemini-3.1-pro-\
|
|
17
|
+
preview":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}};
|
|
18
|
+
function un(t,e,n){if(!n)return;let r=t[n];if(r)return r;let o=n.lastIndexOf("/"),s=o>=0?n.slice(o+1):n,i=t[s];if(i)return i;for(let a of e){if(!s.startsWith(a))continue;let c=s.charAt(a.length);if(c!==
|
|
19
|
+
""&&c!=="-"&&c!=="."&&c!=="_")continue;let l=s.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return t[a]}}function dn(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var Hs=dn(ln);function bt(t){
|
|
20
|
+
return un(ln,Hs,t)}var Ks=0;function pn(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++Ks,o=Date.now?Date.now():0;for(let s=0;s<
|
|
21
|
+
16;s++)e[s]=(s<6?r>>>s*8:o>>>(s-6)*8)&255;}e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=[];for(let r=0;r<16;r++)n.push(e[r].toString(16).padStart(2,"0"));return `${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}\
|
|
22
|
+
-${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var Mc=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function jc(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 fn=class{id;exact=false;constructor(e="heuristic"){this.id=e;}count(e){if(e.length===0)return 0;let n=e.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],r=0;for(let o of n){let s=o[0];if(/\s/.test(s)){let i=(o.
|
|
23
|
+
match(/\n/g)??[]).length;r+=i+Math.floor(Math.max(0,o.length-1)/2);}else /[A-Za-z]/.test(s)?r+=Math.max(1,Math.ceil(o.length/4)):/\d/.test(s)?r+=Math.max(1,Math.ceil(o.length/2)):r+=1;}return Math.max(r,
|
|
24
|
+
Math.ceil(e.length/4))}},je=new fn;var mn=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=je){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){
|
|
25
|
+
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.
|
|
26
|
+
get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},_r=new mn;var hn=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}},Dr={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini",
|
|
27
|
+
"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 Js(t,e={}){let n=e.codificaciones??
|
|
28
|
+
["o200k_base","cl100k_base"],r=false;for(let o of n){let s;try{s=await import(`gpt-tokenizer/encoding/${o}`);}catch{continue}if(typeof s.encode=="function"){t.register(new hn(o,s)),r=true;for(let i of Dr[o]??
|
|
29
|
+
[])t.mapModel(i,o),t.mapModel(`openai/${i}`,o);}}return r}var Hc=Dr,Kc=Js;var Ne=class{avoidedLlm=0;baselineLlm=1;actualLlm=0;baselineRetrieval=0;actualRetrieval=0;baselineTools=0;actualTools=0;retries=0;baselineInput=0;actualInput=0;eliminatedInput=0;compressedInput=0;baselineOutput=0;actualOutput=0;eliminatedOutput=0;providerCachedInput=0;cacheWriteInputTokens=0;cacheWritePremiumUsd=0;sentInputLocal=0;removedInputLocal=0;estimatorExact=false;repairOutput=0;repairInput=0;discoveryInput=0;discoveryOutput=0;extraCostUsd=0;cascadeInput=0;cascadeOutput=0;cascadeAttempt(e,n){
|
|
30
|
+
this.cascadeInput+=Math.max(0,e.inputTokens),this.cascadeOutput+=Math.max(0,e.outputTokens),this.extraCostUsd+=Math.max(0,e.inputTokens)/1e3*n.inputPer1k+Math.max(0,e.outputTokens)/1e3*n.outputPer1k;}cacheWritePremium(e,n,r){
|
|
31
|
+
let o=Math.max(0,e);this.cacheWriteInputTokens+=o,this.cacheWritePremiumUsd+=o/1e3*r.inputPer1k*Math.max(0,n-1);}compressionReport=void 0;eliminate(e){this.eliminatedInput+=Math.max(0,e);}compress(e,n){
|
|
32
|
+
this.compressedInput+=Math.max(0,e-n);}providerCached(e){this.providerCachedInput+=Math.max(0,e);}avoidCall(e,n){this.avoidedLlm+=1,this.actualLlm=0,this.baselineInput=e,this.baselineOutput=n;}get publishedBaselineOutput(){
|
|
33
|
+
return this.avoidedLlm===0?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):this.baselineOutput}estimateCost(e){let n=this.avoidedLlm===0,r="estimated";if(n)if(this.actualInput>0&&
|
|
34
|
+
this.sentInputLocal>0){let d=this.actualInput/this.sentInputLocal,f=Math.max(0,this.actualInput-this.repairInput-this.discoveryInput);this.baselineInput=f+Math.round(d*this.removedInputLocal),r=this.removedInputLocal===
|
|
35
|
+
0?"measured":"estimated";}else this.actualInput>0?(this.baselineInput=this.actualInput,r="measured"):(this.baselineInput=0,r="unmeasured");let o=n?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):
|
|
36
|
+
this.baselineOutput,s=e.cachedInputPer1k??e.inputPer1k,i=Math.min(this.providerCachedInput,this.actualInput),a=d=>Math.max(0,d-i)/1e3*e.inputPer1k+i/1e3*s,c=a(this.baselineInput)+o/1e3*e.outputPer1k,l=a(
|
|
37
|
+
this.actualInput)+this.actualOutput/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd,u=c===0?0:1-l/c;return {baselineEstimate:Ar(c),actual:Ar(l),netSavings:Ws(u),basis:r}}};function Ar(t){
|
|
38
|
+
return Math.round(t*1e10)/1e10}function Ws(t){return Math.round(t*1e6)/1e6}var Gs=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
|
|
39
|
+
4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
|
|
40
|
+
1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,
|
|
41
|
+
1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ys=new TextEncoder;function se(t,e){return t>>>e|t<<32-e}function Pr(t){let e=Ys.encode(t),n=e.length*
|
|
42
|
+
8,r=(e.length+8>>6)+1,o=new Uint8Array(r*64);o.set(e),o[e.length]=128;let s=new DataView(o.buffer);s.setUint32(o.length-8,Math.floor(n/4294967296)),s.setUint32(o.length-4,n>>>0);let i=new Uint32Array(
|
|
43
|
+
[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let l=0;l<o.length;l+=64){for(let b=0;b<16;b++)a[b]=s.getUint32(l+b*4);for(let b=16;b<
|
|
44
|
+
64;b++){let y=a[b-15],E=a[b-2],C=se(y,7)^se(y,18)^y>>>3,O=se(E,17)^se(E,19)^E>>>10;a[b]=a[b-16]+C+a[b-7]+O|0;}let u=i[0],d=i[1],f=i[2],m=i[3],h=i[4],p=i[5],g=i[6],x=i[7];for(let b=0;b<64;b++){let y=se(
|
|
45
|
+
h,6)^se(h,11)^se(h,25),E=h&p^~h&g,C=x+y+E+Gs[b]+a[b]|0,O=se(u,2)^se(u,13)^se(u,22),T=u&d^u&f^d&f,D=O+T|0;x=g,g=p,p=h,h=m+C|0,m=f,f=d,d=u,u=C+D|0;}i[0]=i[0]+u|0,i[1]=i[1]+d|0,i[2]=i[2]+f|0,i[3]=i[3]+m|0,
|
|
46
|
+
i[4]=i[4]+h|0,i[5]=i[5]+p|0,i[6]=i[6]+g|0,i[7]=i[7]+x|0;}let c="";for(let l=0;l<8;l++)c+=(i[l]>>>0).toString(16).padStart(8,"0");return c}var Zs=/\s+/g,Xs=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],Qs=/[¿?¡!;.,:'"·•]/g,ei=/([a-z])\p{M}+/gu,ti=/(^|\s)\p{M}+/gu,
|
|
47
|
+
gn=/\p{L}/u;function Y(t){return t>="0"&&t<="9"}function xt(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,r]of Xs)e=e.replace(n,r);return e=e.normalize("NFD").replace(ei,"$1").replace(ti,"$1").
|
|
48
|
+
normalize("NFC"),e=e.replace(Qs,(n,r,o)=>{let s=o[r-1]??"",i=o[r+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return Y(s)&&Y(i)?n:"";case "!":return Y(s)?n:"";case ".":case ",":return Y(s)&&Y(i)||
|
|
49
|
+
Y(i)&&!Y(s)&&!gn.test(s)?n:"";case ":":return Y(s)&&Y(i)?n:"";case "'":case '"':return gn.test(s)&&gn.test(i)||Y(s)||Y(i)?n:"";default:return Y(s)||Y(i)?n:""}}),e.replace(Zs," ").trim()}function ie(t){return Pr(
|
|
50
|
+
t)}function Se(t){return JSON.stringify(bn(t))}function bn(t){if(Array.isArray(t))return t.map(bn);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=bn(t[n]);return e}return t}
|
|
51
|
+
function xn(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function yn(t){let e=t.context??{},n=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(
|
|
52
|
+
`
|
|
53
|
+
`),r=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${xt(s.content)}`).join(`
|
|
54
|
+
`),o=(t.tools??[]).map(s=>({id:s.id,risk:s.risk,parameters:s.parameters??null})).sort((s,i)=>s.id.localeCompare(i.id));return {model:t.model,modelFamily:xn(t.model),messages:t.messages,normalizedText:r,
|
|
55
|
+
systemPromptHash:ie(n),toolsetHash:ie(Se(o)),structuredDataHash:t.structuredData!==void 0?ie(Se(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.contractId??"none",contractId:t.
|
|
56
|
+
response?.contractId??null,temperature:t.temperature??null,seed:t.seed??null,tenantId:e.tenantId??"anonymous",authorizationScope:e.authorizationScope??"default",principal:e.sessionId??null,locale:e.locale??
|
|
57
|
+
"und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var Lr="n2";function vn(t,e={}){let n=e.servedModel??t.model,r=Se({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily:xn(n),
|
|
58
|
+
model:n,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,data:t.structuredDataHash,locale:t.locale,temperature:t.temperature,seed:t.seed,knowledgeEpoch:t.knowledgeEpoch,
|
|
59
|
+
freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${Lr}:${ie(r)}`}function Mr(t,e={}){let n=Se({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,
|
|
60
|
+
model:e.servedModel??t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,data:t.structuredDataHash,temperature:t.temperature,seed:t.seed,deferrable:e.deferrable===
|
|
61
|
+
true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:inflight:${Lr}:${ie(n)}`}var ni=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\
|
|
62
|
+
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|\
|
|
63
|
+
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\
|
|
64
|
+
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\
|
|
65
|
+
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\
|
|
66
|
+
nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),ri=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nu\
|
|
67
|
+
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\
|
|
68
|
+
|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\
|
|
69
|
+
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\
|
|
70
|
+
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\
|
|
71
|
+
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 kn(t){let e=[],n=t.normalizedText,
|
|
72
|
+
r=(t.original.tools??[]).some(f=>f.risk==="write"||f.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||ni.test(n),s=ri.test(n),i=(t.temperature??0)>.3&&t.seed==null;r&&e.
|
|
73
|
+
push("write/destructive tools present"),o&&e.push("freshness-sensitive request"),s&&e.push("personalized/account-scoped request"),i&&e.push("stochastic sampling (temp>0.3, no seed)");let a=o&&(t.freshnessBucket==
|
|
74
|
+
null||t.freshnessBucket==="any"),c=t.freshnessBucket==="live",l=s&&t.principal==null,u=!i&&!a&&!c&&!l&&!r;r&&e.push("write/destructive tools \u2192 exact cache off (side effects must execute)"),c&&e.push(
|
|
75
|
+
"freshnessBucket=live \u2192 exact cache off (answer must be current)"),a&&e.push("freshness-sensitive without a freshness bucket \u2192 exact cache off"),l&&e.push("personalized request with no princ\
|
|
76
|
+
ipal (context.sessionId) \u2192 exact cache off");let d=!r&&!o&&!s&&!i&&t.freshnessBucket!=="day";return {allowExactCache:u,allowSemanticCache:d,allowSingleflight:!r&&!l,allowCompression:true,requiresFreshData:o,
|
|
77
|
+
hasSideEffects:r,isPersonalized:s,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var yt=class{store=new Map;maxEntries;now;constructor(e={}){this.maxEntries=e.maxEntries??1e4,this.now=e.now??(()=>Date.now());}async get(e){let n=this.store.get(e);return n?n.expiresAtMs!==null&&this.
|
|
78
|
+
now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),n.value):null}async set(e,n,r){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let o=this.store.keys().
|
|
79
|
+
next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:n,expiresAtMs:r!=null?this.now()+r:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};var vt=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.
|
|
80
|
+
inflight.set(e,o),this.waiters.set(e,1);try{return {value:await o,coalesced:!1}}finally{this.inflight.delete(e),this.waiters.delete(e);}}get activeKeys(){return this.inflight.size}};function oi(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 si(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(
|
|
81
|
+
Boolean)}function ii(t){let e=new Array(256).fill(0),n=si(t);if(n.length===0)return e;let r=new Map;for(let s=0;s<n.length;s++){let i=n[s];if(r.set(i,(r.get(i)??0)+1),s+1<n.length){let a=`${i}\0${n[s+
|
|
82
|
+
1]}`;r.set(a,(r.get(a)??0)+1);}}for(let[s,i]of r){let a=oi(s),c=a%256,l=a>>>31===1?-1:1;e[c]+=l*(1+Math.log(i));}let o=0;for(let s of e)o+=s*s;if(o=Math.sqrt(o),o===0)return e;for(let s=0;s<e.length;s++)
|
|
83
|
+
e[s]/=o;return e}function Br(t){return ii(t)}var jr=.72;function ai(t,e){let n=Math.min(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i++){let a=t[i],c=e[i];r+=a*c,o+=a*a,s+=c*c;}return o===0||s===0?0:r/(Math.sqrt(o)*Math.sqrt(s))}var ci=new Set(["no","not",
|
|
84
|
+
"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\xFAn","ning\
|
|
85
|
+
una","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),li=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what","whats","whi\
|
|
86
|
+
ch","who","whom","how","when","where","me","my","i","you","please","tell","give","show","find","do","does","did","be","that","this","it","with","as","at","by","from","about","into","over","than","then",
|
|
87
|
+
"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","estas","ese","e\
|
|
88
|
+
sa","eso","que","cual","cuales","quien","quienes","como","cuando","donde","dame","dime","quiero","necesito","puedes","podrias","favor","porfavor","gracias","me","mi","mis","tu","tus","su","sus","lo","\
|
|
89
|
+
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","aquests","a\
|
|
90
|
+
questes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function et(t){return (t.match(/\d[\d.,:/-]*/g)??
|
|
91
|
+
[]).map(e=>e.replace(/[.,:/-]+$/,""))}function wn(t,e){if(t.length!==e.length)return false;let n=new Map;for(let r of t)n.set(r,(n.get(r)??0)+1);for(let r of e){let o=n.get(r);if(!o)return false;n.set(r,o-1);}
|
|
92
|
+
return true}function tt(t){return t.split(/\s+/).filter(Boolean)}function nt(t){return t.filter(e=>ci.has(e.replace(/'/g,""))||e.endsWith("n't")).length}var ui=/^(system|user|assistant|tool):/;function Nr(t){
|
|
93
|
+
return t.split(`
|
|
94
|
+
`).map(e=>{let n=ui.exec(e);return n?{rol:n[1],texto:e.slice(n[0].length)}:{rol:"",texto:e}})}function di(t,e){let n=Nr(t),r=Nr(e);if(n.length!==r.length)return false;for(let o=0;o<n.length;o++)if(n[o].rol!==
|
|
95
|
+
r[o].rol||!pi(n[o].texto,r[o].texto))return false;return true}function pi(t,e){if(!wn(et(t),et(e)))return false;let n=tt(t),r=tt(e);if(nt(n)!==nt(r))return false;let o=l=>l.length>1&&!li.has(l)&&!/^\d/.test(l),s=new Set(
|
|
96
|
+
n.filter(o)),i=new Set(r.filter(o));if(s.size===0&&i.size===0)return true;let a=0;for(let l of s)i.has(l)&&a++;let c=s.size+i.size-a;return c===0?true:a/c>=.75}var $r=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;constructor(e={}){
|
|
97
|
+
let n=e.embed==null;this.embed=e.embed??Br,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??(n?jr:.9),this.acceptThreshold=e.acceptThreshold??.85,this.ttlMs=e.ttlMs,this.maxRecords=
|
|
98
|
+
e.maxRecords??5e3,this.now=e.now??(()=>Date.now());}async find(e){if(this.records.length===0)return null;let n=await this.embed(e.normalizedText),r=null;for(let o of this.records){if(o.tenantId!==e.tenantId||
|
|
99
|
+
o.authorizationScope!==e.authorizationScope||o.principal!==e.principal||o.knowledgeEpoch!==e.knowledgeEpoch||o.contractId!==e.contractId||o.model!==e.model||o.systemPromptHash!==e.systemPromptHash||o.
|
|
100
|
+
structuredDataHash!==e.structuredDataHash||o.locale!==e.locale||o.schemaVersion!==e.schemaVersion||o.safetyPolicyVersion!==e.safetyPolicyVersion||this.ttlMs!=null&&this.now()-o.storedAtMs>this.ttlMs)continue;
|
|
101
|
+
let s=ai(n,o.embedding);if(s<this.similarityThreshold||!di(e.normalizedText,o.query))continue;let i=this.verify?await this.verify(e.normalizedText,o.query):s,a=Math.min(s,i);a<this.acceptThreshold||(!r||
|
|
102
|
+
a>r.confidence)&&(r={record:o,similarity:s,verifierScore:i,confidence:a,ageMs:this.now()-o.storedAtMs});}return r}async store(e,n){let r=await this.embed(e.normalizedText);this.records.length>=this.maxRecords&&
|
|
103
|
+
this.records.shift(),this.records.push({embedding:r,query:e.normalizedText,answer:n,tenantId:e.tenantId,authorizationScope:e.authorizationScope,principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.
|
|
104
|
+
contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.structuredDataHash,locale:e.locale,schemaVersion:e.schemaVersion,safetyPolicyVersion:e.safetyPolicyVersion,storedAtMs:this.
|
|
105
|
+
now()});}invalidateEpoch(e){let n=0;for(let r=this.records.length-1;r>=0;r--)this.records[r].knowledgeEpoch===e&&(this.records.splice(r,1),n++);return n}get size(){return this.records.length}};var Sn=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}},
|
|
106
|
+
fi={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]??mi(t.normalizedText))?.trim();if(!n)return null;
|
|
107
|
+
let r=gi(n);return r===null||!Number.isFinite(r)?null:{text:hi(r),data:{value:r},resolver:"arithmetic"}}};function mi(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function hi(t){
|
|
108
|
+
return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function gi(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],r=[],o={"+":1,"-":1,
|
|
109
|
+
"*":2,"/":2,"%":2},s=a=>{let c=n.pop(),l=n.pop();if(l===void 0||c===void 0)return false;switch(a){case "+":return n.push(l+c),true;case "-":return n.push(l-c),true;case "*":return n.push(l*c),true;case "/":return c===
|
|
110
|
+
0?false:(n.push(l/c),true);case "%":return c===0?false:(n.push(l%c),true);default:return false}},i=true;for(let a of e)if(/^\d/.test(a))n.push(Number(a)),i=false;else if(a==="(")r.push(a),i=true;else if(a===")"){for(;r.length&&
|
|
111
|
+
r[r.length-1]!=="(";)if(!s(r.pop()))return null;if(r.pop()!=="(")return null;i=false;}else {if(i)return null;for(;r.length&&r[r.length-1]!=="("&&o[r[r.length-1]]>=o[a];)if(!s(r.pop()))return null;r.push(a),
|
|
112
|
+
i=true;}for(;r.length;){let a=r.pop();if(a==="("||!s(a))return null}return n.length===1?n[0]:null}function Fr(){return new Sn().register(fi)}var bi=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,zr=/\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,
|
|
113
|
+
xi=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,kt=class{classifier;maxRounds;constructor(e={}){this.
|
|
114
|
+
classifier=e.classifier,this.maxRounds=e.maxRounds??2;}classify(e){let n=e.original.retrieval?.mode,r=e.normalizedText;if((e.original.tools??[]).some(i=>i.risk==="write"||i.risk==="destructive")&&/\b(create|update|delete|send|pay|book|cancel|crea|actualiza|elimina|env[ií]a|paga)\b/i.
|
|
115
|
+
test(r))return me("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return me("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(xi.test(r)&&!zr.test(r))return me("NO_RETRIEVAL",
|
|
116
|
+
.8,"self-contained transformation",0);let s=this.classifier?.classify(r);return s&&s.confidence>=.75?me(s.executionClass,s.confidence,"local classifier",yi(s.executionClass,this.maxRounds)):n==="singl\
|
|
117
|
+
e"?me("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?me("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):bi.test(r)?me("MULTI_HOP_RETRIEVAL",.7,"comparison/compoun\
|
|
118
|
+
d question",Math.min(this.maxRounds,2)):zr.test(r)?me("SINGLE_RETRIEVAL",.65,"single factual lookup",1):me("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function yi(t,e){return t===
|
|
119
|
+
"SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function me(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var wt=class{maxTools;scoreIntentMatch;constructor(e={}){this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??vi;}passthrough(e){if(!e||e.length===0)return {tools:[],droppedIds:[],reason:"\
|
|
120
|
+
no tools provided",setIsStable:true};let n=e.slice(0,this.maxTools),r=e.slice(this.maxTools).map(o=>o.id);return {tools:n,droppedIds:r,reason:`router off: caller tools passed through unfiltered (${n.length}\
|
|
121
|
+
/${e.length}, capped at maxTools=${this.maxTools}; risk gating is the caller's responsibility while routing is off)`,setIsStable:true}}select(e,n,r){if(!n||n.length===0)return {tools:[],droppedIds:[],reason:"\
|
|
122
|
+
no tools provided",setIsStable:true};let o=r==="TOOL_ACTION",s=n.filter(p=>o||p.risk==="read"),i=p=>o&&p.risk!=="read",a=s.filter(p=>!i(p)),c=s.filter(p=>i(p)),l=c.map(p=>({tool:p,score:this.scoreIntentMatch(
|
|
123
|
+
e,p)})).sort((p,g)=>g.score-p.score).map(p=>p.tool),u=a.map(p=>({tool:p,score:this.scoreIntentMatch(e,p)})).filter(p=>p.score>0).sort((p,g)=>g.score-p.score).map(p=>p.tool),f=[...l.slice(0,this.maxTools),
|
|
124
|
+
...u.slice(0,Math.max(0,this.maxTools-c.length))].map(p=>({tool:p})).map(p=>p.tool).sort((p,g)=>p.id<g.id?-1:p.id>g.id?1:0),m=new Set(f.map(p=>p.id)),h=n.filter(p=>!m.has(p.id)).map(p=>p.id);return {tools:f,
|
|
125
|
+
droppedIds:h,reason:`selected ${f.length}/${n.length} by intent match (writes ${o?"allowed":"blocked"})`,setIsStable:h.length===0}}};function vi(t,e){let n=xt(t),r=0;for(let o of e.intents){let s=xt(o);
|
|
126
|
+
s&&(n.includes(s)?r+=2:s.split(/\s+/).some(i=>i.length>3&&n.includes(i))&&(r+=1));}return r}function ki(t){let e=new Set,n=[];for(let r of t){let o=r.hash??Si(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function wi(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((i,a)=>(a.score??
|
|
127
|
+
0)-(i.score??0));if(r.length<=n)return r;let o=r[0]?.score??0;if(o<=0)return r.slice(0,e.maxDocuments);let s=[];for(let i of r){let a=(i.score??0)/o;if(s.length<n||a>=.4&&s.length<e.maxDocuments)s.push(
|
|
128
|
+
i);else break}return s}async function Vr(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};
|
|
129
|
+
let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,r=[];for(let i=0;i<n;i++){let a=await e.retriever.retrieve(t.query,t.maxDocuments*2);r.push(...a);}let o=r.length;r=ki(r),e.reranker&&
|
|
130
|
+
(r=await e.reranker.rerank(t.query,r));let s=wi(r,{maxDocuments:t.maxDocuments});return {docs:s,rounds:n,retrievedCount:o,keptCount:s.length}}function Si(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function Pl(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function Ll(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{
|
|
131
|
+
...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&Ci(o)?Object.assign(n.userPreferences,
|
|
132
|
+
o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let s=Ei(n,r);s?s.push(...o.map(String)):n.confirmedFacts[r]=o;}for(let r of e.remove??[])delete n.confirmedFacts[r],delete n.userPreferences[r],
|
|
133
|
+
Ri(n,r);return n}function Ml(t){let e=t.rawTurns??3,n=[],r=Ti(t.state);r&&n.push({role:"system",content:`Conversation state:
|
|
134
|
+
${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function Ti(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`fa\
|
|
135
|
+
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(
|
|
136
|
+
"; ")}`),t.openItems.length&&e.push(`open: ${t.openItems.join("; ")}`),e.join(`
|
|
137
|
+
`)}function Ei(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 Ri(t,e){
|
|
138
|
+
for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function Ci(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ur={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function qr(t,e={}){let n=e.delimiter??",",r=e.indent??" ",s=t.split(`
|
|
139
|
+
`).filter(c=>c.trim().length>0).map(c=>({indent:Ii(c,r),content:c.slice(Hr(c,r))}));if(s.length===0)return {};let i=s[0];if(i.indent===0){let c=i.content.match(/^\[(\d+)\]\{(.*)\}:\s*$/);if(c){let u=$e(
|
|
140
|
+
c[2],n),d=Number(c[1]),f=[];for(let m=0,h=1;m<d&&h<s.length;m++,h++){let p=s[h];if(p.indent!==1)break;let g=$e(p.content,n),x={};u.forEach((b,y)=>{x[b]=rt(g[y]??"null");}),f.push(x);}return f}let l=i.content.
|
|
141
|
+
match(/^\[(\d+)\]:\s*(.*)$/);if(l){let u=l[2];return Number(l[1])===0||u.trim()===""?[]:$e(u,n).map(rt)}}let[a]=Kr(s,0,0,n);return a}function Hr(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}
|
|
142
|
+
function Ii(t,e){return Hr(t,e)/e.length}function Kr(t,e,n,r){let o={},s=e;for(;s<t.length;){let i=t[s];if(i.indent<n)break;if(i.indent>n){s++;continue}let a=Oi(i.content,r);if(!a){s++;continue}let{key:c,
|
|
143
|
+
kind:l}=a;if(l.type==="scalar")o[c]=l.value,s++;else if(l.type==="inlineArray")o[c]=l.values,s++;else if(l.type==="emptyArray")o[c]=[],s++;else if(l.type==="table"){let u=[];s++;for(let d=0;d<l.count&&
|
|
144
|
+
s<t.length;d++,s++){let f=t[s];if(f.indent!==n+1)break;let m=$e(f.content,r),h={};l.columns.forEach((p,g)=>{h[p]=rt(m[g]??"null");}),u.push(h);}o[c]=u;}else {let[u,d]=Kr(t,s+1,n+1,r);o[c]=u,s=d;}}return [o,
|
|
145
|
+
s]}function Oi(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:St(n[1]),kind:{type:"table",count:Number(n[2]),columns:$e(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){
|
|
146
|
+
let s=Number(r[2]),i=r[3];return s===0||i.trim()===""?{key:St(r[1]),kind:{type:"emptyArray"}}:{key:St(r[1]),kind:{type:"inlineArray",values:$e(i,e).map(rt)}}}let o=t.match(/^([^:]+):\s*(.*)$/);if(o){let s=St(
|
|
147
|
+
o[1]),i=o[2];return i===""?{key:s,kind:{type:"object"}}:{key:s,kind:{type:"scalar",value:rt(i)}}}return null}function $e(t,e){let n=[],r="",o=false;for(let s=0;s<t.length;s++){let i=t[s];o?i==='"'?t[s+1]===
|
|
148
|
+
'"'?(r+='"',s++):o=false:r+=i:i==='"'?o=true:i===e?(n.push(r),r=""):r+=i;}return n.push(r),n.map(s=>s.trim())}function rt(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,
|
|
149
|
+
'"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function St(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,
|
|
150
|
+
'"'):e}function _i(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return Rn(null,t,0,o,n,r),o.join(`
|
|
151
|
+
`)}function Rn(t,e,n,r,o,s){let i=s.repeat(n),a=t===null?"":`${Ai(t)}`;if(Array.isArray(e)){Di(a,e,n,r,o,s);return}if(En(e)){t!==null&&r.push(`${i}${a}:`);let c=t===null?n:n+1;for(let[l,u]of Object.entries(
|
|
152
|
+
e))Rn(l,u,c,r,o,s);return}r.push(`${i}${a}: ${Tt(e,o)}`);}function Di(t,e,n,r,o,s){let i=s.repeat(n),a=t===""?"":t;if(e.length===0){r.push(`${i}${a}[0]:`);return}if(e.every(Tn)){let d=e.map(f=>Tt(f,o)).
|
|
153
|
+
join(o);r.push(`${i}${a}[${e.length}]: ${d}`);return}let c=Et(e);if(c){r.push(`${i}${a}[${e.length}]{${c.join(o)}}:`);let d=s.repeat(n+1);for(let f of e){let m=c.map(h=>Tt(f[h],o)).join(o);r.push(`${d}${m}`);}
|
|
154
|
+
return}r.push(`${i}${a}[${e.length}]:`);let l=n+1,u=s.repeat(l);for(let d of e)if(Tn(d))r.push(`${u}- ${Tt(d,o)}`);else {let f=[];Rn(null,d,0,f,o,s);let[m,...h]=f;r.push(`${u}- ${m??""}`);for(let p of h)
|
|
155
|
+
r.push(`${u}${s}${p}`);}}function Et(t){if(t.length===0)return null;let e=t[0];if(!En(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(!En(
|
|
156
|
+
o))return null;let s=Object.keys(o);if(s.slice().sort().join("\0")!==r)return null;for(let i of s)if(!Tn(o[i]))return null}return n}function Ai(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:Jr(t)}function Tt(t,e){
|
|
157
|
+
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(`
|
|
158
|
+
`)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?Jr(n):n}function Jr(t){return `"${t.replace(/"/g,'""')}"`}function Tn(t){return t===null||typeof t=="string"||typeof t==
|
|
159
|
+
"number"||typeof t=="boolean"}function En(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Pi="Data is the compact encoder: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; ea\
|
|
160
|
+
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 Li(t={}){return {format:"compact-rows",supports(){return true},
|
|
161
|
+
encode(e){return _i(e,t)},instruction(){return Pi},decode(e){return qr(e,t)}}}var Wr=Li();var Yr={format:"csv",supports(t){return Array.isArray(t)&&Et(t)!==null},encode(t){let e=t,n=Et(e),r=n.map(Gr).join(","),o=e.map(s=>n.map(i=>Gr(s[i])).join(","));return [r,...o].join(`
|
|
162
|
+
`)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function Gr(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,
|
|
163
|
+
'""')}"`:e}var Rt=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[Ur,Wr,Yr],this.minSavingsTokens=e.minimumSavingsTokens??
|
|
164
|
+
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(
|
|
165
|
+
e))continue;let u=l.encode(e);if(l.format!=="json-compact"&&!Mi(l,u,e))continue;let d=l.instruction(e),f=this.tokenizer.count(u,r),m=d?this.tokenizer.count(d,r):0,h=this.qualityPenalty(n.model??"",l.format);
|
|
166
|
+
o.push({format:l.format,encoded:u,instruction:d,payloadTokens:f,instructionTokens:m,penalty:h,total:f+m+h});}let s=o.find(l=>l.format==="json-compact"),i={};for(let l of o)i[l.format]=l.total;if(!s){let l=o[0];
|
|
167
|
+
return l?Zr(l,i,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:i,instructionOverheadTokens:0,reason:"no serializer supported payload; defa\
|
|
168
|
+
ulted to JSON"}}let a=s,c="json baseline (no challenger cleared thresholds)";for(let l of o){if(l.format==="json-compact")continue;let u=s.total-l.total,d=s.total===0?0:u/s.total;u>=this.minSavingsTokens&&
|
|
169
|
+
d>=this.minSavingsRatio&&l.total<a.total&&(a=l,c=`${l.format} saved ${u} tokens (${(d*100).toFixed(1)}%) vs json`);}return Zr(a,i,c)}};function Mi(t,e,n){if(!t.decode)return false;try{return Cn(t.decode(e),
|
|
170
|
+
n)}catch{return false}}function Cn(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.
|
|
171
|
+
length)return false;for(let i=0;i<t.length;i++)if(!Cn(t[i],e[i]))return false;return true}let o=Object.keys(t),s=Object.keys(e);if(o.length!==s.length)return false;for(let i of o)if(!Object.prototype.hasOwnProperty.
|
|
172
|
+
call(e,i)||!Cn(t[i],e[i]))return false;return true}function Zr(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function ae(t,e,n="$"){let r=[];return In(t,e,n,r),{valid:r.length===0,errors:r}}function Bi(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
|
|
173
|
+
string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function In(t,e,n,r){switch(e.enum&&!e.enum.some(s=>zi(s,t))&&r.push({path:n,message:"value not in enum"}),
|
|
174
|
+
e.type??Bi(t)){case "object":ji(t,e,n,r);break;case "array":Ni(t,e,n,r);break;case "string":$i(t,e,n,r);break;case "number":case "integer":Fi(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,
|
|
175
|
+
message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function ji(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,
|
|
176
|
+
message:"expected object"});return}let o=t;for(let s of e.required??[])s in o||r.push({path:`${n}.${s}`,message:"missing required property"});if(e.additionalProperties===false&&e.properties){let s=new Set(
|
|
177
|
+
Object.keys(e.properties));for(let i of Object.keys(o))s.has(i)||r.push({path:`${n}.${i}`,message:"additional property not allowed"});}if(e.properties)for(let[s,i]of Object.entries(e.properties))s in o&&
|
|
178
|
+
In(o[s],i,`${n}.${s}`,r);}function Ni(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\
|
|
179
|
+
ms ${e.maxItems}`}),e.minItems!=null&&t.length<e.minItems&&r.push({path:n,message:`array below minItems ${e.minItems}`}),e.items&&t.forEach((o,s)=>In(o,e.items,`${n}[${s}]`,r));}function $i(t,e,n,r){if(typeof t!=
|
|
180
|
+
"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.
|
|
181
|
+
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\
|
|
182
|
+
sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function Fi(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}
|
|
183
|
+
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.
|
|
184
|
+
minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function zi(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var Ct=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 On(
|
|
185
|
+
e,n,r),r}};function On(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??{}))On(o,`${e}\
|
|
186
|
+
.${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&On(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: s\
|
|
187
|
+
tring should set maxLength or use an enum`);}function Xr(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\
|
|
188
|
+
ate + repair"}}function ou(t=()=>true){return {id:"provider-native",supports:t}}function _n(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;
|
|
189
|
+
return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function du(t){return {async compress(e){let n=e.protectedSpans??[],r=e.text,o=[];n.forEach((c,l)=>{
|
|
190
|
+
let u=`\0PROTECT_${l}\0`;o.push({token:u,span:c}),r=r.split(c.text).join(u);});let s=await t.compress({text:r,...e.targetRatio!=null?{targetRatio:e.targetRatio}:{}}),i=s.compressed,a=true;for(let{token:c,
|
|
191
|
+
span:l}of o){if(!i.includes(c)){a=false;break}i=i.split(c).join(l.text);}return a?{...s,compressed:i,protectedSpans:n.length,fidelityPassed:true}:{compressed:e.text,originalTokens:s.originalTokens,compressedTokens:s.
|
|
192
|
+
originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var pu={async compress(t){return {compressed:t.text,originalTokens:0,
|
|
193
|
+
compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function Qr(t,e){let n=i=>i.toLowerCase().replace(/[.,;:!¡?¿()[\]{}"«»…]/g,
|
|
194
|
+
" ").replace(/\s+/g," ").trim(),o=n((i=>{let a=new Set,c=[];for(let l of i.split(`
|
|
195
|
+
`)){let u=l.trim();u&&a.has(u)||(u&&a.add(u),c.push(l));}return c.join(`
|
|
196
|
+
`)})(t)),s=n(e);return !(!wn(et(o),et(s))||nt(tt(o))!==nt(tt(s)))}var eo=new WeakSet;function to(t){eo.add(t);}var Dn=class{id="mock";options;constructor(e={}){this.options=e,to(this);}async generate(e){let n=e.messages.map(a=>a.content).join(`
|
|
197
|
+
`),r=je.count(n);if(e.tools&&e.tools.length>0){let a=JSON.stringify(e.tools.map(c=>({name:c.id,description:c.description,parameters:c.parameters??{}})));r+=je.count(a);}let o,s=false;if(e.schema){let a=this.
|
|
198
|
+
options.data??It(e.schema);o=JSON.stringify(a),s=true;}else o=this.options.answer??`mock-response(${e.model})`;let i=Math.min(e.maxOutputTokens??Number.MAX_SAFE_INTEGER,je.count(o));return {text:o,usage:{
|
|
199
|
+
inputTokens:r,outputTokens:i,...this.options.cachedInputTokens!=null?{cachedInputTokens:this.options.cachedInputTokens}:{}},structuredNatively:s}}};function It(t){if(t.enum&&t.enum.length>0)return t.enum[0];
|
|
200
|
+
switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?It(r):null;}for(let[n,r]of Object.entries(t.properties??{}))n in e||(e[n]=It(r));return e}case "array":return t.
|
|
201
|
+
items?[It(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 yu(t){return new Dn(t)}var Vi={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},Ot="flex";function ro(t){if(t==null||t==="")return null;let e=Vi[t];return e==null?{servido:t,factor:null,conDescuento:false}:
|
|
202
|
+
{servido:t,factor:e,conDescuento:e<1}}function oo(t,e){return !t||t.factor==null||!t.conDescuento||!Number.isFinite(e)||e<=0?null:e*(1-t.factor)}var Ui="slower and variable: OpenAI publishes no latency\
|
|
203
|
+
commitment for the flex tier. What IS documented is the failure shape \u2014 the default SDK timeout is 10 minutes and a request that exceeds it returns 408, and when flex capacity is short the request re\
|
|
204
|
+
turns 429 and is not charged. Do not put a deferrable request on a user-facing path.",qi="unchanged: this provider has no cheaper synchronous processing tier, so nothing was asked for and the request \
|
|
205
|
+
was scheduled exactly as it would have been.",so="this provider has no cheaper synchronous processing tier, so the request was sent unchanged and nothing is credited; on this provider the deferred dis\
|
|
206
|
+
count lives only in the asynchronous batch API, which is not a request/response call";function io(t){return t==null||t===""?qi:t===Ot?Ui:`unknown: this layer has no published latency statement for the\
|
|
207
|
+
"${t}" tier.`}var ao=new Set;function G(t,e){ao.has(t)||(ao.add(t),console.warn(e));}function De(t){if(t==null||typeof t!="object")return true;let e=t,n=e.properties;if(n&&typeof n=="object"){if(e.additionalProperties!==false)return false;let o=Object.keys(n),s=Array.isArray(e.required)?e.required.
|
|
208
|
+
map(String):[];if(o.some(i=>!s.includes(i)))return false;for(let i of Object.values(n))if(!De(i))return false}if(e.items!==void 0&&!De(e.items))return false;for(let o of ["anyOf","oneOf","allOf"]){let s=e[o];if(Array.
|
|
209
|
+
isArray(s)&&s.some(i=>!De(i)))return false}let r=e.$defs??e.definitions;return !(r&&typeof r=="object"&&Object.values(r).some(o=>!De(o)))}function Hi(t){return !/response_format/i.test(t)||/invalid schema/i.
|
|
210
|
+
test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.test(t)}function Ki(t){return `Respond with a single JSON object and nothing else: no prose, no\
|
|
211
|
+
explanation, no markdown code fences. The object must validate against this JSON Schema:
|
|
212
|
+
`+JSON.stringify(t)}var co=class{id;opts;fetchImpl;sinResponseFormat=new Set;constructor(e){this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch;}async generate(e){let n=this.
|
|
213
|
+
opts.stripProviderPrefix?e.model.replace(/^[^/]+\//,""):e.model,r=e.schema!=null&&!this.sinResponseFormat.has(n),o=await this.enviar(n,e,r);if(!o.ok&&o.status===400&&r){let s=await lo(o);if(!Hi(s))throw new Error(
|
|
214
|
+
`provider ${o.status}: ${s}`);this.sinResponseFormat.add(n),G(`sin-response-format:${n}`,`[bvsala] El modelo "${n}" rechaza \`response_format\` con un 400: no tiene structured outputs. Se repite la peti\
|
|
215
|
+
ci\xF3n pidiendo el JSON por prompt (una sola vez: el modelo queda anotado y las siguientes van directas). El esquema sigue viajando y el layer sigue validando, pero la garant\xEDa la da el layer, no el pro\
|
|
216
|
+
veedor, y el informe lo dice: \`constraints.backend: "none"\`. Para recuperar la garant\xEDa nativa, usa un modelo con structured outputs (gpt-4o o posterior).`),r=false,o=await this.enviar(n,e,false);}if(!o.
|
|
217
|
+
ok){let s=await lo(o);throw new Error(`provider ${o.status}: ${s}`)}return this.leer(o,e,r)}async enviar(e,n,r){let o=n.messages.map(i=>i.role==="tool"?{role:"tool",content:i.content,tool_call_id:i.toolCallId??
|
|
218
|
+
i.metadata?.tool_call_id,...i.name?{name:i.name}:{}}:i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0?{role:"assistant",content:i.content||null,tool_calls:i.toolCalls.map((a,c)=>({id:a.id??`cal\
|
|
219
|
+
l_${c}`,type:"function",function:{name:a.name,arguments:a.arguments}}))}:{role:i.role,content:i.content});n.schema&&!r&&o.push({role:"system",content:Ki(n.schema)});let s={model:e,messages:o};if(n.maxOutputTokens!=
|
|
220
|
+
null&&(s.max_tokens=n.maxOutputTokens),n.temperature!=null&&(s.temperature=n.temperature),n.seed!=null&&(s.seed=n.seed),n.promptCacheKey!=null&&(s.prompt_cache_key=n.promptCacheKey),n.deferrable===true&&
|
|
221
|
+
(s.service_tier=Ot),n.schema&&r){let i=De(n.schema);i||G("strict-incompatible","[bvsala] El contrato de respuesta no cumple el modo `strict` de OpenAI (en strict, `required` debe listar TODAS las clav\
|
|
222
|
+
es de `properties`, y todo objeto necesita `additionalProperties: false`). Se env\xEDa el esquema con `strict: false`: el modelo sigue guiado y el layer sigue validando, pero la garant\xEDa la da el layer, \
|
|
223
|
+
no el proveedor. Para recuperarla, haz obligatorias todas las claves del contrato."),s.response_format={type:"json_schema",json_schema:{name:"bvsala_contract",schema:n.schema,strict:i}};}return n.tools&&
|
|
224
|
+
n.tools.length>0&&(s.tools=n.tools.map(i=>({type:"function",function:{name:i.id,...i.description?{description:i.description}:{},parameters:i.parameters??{type:"object",properties:{}}}}))),await this.fetchImpl(
|
|
225
|
+
`${this.opts.baseUrl.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.headers},
|
|
226
|
+
body:JSON.stringify(s)})}async leer(e,n,r){let o=await e.json(),s=o.choices?.[0]?.message,i=s?.content??"",a=(s?.tool_calls??[]).map(p=>({...p.id?{id:p.id}:{},name:p.function?.name??"",arguments:p.function?.
|
|
227
|
+
arguments??""})).filter(p=>p.name!==""),c=o.usage??{},l=c.prompt_tokens??0,u=c.completion_tokens??0,d=typeof c.prompt_tokens!="number",f=typeof c.completion_tokens!="number";if(this.opts.requireUsage&&
|
|
228
|
+
(d||f))throw new Error(`provider returned incomplete usage (prompt=${c.prompt_tokens??"absent"}, completion=${c.completion_tokens??"absent"}); cannot measure cost. For gateways/streaming, ensure usage\
|
|
229
|
+
reporting is enabled.`);let m=o.choices?.[0]?.finish_reason,h=typeof o.service_tier=="string"&&o.service_tier!==""?o.service_tier:void 0;return {text:i,...a.length>0?{toolCalls:a}:{},...m?{finishReason:m}:
|
|
230
|
+
{},...h?{servedServiceTier:h}:{},...n.deferrable===true?{requestedServiceTier:Ot}:{},usage:{inputTokens:l,outputTokens:u,...c.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:c.prompt_tokens_details.
|
|
231
|
+
cached_tokens}:{}},structuredNatively:n.schema!=null&&r,raw:o}}};async function lo(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function uo(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:
|
|
232
|
+
`+JSON.stringify(t)}var po=4,Fe="bvsala_contract",fo=class{id;opts;fetchImpl;constructor(e={}){this.opts=e,this.id=`anthropic:${e.baseUrl??"https://api.anthropic.com/v1"}`,this.fetchImpl=e.fetchImpl??fetch;}async generate(e){
|
|
233
|
+
let n=this.construirCuerpo(e),r=(this.opts.baseUrl??"https://api.anthropic.com/v1").replace(/\/$/,""),o=await this.fetchImpl(`${r}/messages`,{method:"POST",headers:{"content-type":"application/json","\
|
|
234
|
+
anthropic-version":this.opts.apiVersion??"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},body:JSON.stringify(n.body)});if(!o.ok)throw new Error(`provider ${o.status}\
|
|
235
|
+
: ${await Gi(o)}`);return this.leer(o,e,n.contratoNativo)}construirCuerpo(e){let{system:n,messages:r,prefijoEnMensajes:o,prefijoEnSystem:s}=Ji(e);if(r.length===0)throw new Error("anthropic: the reques\
|
|
236
|
+
t has no user/assistant message. The Messages API needs at least one, and system prompts travel in the `system` field \u2014 they do not count.");let i=(e.tools??[]).map(u=>({name:u.id,...u.description?
|
|
237
|
+
{description:u.description}:{},input_schema:u.parameters??{type:"object",properties:{}}})),a=false,c=false;if(e.schema){let u=i.length>0,d=i.some(m=>m.name===Fe),f=De(e.schema);d?(n.push({type:"text",text:uo(
|
|
238
|
+
e.schema)}),G("anthropic-contrato-nombre-ocupado",`[bvsala] One of your tools is already named \`${Fe}\`, so the output contract cannot travel as a tool without colliding with it (duplicate tool names \
|
|
239
|
+
are a provider error). The schema is sent as prompt text instead, which is measurably more expensive on this API. Rename that tool to get the cheaper path.`)):(!f&&!u&&G("anthropic-strict-incompatible",
|
|
240
|
+
"[bvsala] El contrato de respuesta no cumple el modo `strict` (en strict, `required` debe listar TODAS las claves de `properties`, y todo objeto necesita `additionalProperties: false`). Se env\xEDa el es\
|
|
241
|
+
quema sin `strict`: el modelo sigue guiado y el layer sigue validando, pero la garant\xEDa la da el layer, no el proveedor."),a=f&&!u,i.push({name:Fe,description:u?"Return the final answer in the requ\
|
|
242
|
+
ired shape. Use the other tools first if you need data; call this one instead of writing the answer as text.":"Return the final answer in the required shape.",input_schema:e.schema,...a?{strict:true}:{}}),
|
|
243
|
+
u&&(c=this.opts.forceAnswerThroughTool!==false,G("anthropic-contrato-con-herramientas","[bvsala] This request carries BOTH your tools and an output contract. On Anthropic's Messages API a specific shape \
|
|
244
|
+
is only GUARANTEED by forcing that exact tool, and forcing ours would leave the model unable to call yours. The contract travels as one extra tool"+(c?' and the request is sent with `tool_choice: {typ\
|
|
245
|
+
e: "any"}`, so the model must answer through SOME tool \u2014 yours or the contract \u2014 and can no longer reply in prose. Your tool turn is untouched. The guarantee is still the layer\'s, not the provider\'s (\
|
|
246
|
+
`constraints.backend: "none"`), because the model may pick one of your tools and defer the final answer to the next turn.':", not forced (`forceAnswerThroughTool: false`). The guarantee is the layer's\
|
|
247
|
+
, not the provider's (`constraints.backend: \"none\"`), and if the model answers in prose the layer pays a second full call to repair it \u2014 on this API that second call re-pays the whole tool-use overhea\
|
|
248
|
+
d.")+" Dropping either the tools or the contract from this request is what makes the guarantee free.")));}let l={model:e.model,max_tokens:e.maxOutputTokens??this.opts.defaultMaxOutputTokens??4096,messages:r};
|
|
249
|
+
return n.length>0&&(l.system=n),e.temperature!=null&&(l.temperature=e.temperature),i.length>0&&(l.tools=i),a?l.tool_choice={type:"tool",name:Fe}:c&&(l.tool_choice={type:"any"}),e.deferrable===true&&G("a\
|
|
250
|
+
nthropic-sin-tier-diferible","[bvsala] Esta petici\xF3n se declar\xF3 diferible, pero la API de Mensajes de Anthropic NO tiene un tier s\xEDncrono m\xE1s barato: su `service_tier` elige entre capacidad prioritari\
|
|
251
|
+
a (m\xE1s cara) y est\xE1ndar, no un flex. La petici\xF3n sale sin cambios y el informe no acredita ning\xFAn descuento. El 50% por diferir existe en la Message Batches API, que es as\xEDncrona y no cabe en una llam\
|
|
252
|
+
ada de petici\xF3n/respuesta."),this.marcarCache(e,n,r,o,s),{body:l,contratoNativo:a}}marcarCache(e,n,r,o,s){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return;let i=Math.min(this.opts.maxCacheBreakpoints??
|
|
253
|
+
po,po);if(i<=0)return;let a=s>0?n[s-1]:void 0;if(a&&(a.cache_control={type:"ephemeral"},i-=1),i>0&&o>0){let c=r[Math.min(o,r.length)-1],l=c?.content[c.content.length-1];l&&(l.cache_control={type:"ephe\
|
|
254
|
+
meral"});}}async leer(e,n,r){let o=await e.json(),s=o.content??[],i=s.filter(b=>b.type==="text").map(b=>b.text??"").join(""),a=s.filter(b=>b.type==="tool_use"&&b.name!==Fe).map(b=>({...b.id?{id:b.id}:{},
|
|
255
|
+
name:b.name??"",arguments:JSON.stringify(b.input??{})})).filter(b=>b.name!==""),c=s.find(b=>b.type==="tool_use"&&b.name===Fe),l=c?JSON.stringify(c.input??{}):i,u=o.usage??{},d=u.cache_read_input_tokens,
|
|
256
|
+
f=u.cache_creation_input_tokens,m=(u.input_tokens??0)+(f??0)+(d??0),h=u.output_tokens??0,p=typeof u.input_tokens!="number",g=typeof u.output_tokens!="number";if(this.opts.requireUsage&&(p||g))throw new Error(
|
|
257
|
+
`provider returned incomplete usage (input=${u.input_tokens??"absent"}, output=${u.output_tokens??"absent"}); cannot measure cost.`);let x=typeof u.service_tier=="string"&&u.service_tier!==""?u.service_tier:
|
|
258
|
+
void 0;return {text:l,...a.length>0?{toolCalls:a}:{},...o.stop_reason?{finishReason:Wi(o.stop_reason)}:{},...x?{servedServiceTier:x}:{},usage:{inputTokens:m,outputTokens:h,...d!=null?{cachedInputTokens:d}:
|
|
259
|
+
{},...f!=null?{cacheWriteInputTokens:f}:{}},structuredNatively:n.schema!=null&&r,raw:o}}};function Ji(t){let e=[],n=[],r=t.stablePrefixMessages??0,o=0,s=0,i=true;return t.messages.forEach((a,c)=>{if(a.role===
|
|
260
|
+
"system"&&i){e.push({type:"text",text:a.content}),c<r&&(s=e.length);return}i=false,n.push({role:a.role==="assistant"?"assistant":"user",content:[{type:"text",text:a.content}]}),c<r&&(o=n.length);}),n.length>
|
|
261
|
+
0&&n[0].role==="assistant"&&(n.unshift({role:"user",content:[{type:"text",text:"(continue)"}]}),o>0&&(o+=1)),{system:e,messages:n,prefijoEnMensajes:o,prefijoEnSystem:s}}function Wi(t){switch(t){case "e\
|
|
262
|
+
nd_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "tool_calls";case "refusal":return "content_filter";default:return t}}async function Gi(t){try{return (await t.text()).slice(0,500)}catch{
|
|
263
|
+
return "<no body>"}}var ot=class{events=[];start;now;constructor(e=()=>Date.now()){this.now=e,this.start=e();}record(e,n,r){this.events.push({stage:e,outcome:n,...r?{detail:r}:{},atMs:this.now()-this.start});}elapsed(){return this.
|
|
264
|
+
now()-this.start}all(){return this.events}};var Ae=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function An(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function _t(t,e=""){if(typeof t!="number"){let n=e&&
|
|
265
|
+
`"${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 re(t,e,n=""){
|
|
266
|
+
let r=An(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){let i=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):
|
|
267
|
+
new TypeError(l)}return t}function Pn(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 ho(t,e){re(t,void 0,"digestInt\
|
|
268
|
+
o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function st(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function Dt(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var go=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Yi=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function At(t){if(re(t),go)return t.toHex();
|
|
269
|
+
let e="";for(let n=0;n<t.length;n++)e+=Yi[t[n]];return e}var he={_0:48,_9:57,A:65,F:70,a:97,f:102};function mo(t){if(t>=he._0&&t<=he._9)return t-he._0;if(t>=he.A&&t<=he.F)return t-(he.A-10);if(t>=he.a&&
|
|
270
|
+
t<=he.f)return t-(he.a-10)}function it(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(go)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?
|
|
271
|
+
new RangeError(o.message):o}let e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){let i=mo(t.charCodeAt(
|
|
272
|
+
s)),a=mo(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a;}return r}function Ln(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];re(o),e+=o.length;}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let s=t[r];n.set(s,o),o+=s.length;}return n}function bo(t,e={}){let n=(o,s)=>t(s).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function xo(t=32){
|
|
273
|
+
_t(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(
|
|
274
|
+
`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var yo=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var Pt=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(e,n,r,o){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=
|
|
275
|
+
new Uint8Array(e),this.view=Dt(this.buffer);}update(e){Pn(this),re(e);let{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Dt(e);for(;o<=s-i;i+=
|
|
276
|
+
o)this.process(c,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){Pn(this),
|
|
277
|
+
ho(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;n[i++]=128,st(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let d=i;d<o;d++)n[d]=0;r.setBigUint64(
|
|
278
|
+
o-8,BigInt(this.length*8),s),this.process(r,0);let a=Dt(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\
|
|
279
|
+
ha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s);}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||=new this.
|
|
280
|
+
constructor,e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};var H=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Lt=BigInt(4294967295),vo=BigInt(32);function Zi(t,e=false){return e?{h:Number(t&Lt),l:Number(t>>vo&Lt)}:{h:Number(t>>vo&Lt)|0,l:Number(t&Lt)|0}}function ko(t,e=false){let n=t.length,r=new Uint32Array(n),
|
|
281
|
+
o=new Uint32Array(n);for(let s=0;s<n;s++){let{h:i,l:a}=Zi(t[s],e);[r[s],o[s]]=[i,a];}return [r,o]}var Mn=(t,e,n)=>t>>>n,Bn=(t,e,n)=>t<<32-n|e>>>n,Pe=(t,e,n)=>t>>>n|e<<32-n,Le=(t,e,n)=>t<<32-n|e>>>n,at=(t,e,n)=>t<<64-n|e>>>n-32,ct=(t,e,n)=>t>>>n-32|e<<64-n;function ce(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var wo=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),So=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,To=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Eo=(t,e,n,r,o)=>e+
|
|
282
|
+
n+r+o+(t/2**32|0)|0,Ro=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Co=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0;var Io=ko(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
|
|
283
|
+
"0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
|
|
284
|
+
8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
|
|
285
|
+
0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
|
|
286
|
+
c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0\
|
|
287
|
+
x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
|
|
288
|
+
efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
|
|
289
|
+
eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
|
|
290
|
+
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Qi=Io[0],ea=Io[1],Te=new Uint32Array(80),Ee=new Uint32Array(80),jn=class extends Pt{constructor(e){
|
|
291
|
+
super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:m,Gl:h,Hh:p,Hl:g}=this;return [e,n,r,o,s,i,a,c,l,u,d,f,m,h,p,g]}set(e,n,r,o,s,i,a,c,l,u,d,f,m,h,p,g){this.Ah=
|
|
292
|
+
e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=m|0,this.Gl=h|0,this.Hh=p|0,this.Hl=g|0;}process(e,n){for(let y=0;y<
|
|
293
|
+
16;y++,n+=4)Te[y]=e.getUint32(n),Ee[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){let E=Te[y-15]|0,C=Ee[y-15]|0,O=Pe(E,C,1)^Pe(E,C,8)^Mn(E,C,7),T=Le(E,C,1)^Le(E,C,8)^Bn(E,C,7),D=Te[y-2]|0,R=Ee[y-2]|0,S=Pe(
|
|
294
|
+
D,R,19)^at(D,R,61)^Mn(D,R,6),L=Le(D,R,19)^ct(D,R,61)^Bn(D,R,6),v=To(T,L,Ee[y-7],Ee[y-16]),w=Eo(v,O,S,Te[y-7],Te[y-16]);Te[y]=w|0,Ee[y]=v|0;}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:m,Fl:h,
|
|
295
|
+
Gh:p,Gl:g,Hh:x,Hl:b}=this;for(let y=0;y<80;y++){let E=Pe(d,f,14)^Pe(d,f,18)^at(d,f,41),C=Le(d,f,14)^Le(d,f,18)^ct(d,f,41),O=d&m^~d&p,T=f&h^~f&g,D=Ro(b,C,T,ea[y],Ee[y]),R=Co(D,x,E,O,Qi[y],Te[y]),S=D|0,
|
|
296
|
+
L=Pe(r,o,28)^at(r,o,34)^at(r,o,39),v=Le(r,o,28)^ct(r,o,34)^ct(r,o,39),w=r&s^r&a^s&a,_=o&i^o&c^i&c;x=p|0,b=g|0,p=m|0,g=h|0,m=d|0,h=f|0,{h:d,l:f}=ce(l|0,u|0,R|0,S|0),l=a|0,u=c|0,a=s|0,c=i|0,s=r|0,i=o|0;
|
|
297
|
+
let P=wo(S,v,_);r=So(P,R,L,w),o=P|0;}(({h:r,l:o}=ce(this.Ah|0,this.Al|0,r|0,o|0))),{h:s,l:i}=ce(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ce(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ce(this.Dh|0,this.Dl|0,l|0,
|
|
298
|
+
u|0),{h:d,l:f}=ce(this.Eh|0,this.El|0,d|0,f|0),{h:m,l:h}=ce(this.Fh|0,this.Fl|0,m|0,h|0),{h:p,l:g}=ce(this.Gh|0,this.Gl|0,p|0,g|0),{h:x,l:b}=ce(this.Hh|0,this.Hl|0,x|0,b|0),this.set(r,o,s,i,a,c,l,u,d,
|
|
299
|
+
f,m,h,p,g,x,b);}roundClean(){st(Te,Ee);}destroy(){this.destroyed=true,st(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},Nn=class extends jn{Ah=H[0]|0;Al=H[1]|0;Bh=H[2]|0;Bl=H[3]|0;Ch=H[4]|0;Cl=H[5]|
|
|
300
|
+
0;Dh=H[6]|0;Dl=H[7]|0;Eh=H[8]|0;El=H[9]|0;Fh=H[10]|0;Fl=H[11]|0;Gh=H[12]|0;Gl=H[13]|0;Hh=H[14]|0;Hl=H[15]|0;constructor(){super(64);}};var Mt=bo(()=>new Nn,yo(3));var z=(t,e,n)=>re(t,e,n),Fn=_t,zn=At,le=(...t)=>Ln(...t),Oo=t=>it(t),Nt=An,_o=t=>xo(t),jt=BigInt(0),$n=BigInt(1);function ze(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"e\
|
|
301
|
+
xpected boolean, got type="+typeof t)}return t}function ta(t){if(typeof t=="bigint"){if(!Bt(t))throw new RangeError("positive bigint expected, got "+t)}else Fn(t);return t}function ge(t,e=""){if(typeof t!=
|
|
302
|
+
"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 Do(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?jt:BigInt("0x"+t)}function Vn(t){return Do(At(t))}function be(t){return Do(At(lt(re(t)).reverse()))}
|
|
303
|
+
function Un(t,e){if(_t(e),e===0)throw new RangeError("zero length");t=ta(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return it(n.padStart(e*2,"0"))}function Ao(t,e){
|
|
304
|
+
return Un(t,e).reverse()}function Po(t,e){if(t=z(t),e=z(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 lt(t){return Uint8Array.from(z(t))}var Bt=t=>typeof t=="bigint"&&jt<=t;function na(t,e,n){return Bt(t)&&Bt(e)&&Bt(n)&&e<=t&&t<n}function qn(t,e,n,r){if(!na(e,n,r))throw new RangeError(
|
|
305
|
+
"expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Hn(t){if(t<jt)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>jt;t>>=$n,e+=1);return e}var Lo=t=>($n<<BigInt(t))-$n;function Me(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function r(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(
|
|
306
|
+
`param "${s}" is invalid: expected own property`);let c=t[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.
|
|
307
|
+
entries(s).forEach(([a,c])=>r(a,c,i));o(e,false),o(n,true);}var Kn=()=>{throw new Error("not implemented")};var K=BigInt(0),U=BigInt(1),Be=BigInt(2),No=BigInt(3),$o=BigInt(4),Fo=BigInt(5),ra=BigInt(7),zo=BigInt(8),oa=BigInt(9),Vo=BigInt(16);function N(t,e){if(e<=K)throw new Error("mod: expected positive mod\
|
|
308
|
+
ulus, got "+e);let n=t%e;return n>=K?n:e+n}function oe(t,e,n){if(e<K)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >K;)r*=r,r%=n;return r}function Mo(t,e){if(t===K)throw new Error("invert: expected non-zero n\
|
|
309
|
+
umber");if(e<=K)throw new Error("invert: expected positive modulus, got "+e);let n=N(t,e),r=e,o=K,i=U;for(;n!==K;){let l=r/n,u=r-n*l,d=o-i*l;r=n,n=u,o=i,i=d;}if(r!==U)throw new Error(
|
|
310
|
+
"invert: does not exist");return N(o,e)}function Jn(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function Uo(t,e){let n=t,r=(n.ORDER+U)/$o,o=n.pow(e,r);return Jn(n,o,
|
|
311
|
+
e),o}function sa(t,e){let n=t,r=(n.ORDER-Fo)/zo,o=n.mul(e,Be),s=n.pow(o,r),i=n.mul(e,s),a=n.mul(n.mul(i,Be),s),c=n.mul(i,n.sub(a,n.ONE));return Jn(n,c,e),c}function ia(t){let e=Vt(t),n=qo(t),r=n(e,e.neg(
|
|
312
|
+
e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+ra)/Vo;return((a,c)=>{let l=a,u=l.pow(c,i),d=l.mul(u,r),f=l.mul(u,o),m=l.mul(u,s),h=l.eql(l.sqr(d),c),p=l.eql(l.sqr(f),c);u=l.cmov(u,d,h),d=l.cmov(m,f,p);let g=l.
|
|
313
|
+
eql(l.sqr(d),c),x=l.cmov(u,d,g);return Jn(l,x,c),x})}function qo(t){if(t<No)throw new Error("sqrt is not defined for small field");let e=t-U,n=0;for(;e%Be===K;)e/=Be,n++;let r=Be,o=Vt(t);for(;Bo(o,r)===
|
|
314
|
+
1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Uo;let s=o.pow(r,e),i=(e+U)/Be;return function(c,l){let u=c;if(u.is0(l))return l;if(Bo(u,l)!==1)throw new Error(
|
|
315
|
+
"Cannot find square root");let d=n,f=u.mul(u.ONE,s),m=u.pow(l,e),h=u.pow(l,i);for(;!u.eql(m,u.ONE);){if(u.is0(m))return u.ZERO;let p=1,g=u.sqr(m);for(;!u.eql(g,u.ONE);)if(p++,g=u.sqr(g),p===d)throw new Error(
|
|
316
|
+
"Cannot find square root");let x=U<<BigInt(d-p-1),b=u.pow(f,x);d=p,f=u.sqr(b),m=u.mul(m,f),h=u.mul(h,b);}return h}}function aa(t){return t%$o===No?Uo:t%zo===Fo?sa:t%Vo===oa?ia(t):qo(t)}var xe=(t,e)=>(N(
|
|
317
|
+
t,e)&U)===U,ca=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ho(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=ca.
|
|
318
|
+
reduce((r,o)=>(r[o]="function",r),e);if(Me(t,n),ge(t.BYTES,"BYTES"),ge(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=U)throw new Error("inval\
|
|
319
|
+
id field: expected ORDER > 1, got "+t.ORDER);return t}function la(t,e,n){let r=t;if(n<K)throw new Error("invalid exponent, negatives unsupported");if(n===K)return r.ONE;if(n===U)return e;let o=r.ONE,s=e;
|
|
320
|
+
for(;n>K;)n&U&&(o=r.mul(o,s)),s=r.sqr(s),n>>=U;return o}function zt(t,e,n=false){let r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),s=e.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),i=r.inv(s);return e.
|
|
321
|
+
reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),i),o}function Bo(t,e){let n=t,r=(n.ORDER-U)/Be,o=n.pow(e,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function ua(t,e){if(e!==void 0&&Fn(e),t<=K)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);
|
|
322
|
+
let n=Hn(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 jo=new WeakMap,
|
|
323
|
+
Ft=class{ORDER;BITS;BYTES;isLE;ZERO=K;ONE=U;_lengths;_mod;constructor(e,n={}){if(e<=U)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
|
|
324
|
+
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.
|
|
325
|
+
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:s}=ua(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2\
|
|
326
|
+
048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this);}create(e){return N(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got\
|
|
327
|
+
"+typeof e);return K<=e&&e<this.ORDER}is0(e){return e===K}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&U)===U}neg(e){return N(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return N(
|
|
328
|
+
e*e,this.ORDER)}add(e,n){return N(e+n,this.ORDER)}sub(e,n){return N(e-n,this.ORDER)}mul(e,n){return N(e*n,this.ORDER)}pow(e,n){return la(this,e,n)}div(e,n){return N(e*Mo(n,this.ORDER),this.ORDER)}sqrN(e){
|
|
329
|
+
return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Mo(e,this.ORDER)}sqrt(e){let n=jo.get(this);return n||jo.set(this,n=aa(this.ORDER)),n(this,e)}toBytes(e){return this.
|
|
330
|
+
isLE?Ao(e,this.BYTES):Un(e,this.BYTES)}fromBytes(e,n=false){z(e);let{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes\
|
|
331
|
+
: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?be(e):
|
|
332
|
+
Vn(e);if(a&&(c=N(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return zt(this,e)}cmov(e,n,r){return ze(r,"condition"),r?n:e}};Object.
|
|
333
|
+
freeze(Ft.prototype);function Vt(t,e={}){return new Ft(t,e)}var Ut=BigInt(0),Zn=BigInt(1);function Ko(t,e){let n=e.negate();return t?n:e}function Ht(t,e){let n=zt(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function Yo(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
|
|
334
|
+
throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Wn(t,e){Yo(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=Lo(t),i=BigInt(t);return {windows:n,windowSize:r,mask:s,maxNumber:o,
|
|
335
|
+
shiftBy:i}}function Jo(t,e,n){let{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n,a=Number(t&o),c=t>>i;a>r&&(a-=s,c+=Zn);let l=e*r,u=l+Math.abs(a)-1,d=a===0,f=a<0,m=e%2!==0;return {nextN:c,offset:u,isZero:d,
|
|
336
|
+
isNeg:f,isNegF:m,offsetF:l}}var Gn=new WeakMap,Zo=new WeakMap;function Yn(t){return Zo.get(t)||1}function Wo(t){if(t!==Ut)throw new Error("invalid wNAF")}var qt=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
|
|
337
|
+
e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>Ut;)n&Zn&&(r=r.add(o)),o=o.double(),n>>=Zn;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Wn(n,this.bits),s=[],
|
|
338
|
+
i=e,a=i;for(let c=0;c<r;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double();}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,
|
|
339
|
+
i=Wn(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:f,offsetF:m}=Jo(r,a,i);r=c,u?s=s.add(Ko(f,n[m])):o=o.add(Ko(d,n[l]));}return Wo(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.
|
|
340
|
+
ZERO){let s=Wn(e,this.bits);for(let i=0;i<s.windows&&r!==Ut;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Jo(r,i,s);if(r=a,!l){let d=n[c];o=o.add(u?d.negate():d);}}return Wo(r),o}getPrecomputes(e,n,r){let o=Gn.
|
|
341
|
+
get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Gn.set(n,o))),o}cached(e,n,r){let o=Yn(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let s=Yn(
|
|
342
|
+
e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){Yo(n,this.bits),Zo.set(e,n),Gn.delete(e);}hasCache(e){return Yn(e)!==1}};function Go(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ho(e),e}else return Vt(t,{isLE:n})}function Xo(t,e,n={},r){if(r===void 0&&(r=t==="edwar\
|
|
343
|
+
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>Ut))throw new Error(`CURVE.${c} must be positive bigint`)}
|
|
344
|
+
let o=Go(e.p,n.Fp,r),s=Go(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.
|
|
345
|
+
freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Qo(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var Re=BigInt(0),q=BigInt(1),Xn=BigInt(2),da=BigInt(8);function pa(t,e,n,r){let o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function es(t,e={}){
|
|
346
|
+
let n=e,r=Xo("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r,i=r.CURVE,{h:a}=i;Me(n,{},{uvRatio:"function"});let c=Xn<<BigInt(s.BYTES*8)-q,l=p=>o.create(p),u=n.uvRatio===void 0?(p,g)=>{try{return {isValid:!0,value:o.
|
|
347
|
+
sqrt(o.div(p,g))}}catch{return {isValid:false,value:Re}}}:n.uvRatio;if(!pa(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(p,g,x=false){let b=x?q:Re;return qn("coordinate "+p,g,
|
|
348
|
+
b,c),g}function f(p){if(!(p instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,q,l(i.Gx*i.Gy));static ZERO=new m(Re,q,q,Re);static Fp=o;static Fn=s;X;Y;Z;T;constructor(g,x,b,y){
|
|
349
|
+
this.X=d("x",g),this.Y=d("y",x),this.Z=d("z",b,true),this.T=d("t",y),Object.freeze(this);}static CURVE(){return i}static fromAffine(g){if(g instanceof m)throw new Error("extended point not allowed");let{
|
|
350
|
+
x,y:b}=g||{};return d("x",x),d("y",b),new m(x,b,q,l(x*b))}static fromBytes(g,x=false){let b=o.BYTES,{a:y,d:E}=i;g=lt(z(g,b,"point")),ze(x,"zip215");let C=lt(g),O=g[b-1];C[b-1]=O&-129;let T=be(C),D=x?c:o.
|
|
351
|
+
ORDER;qn("point.y",T,Re,D);let R=l(T*T),S=l(R-q),L=l(E*R-y),{isValid:v,value:w}=u(S,L);if(!v)throw new Error("bad point: invalid y coordinate");let _=(w&q)===q,P=(O&128)!==0;if(!x&&w===Re&&P)throw new Error(
|
|
352
|
+
"bad point: x=0 and x_0=1");return P!==_&&(w=l(-w)),m.fromAffine({x:w,y:T})}static fromHex(g,x=false){return m.fromBytes(Oo(g),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,x=true){
|
|
353
|
+
return h.createCache(this,g),x||this.multiply(Xn),this}assertValidity(){let g=this,{a:x,d:b}=i;if(g.is0())throw new Error("bad point: ZERO");let{X:y,Y:E,Z:C,T:O}=g,T=l(y*y),D=l(E*E),R=l(C*C),S=l(R*R),
|
|
354
|
+
L=l(T*x),v=l(R*l(L+D)),w=l(S+l(b*l(T*D)));if(v!==w)throw new Error("bad point: equation left != right (1)");let _=l(y*E),P=l(C*O);if(_!==P)throw new Error("bad point: equation left != right (2)")}equals(g){
|
|
355
|
+
f(g);let{X:x,Y:b,Z:y}=this,{X:E,Y:C,Z:O}=g,T=l(x*O),D=l(E*y),R=l(b*O),S=l(C*y);return T===D&&R===S}is0(){return this.equals(m.ZERO)}negate(){return new m(l(-this.X),this.Y,this.Z,l(-this.T))}double(){
|
|
356
|
+
let{a:g}=i,{X:x,Y:b,Z:y}=this,E=l(x*x),C=l(b*b),O=l(Xn*l(y*y)),T=l(g*E),D=x+b,R=l(l(D*D)-E-C),S=T+C,L=S-O,v=T-C,w=l(R*L),_=l(S*v),P=l(R*v),B=l(L*S);return new m(w,_,B,P)}add(g){f(g);let{a:x,d:b}=i,{X:y,
|
|
357
|
+
Y:E,Z:C,T:O}=this,{X:T,Y:D,Z:R,T:S}=g,L=l(y*T),v=l(E*D),w=l(O*b*S),_=l(C*R),P=l((y+E)*(T+D)-L-v),B=_-w,V=_+w,I=l(v-x*L),X=l(P*B),$=l(V*I),Q=l(P*I),J=l(B*V);return new m(X,$,J,Q)}subtract(g){return f(g),
|
|
358
|
+
this.add(g.negate())}multiply(g){if(!s.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:b}=h.cached(this,g,y=>Ht(m,y));return Ht(m,[x,b])[0]}multiplyUnsafe(g){
|
|
359
|
+
if(!s.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===Re?m.ZERO:this.is0()||g===q?this:h.unsafe(this,g,x=>Ht(m,x))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){
|
|
360
|
+
return h.unsafe(this,i.n).is0()}toAffine(g){let x=this,b=g,{X:y,Y:E,Z:C}=x,O=x.is0();b==null&&(b=O?da:o.inv(C));let T=l(y*b),D=l(E*b),R=o.mul(C,b);if(O)return {x:Re,y:q};if(R!==q)throw new Error("invZ \
|
|
361
|
+
was invalid");return {x:T,y:D}}clearCofactor(){return a===q?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:x}=this.toAffine(),b=o.toBytes(x);return b[b.length-1]|=g&q?128:0,b}toHex(){return zn(this.toBytes())}toString(){
|
|
362
|
+
return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let h=new qt(m,s.BITS);return s.BITS>=8&&m.BASE.precompute(8),Object.freeze(m.prototype),Object.freeze(m),m}var Kt=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){
|
|
363
|
+
this.ep=e;}static fromBytes(e){Kn();}static fromHex(e){Kn();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){
|
|
364
|
+
return this.ep.toAffine(e)}toHex(){return zn(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return true}isSmallOrder(){return false}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){
|
|
365
|
+
return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.
|
|
366
|
+
ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function ts(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is r\
|
|
367
|
+
equired');let r=e,o=n;Me(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=t,l=r.
|
|
368
|
+
outputLen,u=2*a.BYTES;if(l!==void 0&&(ge(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=o.randomBytes===void 0?_o:o.randomBytes,f=o.adjustScalarBytes===void 0?
|
|
369
|
+
v=>v:o.adjustScalarBytes,m=o.domain===void 0?(v,w,_)=>{if(ze(_,"phflag"),w.length||_)throw new Error("Contexts/pre-hash are not supported");return v}:o.domain;function h(v){return c.create(be(v))}function p(v){
|
|
370
|
+
let w=T.secretKey;z(v,T.secretKey,"secretKey");let _=z(r(v),2*w,"hashedSecretKey"),P=f(_.slice(0,w)),B=_.slice(w,2*w),V=h(P);return {head:P,prefix:B,scalar:V}}function g(v){let{head:w,prefix:_,scalar:P}=p(
|
|
371
|
+
v),B=i.multiply(P),V=B.toBytes();return {head:w,prefix:_,scalar:P,point:B,pointBytes:V}}function x(v){return g(v).pointBytes}function b(v=Uint8Array.of(),...w){let _=le(...w);return h(r(m(_,z(v,void 0,
|
|
372
|
+
"context"),!!s)))}function y(v,w,_={}){v=z(v,void 0,"message"),s&&(v=s(v));let{prefix:P,scalar:B,pointBytes:V}=g(w),I=b(_.context,P,v),X=i.multiply(I).toBytes(),$=b(_.context,X,V,v),Q=c.create(I+$*B);
|
|
373
|
+
if(!c.isValid(Q))throw new Error("sign failed: invalid s");let J=le(X,c.toBytes(Q));return z(J,T.signature,"result")}let E={zip215:o.zip215};function C(v,w,_,P=E){let{context:B}=P,V=P.zip215===void 0?
|
|
374
|
+
!!E.zip215:P.zip215,I=T.signature;v=z(v,I,"signature"),w=z(w,void 0,"message"),_=z(_,T.publicKey,"publicKey"),V!==void 0&&ze(V,"zip215"),s&&(w=s(w));let X=I/2,$=v.subarray(0,X),Q=be(v.subarray(X,I)),J,
|
|
375
|
+
ue,ve;try{J=t.fromBytes(_,V),ue=t.fromBytes($,V),ve=i.multiplyUnsafe(Q);}catch{return false}if(!V&&J.isSmallOrder())return false;let ke=b(B,$,_,w);return ue.add(J.multiplyUnsafe(ke)).subtract(ve).clearCofactor().
|
|
376
|
+
is0()}let O=a.BYTES,T={secretKey:O,publicKey:O,signature:2*O,seed:O};function D(v){return v=v===void 0?d(T.seed):v,z(v,T.seed,"seed")}function R(v){return Nt(v)&&v.length===T.secretKey}function S(v,w){
|
|
377
|
+
try{return !!t.fromBytes(v,w===void 0?E.zip215:w)}catch{return false}}let L={getExtendedPublicKey:g,randomSecretKey:D,isValidSecretKey:R,isValidPublicKey:S,toMontgomery(v){let{y:w}=t.fromBytes(v),_=T.publicKey,
|
|
378
|
+
P=_===32;if(!P&&_!==57)throw new Error("only defined for 25519 and 448");let B=P?a.div(q+w,q-w):a.div(w-q,w+q);return a.toBytes(B)},toMontgomerySecret(v){let w=T.secretKey;z(v,w);let _=r(v.subarray(0,
|
|
379
|
+
w));return f(_).subarray(0,w)}};return Object.freeze(T),Object.freeze(L),Object.freeze({keygen:Qo(D,x),getPublicKey:x,sign:y,verify:C,utils:L,Point:t,lengths:T})}var ha=BigInt(0),ye=BigInt(1),rs=BigInt(2);var ga=BigInt(5),ba=BigInt(8),Ve=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),rr={p:Ve,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ba,
|
|
380
|
+
a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
|
|
381
|
+
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function xa(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=Ve,a=t*t%
|
|
382
|
+
s*t%s,c=oe(a,rs,s)*a%s,l=oe(c,ye,s)*t%s,u=oe(l,ga,s)*l%s,d=oe(u,e,s)*u%s,f=oe(d,n,s)*d%s,m=oe(f,r,s)*f%s,h=oe(m,o,s)*m%s,p=oe(h,o,s)*m%s,g=oe(p,e,s)*u%s;return {pow_p_5_8:oe(g,rs,s)*t%s,b2:a}}function ya(t){
|
|
383
|
+
return t[0]&=248,t[31]&=127,t[31]|=64,t}var er=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function or(t,e){let n=Ve,r=N(e*e*e,n),o=N(r*r*e,n),s=xa(t*o).pow_p_5_8,
|
|
384
|
+
i=N(t*r*s,n),a=N(e*i*i,n),c=i,l=N(i*er,n),u=a===t,d=a===N(-t,n),f=a===N(-t*er,n);return u&&(i=c),(d||f)&&(i=l),xe(i,n)&&(i=N(-i,n)),{isValid:u||d,value:i}}var Ie=es(rr,{uvRatio:or}),Ce=Ie.Fp,is=Ie.Fn;function va(t){return ts(Ie,Mt,Object.assign({adjustScalarBytes:ya,zip215:true},t))}var as=va({});var tr=er;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var wa=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
|
|
385
|
+
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var os=t=>or(ye,t),Ea=BigInt("0x7\
|
|
386
|
+
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),nr=t=>Ce.create(be(t)&Ea);var Oe=class t extends Kt{static BASE=new t(
|
|
387
|
+
Ie.BASE);static ZERO=new t(Ie.ZERO);static Fp=Ce;static Fn=is;constructor(e){super(e);}static fromAffine(e){return new t(Ie.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoP\
|
|
388
|
+
oint expected")}init(e){return new t(e)}static fromBytes(e){re(e,32);let{a:n,d:r}=rr,o=Ve,s=E=>Ce.create(E),i=nr(e);if(!Po(Ce.toBytes(i),e)||xe(i,o))throw new Error("invalid ristretto255 encoding 1");
|
|
389
|
+
let a=s(i*i),c=s(ye+n*a),l=s(ye-n*a),u=s(c*c),d=s(l*l),f=s(n*r*u-d),{isValid:m,value:h}=os(s(f*d)),p=s(h*l),g=s(h*p*f),x=s((i+i)*p);xe(x,o)&&(x=s(-x));let b=s(c*g),y=s(x*b);if(!m||xe(y,o)||b===ha)throw new Error(
|
|
390
|
+
"invalid ristretto255 encoding 2");return new t(new Ie(x,b,ye,y))}static fromHex(e){return t.fromBytes(it(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,s=Ve,i=g=>Ce.create(g),a=i(i(r+n)*i(r-n)),c=i(e*n),
|
|
391
|
+
l=i(c*c),{value:u}=os(i(a*l)),d=i(u*a),f=i(u*c),m=i(d*f*o),h;if(xe(o*m,s)){let g=i(n*tr),x=i(e*tr);e=g,n=x,h=i(d*wa);}else h=f;xe(e*m,s)&&(n=i(-n));let p=i((r-n)*h);return xe(p,s)&&(p=i(-p)),Ce.toBytes(
|
|
392
|
+
p)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:s}=e.ep,i=l=>Ce.create(l),a=i(n*s)===i(r*o),c=i(r*s)===i(n*o);return a||c}is0(){return this.equals(t.ZERO)}};Object.freeze(Oe.BASE);Object.freeze(
|
|
393
|
+
Oe.ZERO);Object.freeze(Oe.prototype);Object.freeze(Oe);var cs=`-----BEGIN PUBLIC KEY-----
|
|
13
394
|
MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
|
|
14
|
-
-----END PUBLIC KEY-----`;function is(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 tr(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4?"=".repeat(4-e.length%4):"";return is(e+n)}function Sa(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=is(e);return n.subarray(n.length-32)}var Ta=new TextEncoder,as=new TextDecoder;function Ea(t){return typeof t=="object"&&t!==null&&"keys"in t}function nr(t,e){let n=t.split(".");if(n.length!==3)return {ok:false,reason:"malformed token"};let r=n[0],o=n[1],s=n[2],i;try{i=JSON.parse(as.decode(tr(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(Ea(e)){let u=typeof i.kid=="string"?i.kid:e.defaultKid,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=Sa(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{return {ok:false,reason:"invalid public key"}}let l=false;try{l=os.verify(tr(s),Ta.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:i,payloadBytes:tr(o)}:{ok:false,reason:"bad signature"}}function Ue(t,e){let n=nr(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(as.decode(n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function rr(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"active":e<=r?"grace":"expired"}function hd(t,e,n={}){let r=Ue(t,e);if(!r.signatureValid||!r.payload)return {status:"invalid",...r.reason?{reason:r.reason}:{}};let o=r.payload,s=n.nowSeconds??Math.floor(Date.now()/1e3),i=rr(o,s,n.revoked);return i==="revoked"?{status:i,payload:o,reason:"license revoked"}:{status:i,payload:o}}var cs="BVSALA-REVOC",Ra=300,Ca=new TextDecoder;function ls(t,e,n={}){let r=l=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:l}),o=nr(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");if(o.header?.typ!==cs)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${cs})`);let s;try{s=JSON.parse(Ca.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof s.seq!="number"||typeof s.asOf!="number"||!Array.isArray(s.revoked))return r("malformed revocation payload");let i=n.minSeq??0;if(s.seq<i)return r(`stale/rolled-back list (seq ${s.seq} < ${i})`);let a=n.nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??Ra;return s.asOf>a+c?r(`asOf too far in the future (${s.asOf} > ${a+c})`):{ok:true,seq:s.seq,asOf:s.asOf,revoked:new Set(s.revoked)}}var qe=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){return this._seq}get asOf(){return this._asOf}get lastContactAt(){return this._lastContactAt}markContact(e){e>this._lastContactAt&&(this._lastContactAt=e);}has(e){return this.set.has(e)}snapshot(){return this.set}apply(e){if(e.seq<this._seq)return false;let n=this.set.size;for(let s of e.revoked)this.set.add(s);let r=this.set.size>n,o=e.seq>this._seq;return e.seq>this._seq&&(this._seq=e.seq),e.asOf>this._asOf&&(this._asOf=e.asOf),r||o}};function qt(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),s=Ue(t,e),i=s.signatureValid?s.payload:void 0,a=new Set(i?.features??[]),c=()=>{if(!i)return "invalid";let u=rr(i,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(u==="active"||u==="grace")){let d=i.expires_at+i.grace_days*86400,p=Math.min(o,d),f=Math.max(n.revocation.lastContactAt,p);if(r()-f>n.maxStalenessSeconds)return "stale"}return u},l=()=>{let u=c();return u==="active"||u==="grace"};return {isEntitled:u=>l()&&a.has(u),isActive:()=>l(),status:c,refreshAfter:()=>{if(i)return Math.min(i.expires_at,r()+86400)}}}function us(t,e,n){return qt(t,e,{revocation:new qe,...n?{now:n}:{}})}var He={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},ds=3,Ia=12;function Oa(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>0){let o=Math.pow(2,Math.min(t.consecutiveFailures,4));n=Math.min(t.maxIntervalSeconds,t.floorSeconds*o);}else {let o=t.refreshAfter!=null?t.refreshAfter-t.nowSeconds:t.pollIntervalSeconds,s=o<0?t.pollIntervalSeconds:o;n=Math.min(t.pollIntervalSeconds,Math.max(t.floorSeconds,s));}let r=1+(e()*2-1)*t.jitterRatio;return Math.max(t.floorSeconds,n*r)}var _a=10,Ht=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;warnedNoFetch=false;lastEtag=null;consecutive304=0;now(){return this.opts.nowSeconds?this.opts.nowSeconds():Math.floor(Date.now()/1e3)}resolveFetch(){return this.opts.fetchImpl?this.opts.fetchImpl:typeof fetch<"u"?fetch:void 0}async pollOnce(){let e=this.resolveFetch();if(!e){this.warnedNoFetch||(this.warnedNoFetch=true,console.warn("[bv-sala] no global fetch available; revocation call-home disabled (offline). License expiry is still enforced from the token.")),this.opts.onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??He.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let s={accept:"application/json"};this.lastEtag&&(s["if-none-match"]=this.lastEtag);try{let i=await e(this.opts.url,{signal:n.signal,headers:s});if(i.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=_a&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!i.ok)throw new Error(`revocations HTTP ${i.status}`);let a=i.headers.get("etag"),c=await i.json();if(!c.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let l=ls(c.list,this.opts.publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??He.maxSkewSeconds});if(!l.ok){let d=l.reason??"rejected";this.opts.onEvent?.({type:"rejected",reason:d}),this.avisar(`rechazada:${d}`,`[bv-sala] la lista de revocaciones NO verifica (${d}). Se mantiene la \xFAltima buena conocida, as\xED que las revocaciones YA conocidas se siguen aplicando, pero las nuevas no llegan. Revise ${this.opts.url}.`);return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let u=this.opts.snapshot.apply(l);this.opts.onEvent?.(u?{type:"applied",seq:l.seq,size:this.opts.snapshot.snapshot().size}:{type:"unchanged",seq:l.seq});}catch(i){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:i}),this.avisarFalloDeRed(i);}finally{clearTimeout(o),this.controller=null;}}callado(){return !!(this.opts.silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||W(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;let n=this.consecutiveFailures;if(n<ds||(n-ds)%Ia!==0)return;let r=e instanceof Error?e.message:String(e);console.warn(`[bv-sala] no se ha podido contactar con el servidor de revocaciones ${n} veces seguidas (${r}). La licencia SIGUE funcionando y las revocaciones ya conocidas se siguen aplicando, pero las NUEVAS no est\xE1n llegando. Compruebe la salida hacia ${this.opts.url}.`);}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)return;let e=Oa({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??He.floorSeconds,pollIntervalSeconds:this.opts.pollIntervalSeconds??He.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??He.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??He.jitterRatio,...this.opts.random?{random:this.opts.random}:{}});this.timer=setTimeout(()=>{this.pollOnce().finally(()=>this.schedule());},e*1e3),this.timer.unref?.();}stop(){this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.controller?.abort();}};var at=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=e.flushIntervalMs??15e3,this.maxBatch=e.maxBatch??50,this.maxBuffer=e.maxBuffer??1e3,this.ci=e.ci??false;}setSeat(e,n){e&&(this.seatId=e),this.ci=n;}record(e){this.buffer.push({report:e,at:this.now()}),this.buffer.length>this.maxBuffer&&this.buffer.splice(0,this.buffer.length-this.maxBuffer),this.buffer.length>=this.maxBatch&&this.flush();}start(){this.timer||(this.timer=setInterval(()=>{this.flush();},this.flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async stopAndDrain(e){this.timer&&(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 s=this.buffer.length;if(await this.flush(),r=this.buffer.length>=s?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(){let e=this.options.fetchImpl??globalThis.fetch;if(!e)return;let n=this.buffer.splice(0,this.maxBatch);try{let r=n.map(s=>this.toWire(s)),o=await e(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.options.serviceAccountKey}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(`el servidor respondi\xF3 ${o.status}`)):o.status===401||o.status===403?(W(`metering-auth-${o.status}`,`[bv-sala] el env\xEDo de uso est\xE1 siendo rechazado con HTTP ${o.status} en ${this.options.url}. Revisa 'serviceAccountKey' (\xBFrotada? \xBFrevocada? \xBFde otra organizaci\xF3n?). Mientras no funcione NO se reporta uso: el panel dir\xE1 que no ve tr\xE1fico y los asientos facturables saldr\xE1n a cero.`),this.options.onAuthError?.(o.status)):(this.fallosSeguidos++,this.avisarDeFallo(o.status===404||o.status===405?`HTTP ${o.status}: la URL de env\xEDo parece equivocada`:`el servidor rechaz\xF3 el lote con HTTP ${o.status}`));}catch(r){this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(r instanceof Error?r.message:"error de red");}}avisarDeFallo(e){if(this.options.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.warn(`[bv-sala] el env\xEDo de uso lleva ${n} intentos seguidos fallando contra ${this.options.url} (${e}). Las peticiones SIGUEN funcionando, pero el uso no est\xE1 llegando: el panel dir\xE1 que no ve tr\xE1fico y los asientos facturables saldr\xE1n a cero. Comprueba 'meteringUrl' \u2014 por defecto es \`\${licenseServerUrl}/api/metering/usage\`.`);}requeue(e){this.buffer=[...e,...this.buffer],this.buffer.length>this.maxBuffer&&(this.buffer.length=this.maxBuffer);}toWire(e){let n=e.report;return {orgId:this.options.orgId??"self",...this.seatId?{seatId:this.seatId}:{},...this.ci?{ci:true}:{},requestId:n.requestId,model:n.model,at:e.at,avoidedLlm:n.calls.avoidedLlm,actualLlm:n.calls.actualLlm,baselineInputTokens:n.tokens.baselineInput,actualInputTokens:n.tokens.actualInput,eliminatedInputTokens:n.tokens.eliminatedInput,compressedInputTokens:n.tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutputTokens:n.tokens.actualOutput,providerCachedInputTokens:n.tokens.providerCachedInput??0,cacheResult:n.cache.result,baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{}}}};function Kt(){return globalThis.process}function Da(t){if(/^[0-9a-f]{12}$/.test(t)||/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||/^ip-\d{1,3}(-\d{1,3}){3}$/i.test(t))return true;let e="[bcdfghjklmnpqrstvwxz2456789]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function Aa(t){return !!(t.AWS_LAMBDA_FUNCTION_NAME??t.LAMBDA_TASK_ROOT??t.VERCEL??t.VERCEL_ENV??t.K_SERVICE??t.FUNCTION_TARGET??t.FUNCTIONS_WORKER_RUNTIME??t.NETLIFY)}async function Pa(){if(Kt()?.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 La(t,e=Pa){if(t.KUBERNETES_SERVICE_HOST||Aa(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||Da(n)))return n}async function Ma(){let t=Kt();if(!t||!t.env)return;let e=t.env,n=await La(e),r=[t.platform,t.arch,t.execPath,n,e.USER??e.USERNAME??e.LOGNAME,e.HOME??e.USERPROFILE].filter(o=>typeof o=="string"&&o.length>0);return r.length?r.join("|"):void 0}var Ba=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function or(){let t=Kt()?.env;if(!t)return false;for(let e of Ba){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function ja(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let i=await n.subtle.importKey("raw",r.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",i,r.encode(e));return [...new Uint8Array(a)].map(c=>c.toString(16).padStart(2,"0")).join("")}catch{}let o=2166136261,s=`${t}|${e}`;for(let i=0;i<s.length;i++)o^=s.charCodeAt(i),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function sr(t){let n=Kt()?.env?.BVSALA_SEAT_ID;if(n&&Na.test(n))return n;let r=await Ma();if(!r)return;let o=await ja(t,r);if(o)return `m-${o.slice(0,32)}`}var Na=/^[A-Za-z0-9._:/-]{1,128}$/;var ps={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function fs(t){return {exactCache:t.exactCache??new gt,semanticCache:t.semanticCache,singleflight:t.singleflight??new bt,resolvers:t.resolvers??Nr(),router:t.router??new xt,toolSelector:t.toolSelector??new yt,formatSelector:t.formatSelector??new St({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new Tt,constraintBackends:t.constraintBackends??[]}}var $a=36e5,Fa=7*86400,za=3e4,Jt=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;avisadoDeCredencial=false;currentExpiresAt;currentOrg;constructor(e){this.opts=e,this.pollIntervalMs=e.pollIntervalMs??$a,this.refreshLeadSeconds=e.refreshLeadSeconds??Fa;let n=Ue(e.initialToken,e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.expires_at:0,this.currentOrg=n.signatureValid?n.payload?.org_id:void 0;}start(){this.timer||(this.checkNow(),this.timer=setInterval(()=>{this.checkNow();},this.pollIntervalMs),this.timer.unref?.());}stop(){this.parado=true,this.timer&&clearInterval(this.timer),this.timer=null,this.controller?.abort(),this.controller=null;}nowSeconds(){return Math.floor((this.opts.now?this.opts.now():Date.now())/1e3)}async checkNow(){if(this.enVuelo||this.parado||this.currentExpiresAt-this.nowSeconds()>this.refreshLeadSeconds)return false;this.enVuelo=true;let e=new AbortController;this.controller=e;let n=setTimeout(()=>e.abort(),this.opts.requestTimeoutMs??za);n.unref?.();try{let o=await(this.opts.fetchImpl??globalThis.fetch.bind(globalThis))(this.opts.url,{signal:e.signal,headers:{authorization:`Bearer ${this.opts.serviceAccountKey}`,accept:"application/json"}});if(!o.ok)return (o.status===401||o.status===403||o.status===404)&&!this.avisadoDeCredencial&&(this.avisadoDeCredencial=!0,console.warn(`[bv-sala] la recogida autom\xE1tica de la licencia renovada falla con HTTP ${o.status} en ${this.opts.url}. Revisa 'serviceAccountKey' (\xBFrotada? \xBFde otra organizaci\xF3n?) y 'licenseServerUrl': mientras no funcione, el token NO se renovar\xE1 solo y el SDK dejar\xE1 de operar al terminar el periodo de gracia.`)),!1;let s=await o.json();if(typeof s.token!="string")return !1;let i=Ue(s.token,this.opts.publicKey);return !i.signatureValid||!i.payload||i.payload.expires_at<=this.currentExpiresAt||this.currentOrg&&i.payload.org_id!==this.currentOrg||this.opts.revocados?.snapshot().has(i.payload.jti)||this.parado?!1:(this.currentExpiresAt=i.payload.expires_at,this.currentOrg=i.payload.org_id,this.opts.onNewToken(s.token),!0)}catch{return false}finally{clearTimeout(n),this.controller===e&&(this.controller=null),this.enVuelo=false;}}};var ir={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},ar={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},cr={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1};var ms={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function Gt(t,e,n,r){let o=r.minimumCacheTokens;if(o==null||t<o)return t;let s=Math.min(e,t),i=t-s,a=Math.min(1,Math.max(0,n)),c=a*s*r.cacheReadMultiplier+(1-a)*s*r.cacheWriteMultiplier;return i+c}function lr(t){let e=Gt(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=Gt(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??0),r=e-n,o=t.tier.minimumCacheTokens,i=o!=null&&t.originalTokens>=o&&t.compressedTokens<o,a;if(r<=0){let c=e<t.originalTokens;a=i?`compressing drops the prompt out of the cacheable tier (${t.compressedTokens} < ${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*100).toFixed(0)}% hit rate)`:"the saving does not cover the compressor's cost";}else i?a=`pays off even after losing the prefix cache (${(t.prefixHitRate*100).toFixed(0)}% hit rate)`:a="pays off and does not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function hs(t){let e=o=>lr({...t,prefixHitRate:o}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,r=1;for(let o=0;o<40;o++){let s=(n+r)/2;e(s)>0?n=s:r=s;}return (n+r)/2}function Va(t){let e=hs({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(Gt(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.totalTokens?null:1)}var Wt=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-1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=Va(n),o=this.estados.get(e),s=Ua(o);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:r,observada:s}:r==null?{marcar:true,razon:"marking cannot lose money at this tier (no write premium)",umbral:r,observada:s}:o?.apagada?{marcar:false,razon:`prefix-cache marking OFF: measured hit rate ${Ke(s)} did not reach the ${Ke(r)} break-even, so marking was costing money`,umbral:r,observada:s}:o==null||o.marcadas<this.exploracion?{marcar:true,razon:`exploring the prefix cache (${o?.marcadas??0}/${this.exploracion}); hit rate is only observable on requests that were marked`,umbral:r,observada:s}:s!=null&&s>r?{marcar:true,razon:`measured hit rate ${Ke(s)} beats the ${Ke(r)} break-even`,umbral:r,observada:s}:(o.apagada=true,{marcar:false,razon:`prefix-cache marking OFF: measured hit rate ${Ke(s)} did not reach the ${Ke(r)} break-even, so marking was costing money`,umbral:r,observada:s})}registrar(e,n){let r=this.estados.get(e)??{marcadas:0,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 Ua(t){if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function Ke(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var gs=.5;function qa(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function Ha(t){return 1-t}function Ka(t,e=gs){return e-t}function bs(t,e,n=gs){if(!t||!e)return null;let r=qa(t,e);if(r==null||!Number.isFinite(r))return null;let o=Ha(r),s=Ka(r,n),i=s>0,a=c=>`${(c*100).toFixed(1)}%`;return {r,equilibrio:o,escaladoMaximo:s,viable:i,razon:i?`the cheap model costs ${a(r)} of the strong one, so routing pays off while escalations stay under ${a(s)} (it stops saving money at ${a(o)})`:`the cheap model costs ${a(r)} of the strong one: even with zero escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var ur={"gpt-4":"gpt-4o","gpt-4-turbo":"gpt-4o-mini","gpt-4o":"gpt-4o-mini","gpt-4.1":"gpt-4.1-mini","claude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-opus":"claude-3-haiku","claude-3-5-sonnet":"claude-3-5-haiku"};function Ja(t){return Object.keys(t).sort((e,n)=>n.length-e.length||e.localeCompare(n))}function xs(t,e=ur){if(!t)return null;let n=t.lastIndexOf("/"),r=n>=0?t.slice(0,n+1):"",o=n>=0?t.slice(n+1):t,s=e[t]??e[o]??Ga(o,e);return !s||s===o?null:r+s}function Ga(t,e){for(let n of Ja(e))if(t.startsWith(n)&&t.charAt(n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var Yt=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(e)}decidir(e,n){let r=this.estados.get(e),o=Wa(r),s=r?.enrutadas??0,i=a=>a==null?"n/a":`${(a*100).toFixed(1)}%`;return r?.apagada?{enrutar:false,razon:`model cascade OFF for this workload: measured escalation rate ${i(o)} is at or above the ${i(n.equilibrio)} break-even, so routing was costing money`,observada:o,muestras:s}:s<this.exploracion?{enrutar:true,razon:`measuring this workload (${s}/${this.exploracion}); the escalation rate is only observable on requests that were actually routed`,observada:o,muestras:s}:o!=null&&o<n.equilibrio?{enrutar:true,razon:`measured escalation rate ${i(o)} stays under the ${i(n.equilibrio)} break-even (this is a MONEY check, not a quality one)`,observada:o,muestras:s}:(r&&(r.apagada=true),{enrutar:false,razon:`model cascade OFF for this workload: measured escalation rate ${i(o)} is at or above the ${i(n.equilibrio)} break-even, so routing was costing money`,observada:o,muestras:s})}registrar(e,n){let r=this.estados.get(e)??{enrutadas:0,escaladas:0,apagada:false};r.enrutadas+=1,n&&(r.escaladas+=1),this.estados.set(e,r);}};function Wa(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var Ya=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function Za(t){return t?dr(t)?"value-constrained":"structural":"none"}function dr(t,e=0){if(e>12)return false;let n=t;for(let r of Ya)if(n[r]!==void 0)return true;if(t.properties){for(let r of Object.values(t.properties))if(dr(r,e+1))return true}return !!(t.items&&dr(t.items,e+1))}function ys(t){let e=Za(t.schema),n=(t.tools??[]).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 cannot 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 report 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 content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function pr(t){let e=[];if(e.push("non-empty"),t.texto.trim()==="")return {acepta:false,motivo:"the cheap model returned an empty answer",comprobaciones:e};if(e.push("final-answer"),t.pidioHerramientas)return {acepta:false,motivo:"the cheap model asked to run tools: that is an action, not a final answer, and the output contract cannot check it",comprobaciones:e};if(e.push("not-truncated"),t.finishReason==="length")return {acepta:false,motivo:"the cheap model's answer was cut off by maxOutputTokens",comprobaciones:e};if(e.push("output-contract"),!t.schema)return {acepta:false,motivo:"no output contract to verify against",comprobaciones:e};let n;try{n=JSON.parse(t.texto);}catch{return {acepta:false,motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=ae(n,t.schema);return r.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{acepta:false,motivo:`the cheap model's answer does not satisfy the output contract (${r.errors.slice(0,3).map(s=>`${s.path}: ${s.message}`).join("; ")})`,comprobaciones:e}}function vs(t,e){let n,r;try{n=JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=Zt(n),s=Zt(r);return o.length===0&&s.length===0?{divergen:false,motivo:"no comparable facts (free prose only)"}:Qa(o,s)?{divergen:false,motivo:"the hard values agree"}:{divergen:true,motivo:"both answers satisfy the contract but disagree on at least one hard value; this is the signature of a false valid \u2014 it is a reason to look, never a verdict"}}var Xa=40;function Zt(t,e=0,n=[]){if(e>12)return n;if(typeof t=="number"&&Number.isFinite(t))n.push(`n:${t}`);else if(typeof t=="boolean")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=Xa&&n.push(`s:${r.toLowerCase()}`);}else if(Array.isArray(t))for(let r of t)Zt(r,e+1,n);else if(t&&typeof t=="object")for(let r of Object.keys(t).sort())Zt(t[r],e+1,n);return n.sort()}function Qa(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 ks="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, because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function ec(t){if(t<=0)return "";let e=ks;for(;e.length<t;)e+=ks;return e.slice(0,t)}function tc(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 fr(t){if(t.enum&&t.enum.length>0)return {valor:tc(t.enum)};switch(t.type??(t.properties?"object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:ec(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?{valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=fr(t.items);return n?{valor:Array.from({length:t.maxItems},()=>n.valor)}:void 0}case "object":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let s=fr(o);if(!s)return;n[r]=s.valor;}return {valor:n}}default:return}}function nc(t){let e=fr(t);return e?JSON.stringify(e.valor):null}function ws(t,e){let n=nc(t);return n===null?null:e(n)}var Xt=16,Ss=64,rc=8,oc="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 Ts(t,e,n,r={}){let o=r.minimumSavingsTokens??rc,s;try{if(gr(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};s=xr(t,0);}catch(S){return {applied:false,reason:S instanceof RangeError?"schema too deep or cyclic":"schema could not be compacted"}}if(s.renamed===0&&s.coded===0)return {applied:false,reason:"nothing to compact (no renameable keys, no codeable enums)"};let i=s.node;if(!i)return {applied:false,reason:"nothing to compact"};let a=S=>Je(S,i,true),c=S=>Je(S,i,false),l=uc(t),u=sc(t,s.compact,i,l);if(!u.ok)return {applied:false,reason:u.reason};let d=e(JSON.stringify(t)),p=e(JSON.stringify(s.compact)),f=d-p,m=Number.POSITIVE_INFINITY;for(let S of l){let L=e(JSON.stringify(S))-e(JSON.stringify(a(S)));L<m&&(m=L);}Number.isFinite(m)||(m=0);let g=S=>S/1e3*n.inputPer1k,h=S=>S/1e3*n.outputPer1k,x=g(o),b=n.outputPer1k>0?(o-f)*n.inputPer1k/n.outputPer1k:Number.NEGATIVE_INFINITY,y=Number.isFinite(b)?b.toFixed(1):"any",E=n.inputPer1k>0?`${(n.outputPer1k/n.inputPer1k).toFixed(1)}x`:"more than",C=r.evidencia;if(C==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 the model, not of the schema: ${oc}. Here the compact contract saves ${f} input tokens and output is billed ${E} input, so it only pays while the output delta stays above ${y} tokens. Measure yours (benchmarks/ab-live.ts) and pass it in`};let O=C.deltaTokens;if(O<0)return {applied:false,reason:`the measured output delta is ${O} tokens: this model writes MORE from a compact contract (${C.procedencia}). The input win is capped by the size of the schema while the output loss grows with the answer and is billed ${E} input, so no schema is big enough to buy it back`};let T=g(f)+h(O),D=n.inputPer1k>0?T*1e3/n.inputPer1k:f,R=`+${O} tokens (${O>0?"the model wrote LESS":"no measured change"}), ${C.procedencia}`;return T<x?{applied:false,reason:`net saving $${T.toFixed(9)}/request is below the floor of ${o} input tokens ($${x.toFixed(9)}): the compact contract saves ${f} input tokens and the measured output delta is ${R}; break-even at ${y}`}:{applied:true,reason:`net saving $${T.toFixed(9)}/request (${D.toFixed(1)} input tokens equivalent): the compact contract saves ${f} input tokens and the measured output delta is ${R}; break-even at ${y}`,plan:{compactSchema:s.compact,expand:c,compact:a,renamedKeys:s.renamed,codedEnumValues:s.coded,schemaTokensOriginal:d,schemaTokensCompact:p,modelledShapeSavingTokens:m,measuredOutputDeltaTokens:O,outputDeltaProvenance:C.procedencia,breakEvenOutputDeltaTokens:b,netSavingUsd:T}}}function sc(t,e,n,r){for(let o of r){if(!ae(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let s=Je(o,n,true);if(!ae(s,e).valid)return {ok:false,reason:"compact witness does not validate against the compact schema"};if(!br(Je(s,n,false),o))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function Es(t){return t.type==="object"||t.type==null&&t.properties!=null}function Rs(t){return t.type==="array"||t.type==null&&t.items!=null}function ic(t){let e=t.enum;return !e||e.length===0||e.length>Ss||!e.every(n=>typeof n=="string")?null:e}function xr(t,e){if(e>Xt)throw new RangeError("schema too deep");let n=ic(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=Cs(n,true);if(!r)return {compact:t,renamed:0,coded:0};let o=[...r].filter(([i,a])=>i!==a).length;if(o===0)return {compact:t,renamed:0,coded:0};let s=new Map;for(let[i,a]of r)s.set(a,i);return {compact:{...t,enum:n.map(i=>r.get(i))},node:{enumFwd:r,enumBack:s},renamed:0,coded:o}}return Es(t)?ac(t,e):Rs(t)?cc(t,e):{compact:t,renamed:0,coded:0}}function ac(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};let r=0,o=0,s=new Map,i=new Map;for(let[p,f]of n){let m=xr(f,e+1);i.set(p,m.compact),m.node&&s.set(p,m.node),r+=m.renamed,o+=m.coded;}let a=null;t.additionalProperties===false&&(a=Cs(n.map(([p])=>p),false));let c={};for(let[p]of n)c[a?.get(p)??p]=i.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[m,g]of a)p.set(g,m);let f=false;for(let[m,g]of a)m!==g&&(f=true);if(f){u.keysFwd=a,u.keysBack=p;for(let[m,g]of a)m!==g&&(r+=1);}}s.size>0&&(u.props=s);let d=!u.keysFwd&&!u.props;return {compact:l,...d?{}:{node:u},renamed:r,coded:o}}function cc(t,e){if(!t.items)return {compact:t,renamed:0,coded:0};let n=xr(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function Cs(t,e){let n=[...t].sort(),r=new Set,o=new Map;n.forEach((i,a)=>{let c=e?i.toUpperCase():i,l=i;for(let u=1;u<i.length;u++){let d=c.slice(0,u);if(!r.has(d)){l=d;break}}if(l===i){let u=a.toString(36);u.length<i.length&&!r.has(u)&&(l=u);}r.add(l),o.set(i,l);});let s=new Set(t);for(let[i,a]of o)if(a!==i&&s.has(a))return null;return o}function Je(t,e,n){let r=n?e.enumFwd:e.enumBack;if(r&&typeof t=="string")return r.get(t)??t;if(e.items&&Array.isArray(t))return t.map(s=>Je(s,e.items,n));let o=n?e.keysFwd:e.keysBack;if((o||e.props)&&lc(t)){let s={};for(let[i,a]of Object.entries(t)){let c=o?.get(i)??i,l=n?i:c,u=e.props?.get(l);s[c]=u?Je(a,u,n):a;}return s}return t}function lc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function uc(t){let e=Math.min(Ss,Math.max(1,mr(t,0))),n=[];for(let r=0;r<e;r++)n.push(hr(t,r,0));return n}function mr(t,e){if(e>Xt)return 0;let n=t.enum?.length??0;for(let r of Object.values(t.properties??{}))n=Math.max(n,mr(r,e+1));return t.items&&(n=Math.max(n,mr(t.items,e+1))),n}function hr(t,e,n){if(n>Xt)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(Es(t)){let r={};for(let[o,s]of Object.entries(t.properties??{}))r[o]=hr(s,e,n+1);return r}if(Rs(t)){if(t.maxItems===0)return [];let r=Math.max(1,t.minItems??1),o=t.maxItems!=null?Math.min(r,t.maxItems):r,s=t.items;return Array.from({length:o},()=>s?hr(s,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";let r=Math.max(1,t.minLength??1),o=t.maxLength!=null?Math.min(r,t.maxLength):r;return "x".repeat(o)}case "number":case "integer":{let r=t.minimum??1;return t.maximum!=null&&r>t.maximum&&(r=t.maximum),t.type==="integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function gr(t,e){if(e>Xt)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.values(t.properties??{}))if(gr(n,e+1))return true;return !!(t.items&&gr(t.items,e+1))}function br(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.isArray(t),r=Array.isArray(e);if(n||r){if(!n||!r||t.length!==e.length)return false;for(let i=0;i<t.length;i++)if(!br(t[i],e[i]))return false;return true}let o=Object.keys(t),s=Object.keys(e);if(o.length!==s.length)return false;for(let i of o)if(!Object.prototype.hasOwnProperty.call(e,i)||!br(t[i],e[i]))return false;return true}var dc="2026-08-14",Is={"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 enums)",pares:8}},pc=cn(Is);function fc(t){return an(Is,pc,t)}var Qt=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&&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,origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let s=fc(e);return s?{deltaTokens:s.deltaTokens,origen:"catalogue",procedencia:`measured by BiVelio on ${e} (${dc}, ${s.pares} paired reps, ${s.contrato}, ${s.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};function yr(t,e){if(e?.cacheTier)return e.cacheTier;let n=t.toLowerCase(),r=n.indexOf("/"),o=r>0?n.slice(0,r):"",s=r>=0?n.slice(r+1):n;return o==="openai"||o==="azure-openai"?ir:o==="anthropic"?ar:o==="google"||o==="google-vertex"?cr:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(s)?ir:s.startsWith("claude")?ar:s.startsWith("gemini")?cr:ms}function Os(t){let e=t.prefix!=null,n=lr({originalTokens:t.originalTokens,compressedTokens:t.compressedTokens,stablePrefixTokens:t.prefix?.stableTokens??0,prefixHitRate:t.prefix?.hitRate??0,tier:t.tier,...t.compressorCostTokens!=null?{compressorCostTokens:t.compressorCostTokens}:{}});if(e)return n;let r=t.tier.minimumCacheTokens;return r!=null&&t.originalTokens>=r&&t.compressedTokens<r?{...n,comprimir:false,razon:`compressing would drop the prompt out of the cacheable tier (${t.compressedTokens} < ${r}) and nobody has measured the prefix hit rate, so it cannot be claimed to pay for itself. Declare it in \`compressionEconomics.prefix\` to unlock the full decision`}:n}function Ds(t){let e=u=>u/1e3*t.precio.inputPer1k,n=u=>u/1e3*t.precio.outputPer1k,r=e(t.promptTokens+t.descriptoresLigeros)+n(t.salidaDelSondeo),o=e(t.promptTokens+t.esquemasCompletos)+n(t.salidaFinal),s=r+e(t.promptTokens+t.esquemasDeLaSegunda)+n(t.salidaFinal),i=o-s,a=r,c=i>0&&i>=a,l;return i<=0?l=`descubrir cuesta m\xE1s de lo que ahorra: el prompt (${t.promptTokens} tokens) se paga dos veces y los esquemas que se evitan (${t.esquemasCompletos-t.esquemasDeLaSegunda}) no lo cubren`:c?l=`se evitan ${t.esquemasCompletos-t.esquemasDeLaSegunda} tokens de esquema en el peor caso, bastante para pagar el prompt repetido y el sondeo`:l="la ganancia no cubre el coste de degradar: si el sondeo no elige, la petici\xF3n sale igual con todos los esquemas y el sondeo es coste puro",{aplicar:c,costeDeUnaLlamada:o,costeDeDosLlamadas:s,ganancia:i,perdidaSiDegrada:a,razon:l}}function As(t){let n=(t.description??t.intents.join("; ")).trim().split(/\r?\n/,1)[0]??"",r=n.length>_s?n.slice(0,_s-1).trimEnd()+"\u2026":n;return {id:t.id,intents:t.intents,risk:t.risk,...r?{description:r}:{}}}var _s=200;function Ps(t,e,n){let r=new Map(e.map(c=>[c.id,c])),o=[],s=[],i=new Set;for(let c of t){let l=r.get(c);if(!l){s.push(c);continue}o.includes(l.id)||(o.push(l.id),l.risk==="read"&&i.size<Math.max(0,n)&&i.add(l.id));}return {tools:e.filter(c=>c.risk!=="read"||i.has(c.id)),reconocidos:o,ignorados:s}}function Ls(t,e){let n=0,r=[];for(let o of t)o.risk==="read"?r.push(o.tokens):n+=o.tokens;r.sort((o,s)=>s-o);for(let o of r.slice(0,Math.max(0,e)))n+=o;return n}var Ns=new WeakSet;function mc(t){typeof t=="object"&&t!==null&&Ns.add(t);}function hc(t){return typeof t=="object"&&t!==null&&Ns.has(t)}function js(t){switch(t){case "none":return gc();case "invalid":return "BiVelio license key is not valid (it does not verify). Check you pasted the WHOLE key, and that it is the license key from your dashboard \u2014 not the `bvk_` service-account key, which goes in `serviceAccountKey`. Keys: https://savings.bivelio.com/dashboard/install (license status: invalid)";case "revoked":return "BiVelio license has been revoked. If this is unexpected, check your billing status at https://savings.bivelio.com/dashboard/account or write to support@bivelio.com (license status: revoked)";case "stale":return "BiVelio could not confirm your license with the control plane in time \u2014 this is a connectivity problem, not a billing one: your license is still valid. Allow outbound HTTPS to your `licenseServerUrl` (https://savings.bivelio.com by default) and retry. (license 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 license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function gc(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 the signed token from your subscription, verified offline. This published package has no unlicensed mode. Copy your key and a ready-to-paste snippet at https://savings.bivelio.com/dashboard/install (license status: none)"}function bc(){return "licenseGate must implement isActive(): a gate that cannot prove the license is live is refused. In this published package an injected gate is not a licensing path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var en=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new Wt;verjaDeCascada;memoriaDelCodebook=new Qt;constructor(e){this.config=e,this.deps=fs(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>ln()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.verjaDeCascada=new Yt(e.modelCascade?.exploration!=null?{exploracion:e.modelCascade.exploration}:{});}async generate(e){this.assertLicensed();let n={llamadas:0,falloDelProveedor:false};try{return await this.generateOptimized(e,n)}catch(r){if(r instanceof Ae||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||hc(r))throw r;return await this.failOpenDirect(e,r)}}async llamarProveedor(e,n){n.llamadas+=1;try{return await this.config.provider.generate(e)}catch(r){throw n.falloDelProveedor=true,r}}decidirMarcadoDeCache(e,n,r,o,s,i,a){let c={marcar:false,huella:"",mensajesDePrefijo:0},l=Ec(n,this.config.compressionEconomics);if(!l)return a.record("prefix-cache","skipped",{reason:`no cache read discount for model "${n}" (unrecognised provider, or a declared tier that does not discount reads): not claiming a cacheable prefix`}),c;if(!o.setIsStable)return a.record("prefix-cache","skipped",{reason:"the tool SET is selected per request; tools render first, so the prefix cannot hit. Pruning wins here (it is a measured saving); pass the tools you want fixed."}),c;if(s)return a.record("prefix-cache","skipped",{reason:"savings.toolDiscovery is on: which schemas travel is decided by a non-deterministic probe, so the tool block \u2014 which renders first \u2014 varies across requests that would share a prefix fingerprint. Marking would pay the 1.25x write premium for a prefix that cannot hit. Turn tool discovery off to reclaim the prefix cache."}),c;if(i<=0)return c;let u=r.slice(0,i),d=this.tokensFor(this.assemblePromptText(u,o.tools),e),p=this.tokensFor(this.assemblePromptText(r,o.tools),e),f=ie(Se({model:n,tools:(o.tools??[]).map(g=>g.id),prefijo:u.map(g=>`${g.role}:${g.content}`)})),m=this.verjaDeCache.decidir(f,{totalTokens:p,stablePrefixTokens:d,tier:l});return a.record("prefix-cache",m.marcar?"marked":"skipped",{reason:m.razon,stablePrefixTokens:d,breakEvenHitRate:m.umbral,observedHitRate:m.observada}),m.marcar?{marcar:true,huella:f,mensajesDePrefijo:i}:c}decidirCascada(e,n,r,o){let s=r.modelCascade??"off",i={modo:"off",modeloPedido:e.model,modeloServido:e.model,candidato:null,enruta:false,elegible:false,razon:"the model cascade is off",fuerza:"none",bucket:"",economia:null,observada:null,muestras:0,precioBarato:null,tasaDeMuestreo:0};if(s==="off")return i;let a=ys({schema:e.response?.schema,tools:e.tools}),c=xs(e.model,this.config.modelCascade?.pairs??ur),l=this.precioConocido(e.model),u=c?this.precioConocido(c):void 0,d=bs(u,l),p=ie(Se({tenant:n.tenantId,scope:n.authorizationScope,contract:n.contractId,schema:n.schemaVersion,fuerte:e.model,barato:c,tools:n.toolsetHash})),f=this.verjaDeCascada.estado(p),m={modo:s,modeloPedido:e.model,modeloServido:e.model,candidato:c,enruta:false,elegible:false,razon:a.razon,fuerza:a.fuerza,bucket:p,economia:d,observada:f&&f.enrutadas>0?f.escaladas/f.enrutadas:null,muestras:f?.enrutadas??0,precioBarato:u??null,tasaDeMuestreo:0},g=b=>(o.record("model-cascade",s==="on"?"not routed":"not eligible",{reason:b}),{...m,razon:b});if(!a.elegible)return g(a.razon);if(!c)return g(`no cheaper model is paired with "${e.model}"; declare one in createSavingsLayer({ modelCascade: { pairs } }) if your provider has one`);if(!d){let b=[...this.precioConocido(e.model)?[]:[e.model],...u?[]:[c]];return g(`no known price for ${b.map(y=>`"${y}"`).join(" or ")||"this pair"}, so the arithmetic that decides whether routing pays cannot be run. The illustrative default price is deliberately NOT used here: it would approve a pair nobody has priced. Pass \`costModels\` for both models to enable the cascade for them`)}if(!d.viable)return g(d.razon);let h=Math.min(1,Math.max(0,this.config.modelCascade?.shadowSampleRate??0));if(s==="shadow")return o.record("model-cascade","shadow",{candidateModel:c,costRatio:d.r,breakEvenEscalationRate:d.equilibrio,verifier:a.fuerza,workload:p,note:"measuring only: the request goes to the model you asked for. The escalation rate is not a quality score \u2014 a well-formed answer with wrong content passes the verifier."}),{...m,elegible:true,razon:a.razon,tasaDeMuestreo:h};let x=this.verjaDeCascada.decidir(p,d);return x.enrutar?(this.avisar(`cascada:${e.model}->${c}`,`[bv-sala] model cascade ON: requests for "${e.model}" may be answered by "${c}" when a deterministic gate accepts the answer. The gate checks the SHAPE of the answer against your output contract, never its meaning, so a well-formed answer with wrong content is served and counted as a success. report.model always names the model that answered, and report.qualityStatus reads "bounded_degradation".`),o.record("model-cascade","routed",{candidateModel:c,costRatio:d.r,breakEvenEscalationRate:d.equilibrio,observedEscalationRate:x.observada,verifier:a.fuerza,workload:p,reason:x.razon}),{...m,modeloServido:c,enruta:true,elegible:true,razon:x.razon,observada:x.observada,muestras:x.muestras,tasaDeMuestreo:0}):(o.record("model-cascade","off (gate)",{reason:x.razon,observedEscalationRate:x.observada,breakEvenEscalationRate:d.equilibrio}),{...m,elegible:true,razon:x.razon,observada:x.observada,muestras:x.muestras})}devOpen(){return false}assertLicensed(){if(this.devOpen())return;let e=this.config.licenseGate;if(e&&typeof e.isActive=="function"){if(e.isActive())return;let n=typeof e.status=="function"?e.status():void 0;throw new Ae(js(n),n)}throw e?new Ae(bc(),"invalid"):new Ae(js("none"),"none")}avisar(e,n){this.config.silenceWarnings||W(e,n);}avisarDeTruncado(e,n,r,o,s){let i=e.response?.maxOutputTokens,a=dt(e)||"(sin contractId)",c=s?" La capa lo ha APUNTADO: las siguientes peticiones de este contrato llevar\xE1n sus l\xEDmites de valor escritos en el prompt, que es lo \xFAnico que puede corregirlo sin tocarte el tope. Si aun as\xED se corta, es que la tarea no cabe en el contrato: ensancha el esquema y sube el tope con \xE9l.":"",l=o===null?" El esquema no acota la respuesta (falta `maxLength`/`maxItems`), as\xED que no hay forma de saber de antemano cu\xE1nto necesita: ac\xF3talo y el tope deja de ser una apuesta.":i==null?` El contrato autoriza ~${o} tokens y esta petici\xF3n no declara tope, as\xED que quien cort\xF3 fue un tope del PROVEEDOR (la API de Anthropic exige \`max_tokens\` y el adaptador manda 4096 por defecto). Declara \`maxOutputTokens\` y el corte deja de ser una sorpresa.`:o>i?` El contrato autoriza respuestas de hasta ~${o} tokens con este modelo (lo que permiten sus \`maxLength\`/\`maxItems\`) y el tope son ${i}: ninguna respuesta que use lo que el propio esquema permite cabe. Un tope calibrado con otro modelo NO se hereda \u2014 el esquema acota CARACTERES, que son iguales en todas partes, y el tope acota TOKENS, que son distintos en cada tokenizador.`:` El contrato autoriza ~${o} tokens y el tope son ${i}, as\xED que el tope no es el problema: este modelo est\xE1 escribiendo m\xE1s de lo que su propio esquema permite (ning\xFAn modo estructurado impone \`maxLength\`).${c}`;this.avisar(`salida-truncada:${a}:${n}`,`[bvsala] La respuesta se cort\xF3 al agotar \`maxOutputTokens\`${i!=null?` (${i})`:""} con el modelo ${n} y el contrato \xAB${a}\xBB: el proveedor devolvi\xF3 finish_reason "length" y ${r} tokens de salida, as\xED que el JSON no valida. NO se reintenta: con el mismo tope volver\xEDa a cortarse y ser\xEDa una llamada pagada para el mismo fallo.${l}`);}avisarDePalancasSinConfigurar(e){this.config.silenceWarnings||((e.compression===true||e.compression==="auto")&&!this.config.compressor&&this.avisar("palanca-sin-compresor","[bv-sala] se pidi\xF3 `savings.compression` pero esta capa no tiene compresor, as\xED que NO se comprime nada: el contexto largo viaja y se paga entero. En el informe, `report.compression` sale AUSENTE y `tokens.eliminatedInput` a 0 \u2014 lo mismo que se ve cuando no hab\xEDa nada que comprimir. El compresor es un sidecar porque a\xF1ade latencia y c\xF3mputo que solo usted debe decidir pagar: ench\xFAfelo con `createSavingsLayer({ compressor })`, cualquier objeto con `compress({ text })`. Si su plan no incluye `long_context_compression`, har\xE1 falta adem\xE1s esa funci\xF3n. El resto de la capa sigue ahorrando igual."),e.semanticCache&&!this.deps.semanticCache&&this.avisar("palanca-sin-cache-semantica",'[bv-sala] se pidi\xF3 `savings.semanticCache` pero esta capa no tiene cach\xE9 sem\xE1ntica, as\xED que toda pregunta reformulada saldr\xE1 `cache: "miss"` y se pagar\xE1 al proveedor otra vez. No viene por defecto porque necesita un embebedor, que es coste y proveedor suyos: ench\xFAfela con `createSavingsLayer({ semanticCache: new InMemorySemanticCache({ embed }) })`. La cach\xE9 exacta y el resto de la capa siguen funcionando.'));}async generateOptimized(e,n={llamadas:0,falloDelProveedor:false}){this.assertLicensed();let r=new et(this.now),o=new Ne,s=gn(e),i=xn(s),a=e.savings??{};this.avisarDePalancasSinConfigurar(a);let c=this.decidirCascada(e,s,a,r),l=this.costModelFor(c.modeloServido);r.record("canonicalize","done",{tenant:s.tenantId,contract:s.contractId}),r.record("policy",i.reasons.join("; ")||"no restrictions",{allowExactCache:i.allowExactCache,allowSemanticCache:i.allowSemanticCache});let u=this.tokensFor(this.assembleBaselinePrompt(e),e),d=e.response?.maxOutputTokens??256;if(o.baselineInput=u,o.baselineOutput=d,o.baselineTools=e.tools?.length??0,a.deterministicResolvers!==false){let g=this.deps.resolvers.try(s);if(g)return o.avoidCall(u,this.tokensFor(g.text,e)),r.record("resolver",g.resolver,{avoided:true}),this.finish(e,s,{text:g.text,data:g.data,storedAtMs:this.now()},"deterministic",o,l,r,lt(),ut(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(c,{servedModel:e.model}))}let p=bn(s,{servedModel:c.modeloServido});if(i.allowExactCache&&a.exactCache!==false){let g=await this.deps.exactCache.get(p);if(g)return o.avoidCall(u,this.tokensFor(g.text,e)),r.record("exact-cache","hit",{ageMs:this.now()-g.storedAtMs}),this.finish(e,s,g,"exact",o,l,r,lt(),ut(),this.now()-g.storedAtMs,void 0,void 0,void 0,void 0,this.informeDeCascada(c));r.record("exact-cache","miss");}let f=Dr(s,{servedModel:c.modeloServido,deferrable:a.deferrable===true,toolDiscovery:a.toolDiscovery===true,...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{}}),m=async()=>{try{return await this.expensivePath(n,e,s,i,a,o,l,r,p,u,c)}catch(g){throw (n.falloDelProveedor||n.llamadas>0)&&mc(g),g}};if(i.allowSingleflight&&a.singleflight!==false){let{value:g,coalesced:h}=await this.deps.singleflight.run(f,m);return h?(r.record("singleflight","coalesced",{key:f}),this.asCoalescedFollower(g,u,this.tokensFor(g.text??"",e),l,e)):g}return m()}async expensivePath(e,n,r,o,s,i,a,c,l,u,d){let p=this.entitled("semantic_cache");if(o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&!p&&c.record("semantic-cache","degraded: feature not licensed (free tier)"),o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&p){let k=await this.deps.semanticCache.find(r);if(k)return i.avoidCall(u,this.tokensFor(k.record.answer.text,n)),c.record("semantic-cache","hit",{confidence:k.confidence,similarity:k.similarity}),this.finish(n,r,k.record.answer,"semantic",i,a,c,lt(),ut(),k.ageMs,k.confidence,void 0,void 0,void 0,this.informeDeCascada(d,{servedModel:n.model}));c.record("semantic-cache","miss");}let f=s.router===false,m=f?lt():this.deps.router.classify(r);c.record("router",m.executionClass,{confidence:m.confidence,reason:m.reason});let g=f?this.deps.toolSelector.passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,m.executionClass);if(i.actualTools=g.tools.length,g.droppedIds.length){let k=new Set(g.droppedIds),A=(n.tools??[]).filter(j=>k.has(j.id)).reduce((j,G)=>j+this.tokensFor(vr(G),n),0);i.eliminate(A),c.record("tool-selector",g.reason,{dropped:g.droppedIds,eliminatedTokens:A});}i.baselineRetrieval=m.rounds;let h=await Fr({execution:m.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.maxRounds??m.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});i.actualRetrieval=h.rounds,h.retrievedCount>0&&c.record("retrieval",`kept ${h.keptCount}/${h.retrievedCount}`,{rounds:h.rounds});let x=ut(),b=[...n.messages],y=wr(n.messages),E=false,C=h.docs.length>0?{role:"system",content:`Retrieved context \u2014 answer using only this evidence and cite sources by [id]:
|
|
395
|
+
-----END PUBLIC KEY-----`;function ls(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 sr(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.
|
|
396
|
+
length%4?"=".repeat(4-e.length%4):"";return ls(e+n)}function Ca(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=ls(e);return n.subarray(n.length-32)}var Ia=new TextEncoder,us=new TextDecoder;
|
|
397
|
+
function Oa(t){return typeof t=="object"&&t!==null&&"keys"in t}function ir(t,e){let n=t.split(".");if(n.length!==3)return {ok:false,reason:"malformed token"};let r=n[0],o=n[1],s=n[2],i;try{i=JSON.parse(us.
|
|
398
|
+
decode(sr(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(Oa(e)){let u=typeof i.kid=="string"?i.kid:e.defaultKid,d=e.keys[u];if(!d)return {ok:false,reason:`unknown key id "${u}"`};a=d;}else {
|
|
399
|
+
if(!e)return {ok:false,reason:"no verification key"};a=e;}let c;try{if(c=Ca(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{return {ok:false,reason:"invalid public key"}}let l=false;try{l=as.verify(
|
|
400
|
+
sr(s),Ia.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:i,payloadBytes:sr(o)}:{ok:false,reason:"bad signature"}}function Ue(t,e){let n=ir(t,e);if(!n.
|
|
401
|
+
ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(us.decode(n.payloadBytes))}}catch{return {signatureValid:false,reason:"payloa\
|
|
402
|
+
d is not valid JSON"}}}function ar(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"active":e<=r?"grace":"expired"}function vd(t,e,n={}){let r=Ue(t,
|
|
403
|
+
e);if(!r.signatureValid||!r.payload)return {status:"invalid",...r.reason?{reason:r.reason}:{}};let o=r.payload,s=n.nowSeconds??Math.floor(Date.now()/1e3),i=ar(o,s,n.revoked);return i==="revoked"?{status:i,
|
|
404
|
+
payload:o,reason:"license revoked"}:{status:i,payload:o}}var ds="BVSALA-REVOC",_a=300,Da=new TextDecoder;function ps(t,e,n={}){let r=l=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:l}),o=ir(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
|
|
405
|
+
if(o.header?.typ!==ds)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${ds})`);let s;try{s=JSON.parse(Da.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof s.
|
|
406
|
+
seq!="number"||typeof s.asOf!="number"||!Array.isArray(s.revoked))return r("malformed revocation payload");let i=n.minSeq??0;if(s.seq<i)return r(`stale/rolled-back list (seq ${s.seq} < ${i})`);let a=n.
|
|
407
|
+
nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??_a;return s.asOf>a+c?r(`asOf too far in the future (${s.asOf} > ${a+c})`):{ok:true,seq:s.seq,asOf:s.asOf,revoked:new Set(s.revoked)}}var qe=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
|
|
408
|
+
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.
|
|
409
|
+
set}apply(e){if(e.seq<this._seq)return false;let n=this.set.size;for(let s of e.revoked)this.set.add(s);let r=this.set.size>n,o=e.seq>this._seq;return e.seq>this._seq&&(this._seq=e.seq),e.asOf>this._asOf&&
|
|
410
|
+
(this._asOf=e.asOf),r||o}};function Jt(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),s=Ue(t,e),i=s.signatureValid?s.payload:void 0,a=new Set(i?.features??[]),c=()=>{if(!i)return "invalid";let u=ar(
|
|
411
|
+
i,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(u==="active"||u==="grace")){let d=i.expires_at+i.grace_days*86400,f=Math.min(o,d),m=Math.max(n.revocation.lastContactAt,f);if(r()-m>n.maxStalenessSeconds)
|
|
412
|
+
return "stale"}return u},l=()=>{let u=c();return u==="active"||u==="grace"};return {isEntitled:u=>l()&&a.has(u),isActive:()=>l(),status:c,refreshAfter:()=>{if(i)return Math.min(i.expires_at,r()+86400)}}}function fs(t,e,n){return Jt(t,e,{revocation:new qe,...n?{now:n}:{}})}var He={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},ms=3,Aa=12;function Pa(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
|
|
413
|
+
0){let o=Math.pow(2,Math.min(t.consecutiveFailures,4));n=Math.min(t.maxIntervalSeconds,t.floorSeconds*o);}else {let o=t.refreshAfter!=null?t.refreshAfter-t.nowSeconds:t.pollIntervalSeconds,s=o<0?t.pollIntervalSeconds:
|
|
414
|
+
o;n=Math.min(t.pollIntervalSeconds,Math.max(t.floorSeconds,s));}let r=1+(e()*2-1)*t.jitterRatio;return Math.max(t.floorSeconds,n*r)}var La=10,Wt=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;warnedNoFetch=false;lastEtag=null;consecutive304=0;now(){
|
|
415
|
+
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();
|
|
416
|
+
if(!e){this.warnedNoFetch||(this.warnedNoFetch=true,console.warn("[bv-sala] no global fetch available; revocation call-home disabled (offline). License expiry is still enforced from the token.")),this.opts.
|
|
417
|
+
onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??He.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let s={accept:"applicati\
|
|
418
|
+
on/json"};this.lastEtag&&(s["if-none-match"]=this.lastEtag);try{let i=await e(this.opts.url,{signal:n.signal,headers:s});if(i.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.
|
|
419
|
+
now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=La&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!i.
|
|
420
|
+
ok)throw new Error(`revocations HTTP ${i.status}`);let a=i.headers.get("etag"),c=await i.json();if(!c.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let l=ps(c.list,this.opts.
|
|
421
|
+
publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??He.maxSkewSeconds});if(!l.ok){let d=l.reason??"rejected";this.opts.onEvent?.({type:"rejected",
|
|
422
|
+
reason:d}),this.avisar(`rechazada:${d}`,`[bv-sala] la lista de revocaciones NO verifica (${d}). Se mantiene la \xFAltima buena conocida, as\xED que las revocaciones YA conocidas se siguen aplicando, pero la\
|
|
423
|
+
s nuevas no llegan. Revise ${this.opts.url}.`);return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let u=this.opts.snapshot.apply(l);this.opts.onEvent?.(u?{type:"applied",seq:l.seq,
|
|
424
|
+
size:this.opts.snapshot.snapshot().size}:{type:"unchanged",seq:l.seq});}catch(i){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:i}),this.avisarFalloDeRed(i);}finally{clearTimeout(o),
|
|
425
|
+
this.controller=null;}}callado(){return !!(this.opts.silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||G(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;
|
|
426
|
+
let n=this.consecutiveFailures;if(n<ms||(n-ms)%Aa!==0)return;let r=e instanceof Error?e.message:String(e);console.warn(`[bv-sala] no se ha podido contactar con el servidor de revocaciones ${n} veces s\
|
|
427
|
+
eguidas (${r}). La licencia SIGUE funcionando y las revocaciones ya conocidas se siguen aplicando, pero las NUEVAS no est\xE1n llegando. Compruebe la salida hacia ${this.opts.url}.`);}start(){this.started||
|
|
428
|
+
this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)return;let e=Pa({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.
|
|
429
|
+
consecutiveFailures,floorSeconds:this.opts.floorSeconds??He.floorSeconds,pollIntervalSeconds:this.opts.pollIntervalSeconds??He.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??He.maxIntervalSeconds,
|
|
430
|
+
jitterRatio:this.opts.jitterRatio??He.jitterRatio,...this.opts.random?{random:this.opts.random}:{}});this.timer=setTimeout(()=>{this.pollOnce().finally(()=>this.schedule());},e*1e3),this.timer.unref?.();}stop(){
|
|
431
|
+
this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.controller?.abort();}};var dt=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=
|
|
432
|
+
e.flushIntervalMs??15e3,this.maxBatch=e.maxBatch??50,this.maxBuffer=e.maxBuffer??1e3,this.ci=e.ci??false;}setSeat(e,n){e&&(this.seatId=e),this.ci=n;}record(e){this.buffer.push({report:e,at:this.now()}),this.
|
|
433
|
+
buffer.length>this.maxBuffer&&this.buffer.splice(0,this.buffer.length-this.maxBuffer),this.buffer.length>=this.maxBatch&&this.flush();}start(){this.timer||(this.timer=setInterval(()=>{this.flush();},this.
|
|
434
|
+
flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async stopAndDrain(e){this.timer&&(clearInterval(this.timer),this.timer=void 0);let n=e??
|
|
435
|
+
Math.ceil(this.maxBuffer/this.maxBatch)+4,r=0;for(let o=0;o<n&&this.buffer.length>0;o++){let s=this.buffer.length;if(await this.flush(),r=this.buffer.length>=s?r+1:0,r>=2)break}}async flush(){if(this.
|
|
436
|
+
inflight)return this.inflight;if(this.buffer.length!==0){this.inflight=this.hacerFlush();try{await this.inflight;}finally{this.inflight=null;}}}async hacerFlush(){let e=this.options.fetchImpl??globalThis.
|
|
437
|
+
fetch;if(!e)return;let n=this.buffer.splice(0,this.maxBatch);try{let r=n.map(s=>this.toWire(s)),o=await e(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bear\
|
|
438
|
+
er ${this.options.serviceAccountKey}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(`el servidor respondi\xF3 ${o.status}`)):
|
|
439
|
+
o.status===401||o.status===403?(G(`metering-auth-${o.status}`,`[bv-sala] el env\xEDo de uso est\xE1 siendo rechazado con HTTP ${o.status} en ${this.options.url}. Revisa 'serviceAccountKey' (\xBFrotada? \xBF\
|
|
440
|
+
revocada? \xBFde otra organizaci\xF3n?). Mientras no funcione NO se reporta uso: el panel dir\xE1 que no ve tr\xE1fico y los asientos facturables saldr\xE1n a cero.`),this.options.onAuthError?.(o.status)):
|
|
441
|
+
(this.fallosSeguidos++,this.avisarDeFallo(o.status===404||o.status===405?`HTTP ${o.status}: la URL de env\xEDo parece equivocada`:`el servidor rechaz\xF3 el lote con HTTP ${o.status}`));}catch(r){this.
|
|
442
|
+
fallosSeguidos++,this.requeue(n),this.avisarDeFallo(r instanceof Error?r.message:"error de red");}}avisarDeFallo(e){if(this.options.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.
|
|
443
|
+
warn(`[bv-sala] el env\xEDo de uso lleva ${n} intentos seguidos fallando contra ${this.options.url} (${e}). Las peticiones SIGUEN funcionando, pero el uso no est\xE1 llegando: el panel dir\xE1 que no ve tr\xE1\
|
|
444
|
+
fico y los asientos facturables saldr\xE1n a cero. Comprueba 'meteringUrl' \u2014 por defecto es \`\${licenseServerUrl}/api/metering/usage\`.`);}requeue(e){this.buffer=[...e,...this.buffer],this.buffer.
|
|
445
|
+
length>this.maxBuffer&&(this.buffer.length=this.maxBuffer);}toWire(e){let n=e.report;return {orgId:this.options.orgId??"self",...this.seatId?{seatId:this.seatId}:{},...this.ci?{ci:true}:{},requestId:n.requestId,
|
|
446
|
+
model:n.model,at:e.at,avoidedLlm:n.calls.avoidedLlm,actualLlm:n.calls.actualLlm,baselineInputTokens:n.tokens.baselineInput,actualInputTokens:n.tokens.actualInput,eliminatedInputTokens:n.tokens.eliminatedInput,
|
|
447
|
+
compressedInputTokens:n.tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutputTokens:n.tokens.actualOutput,providerCachedInputTokens:n.tokens.providerCachedInput??0,cacheResult:n.
|
|
448
|
+
cache.result,baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{}}}};function Gt(){return globalThis.process}function Ma(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\
|
|
449
|
+
]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function Ba(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??
|
|
450
|
+
t.NETLIFY)}async function ja(){if(Gt()?.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 Na(t,e=ja){
|
|
451
|
+
if(t.KUBERNETES_SERVICE_HOST||Ba(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||Ma(n)))return n}async function $a(){let t=Gt();if(!t||!t.env)return;let e=t.env,n=await Na(e),r=[t.platform,
|
|
452
|
+
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 Fa=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
|
|
453
|
+
ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function cr(){let t=Gt()?.env;if(!t)
|
|
454
|
+
return false;for(let e of Fa){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function za(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let i=await n.subtle.importKey("raw",
|
|
455
|
+
r.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",i,r.encode(e));return [...new Uint8Array(a)].map(c=>c.toString(16).padStart(2,"0")).join("")}catch{}let o=2166136261,s=`${t}\
|
|
456
|
+
|${e}`;for(let i=0;i<s.length;i++)o^=s.charCodeAt(i),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function lr(t){let n=Gt()?.env?.BVSALA_SEAT_ID;if(n&&Va.test(n))return n;let r=await $a();
|
|
457
|
+
if(!r)return;let o=await za(t,r);if(o)return `m-${o.slice(0,32)}`}var Va=/^[A-Za-z0-9._:/-]{1,128}$/;var hs={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function gs(t){return {exactCache:t.exactCache??new yt,semanticCache:t.semanticCache,singleflight:t.singleflight??new vt,resolvers:t.resolvers??Fr(),router:t.router??new kt,toolSelector:t.toolSelector??
|
|
458
|
+
new wt,formatSelector:t.formatSelector??new Rt({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new Ct,constraintBackends:t.constraintBackends??[]}}var Ua=36e5,qa=7*86400,Ha=3e4,Yt=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;avisadoDeCredencial=false;currentExpiresAt;currentOrg;constructor(e){this.opts=
|
|
459
|
+
e,this.pollIntervalMs=e.pollIntervalMs??Ua,this.refreshLeadSeconds=e.refreshLeadSeconds??qa;let n=Ue(e.initialToken,e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.expires_at:
|
|
460
|
+
0,this.currentOrg=n.signatureValid?n.payload?.org_id:void 0;}start(){this.timer||(this.checkNow(),this.timer=setInterval(()=>{this.checkNow();},this.pollIntervalMs),this.timer.unref?.());}stop(){this.parado=
|
|
461
|
+
true,this.timer&&clearInterval(this.timer),this.timer=null,this.controller?.abort(),this.controller=null;}nowSeconds(){return Math.floor((this.opts.now?this.opts.now():Date.now())/1e3)}async checkNow(){if(this.
|
|
462
|
+
enVuelo||this.parado||this.currentExpiresAt-this.nowSeconds()>this.refreshLeadSeconds)return false;this.enVuelo=true;let e=new AbortController;this.controller=e;let n=setTimeout(()=>e.abort(),this.opts.requestTimeoutMs??
|
|
463
|
+
Ha);n.unref?.();try{let o=await(this.opts.fetchImpl??globalThis.fetch.bind(globalThis))(this.opts.url,{signal:e.signal,headers:{authorization:`Bearer ${this.opts.serviceAccountKey}`,accept:"applicatio\
|
|
464
|
+
n/json"}});if(!o.ok)return (o.status===401||o.status===403||o.status===404)&&!this.avisadoDeCredencial&&(this.avisadoDeCredencial=!0,console.warn(`[bv-sala] la recogida autom\xE1tica de la licencia renova\
|
|
465
|
+
da falla con HTTP ${o.status} en ${this.opts.url}. Revisa 'serviceAccountKey' (\xBFrotada? \xBFde otra organizaci\xF3n?) y 'licenseServerUrl': mientras no funcione, el token NO se renovar\xE1 solo y el SDK dejar\xE1\
|
|
466
|
+
de operar al terminar el periodo de gracia.`)),!1;let s=await o.json();if(typeof s.token!="string")return !1;let i=Ue(s.token,this.opts.publicKey);return !i.signatureValid||!i.payload||i.payload.expires_at<=
|
|
467
|
+
this.currentExpiresAt||this.currentOrg&&i.payload.org_id!==this.currentOrg||this.opts.revocados?.snapshot().has(i.payload.jti)||this.parado?!1:(this.currentExpiresAt=i.payload.expires_at,this.currentOrg=
|
|
468
|
+
i.payload.org_id,this.opts.onNewToken(s.token),!0)}catch{return false}finally{clearTimeout(n),this.controller===e&&(this.controller=null),this.enVuelo=false;}}};var ur={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},dr={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},pr={minimumCacheTokens:1024,cacheReadMultiplier:.1,
|
|
469
|
+
cacheWriteMultiplier:1};var bs={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function Zt(t,e,n,r){let o=r.minimumCacheTokens;if(o==null||t<o)return t;let s=Math.min(e,t),i=t-s,a=Math.min(1,Math.max(0,
|
|
470
|
+
n)),c=a*s*r.cacheReadMultiplier+(1-a)*s*r.cacheWriteMultiplier;return i+c}function fr(t){let e=Zt(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=Zt(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??
|
|
471
|
+
0),r=e-n,o=t.tier.minimumCacheTokens,i=o!=null&&t.originalTokens>=o&&t.compressedTokens<o,a;if(r<=0){let c=e<t.originalTokens;a=i?`compressing drops the prompt out of the cacheable tier (${t.compressedTokens}\
|
|
472
|
+
< ${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*
|
|
473
|
+
100).toFixed(0)}% hit rate)`:"the saving does not cover the compressor's cost";}else i?a=`pays off even after losing the prefix cache (${(t.prefixHitRate*100).toFixed(0)}% hit rate)`:a="pays off and do\
|
|
474
|
+
es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function xs(t){let e=o=>fr({...t,prefixHitRate:o}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,
|
|
475
|
+
r=1;for(let o=0;o<40;o++){let s=(n+r)/2;e(s)>0?n=s:r=s;}return (n+r)/2}function Ka(t){let e=xs({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(Zt(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.
|
|
476
|
+
totalTokens?null:1)}var Xt=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-
|
|
477
|
+
1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=Ka(n),o=this.estados.get(e),s=Ja(o);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:r,observada:s}:r==null?
|
|
478
|
+
{marcar:true,razon:"marking cannot lose money at this tier (no write premium)",umbral:r,observada:s}:o?.apagada?{marcar:false,razon:`prefix-cache marking OFF: measured hit rate ${Ke(s)} did not reach the ${Ke(
|
|
479
|
+
r)} break-even, so marking was costing money`,umbral:r,observada:s}:o==null||o.marcadas<this.exploracion?{marcar:true,razon:`exploring the prefix cache (${o?.marcadas??0}/${this.exploracion}); hit rate \
|
|
480
|
+
is only observable on requests that were marked`,umbral:r,observada:s}:s!=null&&s>r?{marcar:true,razon:`measured hit rate ${Ke(s)} beats the ${Ke(r)} break-even`,umbral:r,observada:s}:(o.apagada=true,{marcar:false,
|
|
481
|
+
razon:`prefix-cache marking OFF: measured hit rate ${Ke(s)} did not reach the ${Ke(r)} break-even, so marking was costing money`,umbral:r,observada:s})}registrar(e,n){let r=this.estados.get(e)??{marcadas:0,
|
|
482
|
+
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 Ja(t){
|
|
483
|
+
if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function Ke(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var ys=.5;function Wa(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function Ga(t){return 1-t}function Ya(t,e=ys){return e-t}function vs(t,e,n=ys){
|
|
484
|
+
if(!t||!e)return null;let r=Wa(t,e);if(r==null||!Number.isFinite(r))return null;let o=Ga(r),s=Ya(r,n),i=s>0,a=c=>`${(c*100).toFixed(1)}%`;return {r,equilibrio:o,escaladoMaximo:s,viable:i,razon:i?`the c\
|
|
485
|
+
heap model costs ${a(r)} of the strong one, so routing pays off while escalations stay under ${a(s)} (it stops saving money at ${a(o)})`:`the cheap model costs ${a(r)} of the strong one: even with zer\
|
|
486
|
+
o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var mr={"gpt-4":"gpt-4o","gpt-4-turbo":"gpt-4o-mini","gpt-4o":"gpt-4o-mini","gpt-4.1":"gpt-4.1-mini","cla\
|
|
487
|
+
ude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-opus":"claude-3-haiku","claude-3-5-sonnet":"claude-3-5-haiku"};function Za(t){return Object.keys(t).sort((e,n)=>n.length-e.
|
|
488
|
+
length||e.localeCompare(n))}function ks(t,e=mr){if(!t)return null;let n=t.lastIndexOf("/"),r=n>=0?t.slice(0,n+1):"",o=n>=0?t.slice(n+1):t,s=e[t]??e[o]??Xa(o,e);return !s||s===o?null:r+s}function Xa(t,e){
|
|
489
|
+
for(let n of Za(e))if(t.startsWith(n)&&t.charAt(n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var Qt=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(
|
|
490
|
+
e)}decidir(e,n){let r=this.estados.get(e),o=Qa(r),s=r?.enrutadas??0,i=a=>a==null?"n/a":`${(a*100).toFixed(1)}%`;return r?.apagada?{enrutar:false,razon:`model cascade OFF for this workload: measured escal\
|
|
491
|
+
ation rate ${i(o)} is at or above the ${i(n.equilibrio)} break-even, so routing was costing money`,observada:o,muestras:s}:s<this.exploracion?{enrutar:true,razon:`measuring this workload (${s}/${this.exploracion}\
|
|
492
|
+
); the escalation rate is only observable on requests that were actually routed`,observada:o,muestras:s}:o!=null&&o<n.equilibrio?{enrutar:true,razon:`measured escalation rate ${i(o)} stays under the ${i(
|
|
493
|
+
n.equilibrio)} break-even (this is a MONEY check, not a quality one)`,observada:o,muestras:s}:(r&&(r.apagada=true),{enrutar:false,razon:`model cascade OFF for this workload: measured escalation rate ${i(o)}\
|
|
494
|
+
is at or above the ${i(n.equilibrio)} break-even, so routing was costing money`,observada:o,muestras:s})}registrar(e,n){let r=this.estados.get(e)??{enrutadas:0,escaladas:0,apagada:false};r.enrutadas+=1,
|
|
495
|
+
n&&(r.escaladas+=1),this.estados.set(e,r);}};function Qa(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var ec=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function tc(t){return t?hr(t)?"value-constrained":"structural":"none"}function hr(t,e=0){if(e>12)return false;let n=t;
|
|
496
|
+
for(let r of ec)if(n[r]!==void 0)return true;if(t.properties){for(let r of Object.values(t.properties))if(hr(r,e+1))return true}return !!(t.items&&hr(t.items,e+1))}function ws(t){let e=tc(t.schema),n=(t.tools??
|
|
497
|
+
[]).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\
|
|
498
|
+
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\
|
|
499
|
+
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 \
|
|
500
|
+
content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function gr(t){let e=[];if(e.push("non-empty"),t.texto.trim()==="")return {acepta:false,
|
|
501
|
+
motivo:"the cheap model returned an empty answer",comprobaciones:e};if(e.push("final-answer"),t.pidioHerramientas)return {acepta:false,motivo:"the cheap model asked to run tools: that is an action, not a \
|
|
502
|
+
final answer, and the output contract cannot check it",comprobaciones:e};if(e.push("not-truncated"),t.finishReason==="length")return {acepta:false,motivo:"the cheap model's answer was cut off by maxOutput\
|
|
503
|
+
Tokens",comprobaciones:e};if(e.push("output-contract"),!t.schema)return {acepta:false,motivo:"no output contract to verify against",comprobaciones:e};let n;try{n=JSON.parse(t.texto);}catch{return {acepta:false,
|
|
504
|
+
motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=ae(n,t.schema);return r.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
|
|
505
|
+
acepta:false,motivo:`the cheap model's answer does not satisfy the output contract (${r.errors.slice(0,3).map(s=>`${s.path}: ${s.message}`).join("; ")})`,comprobaciones:e}}function Ss(t,e){let n,r;try{n=
|
|
506
|
+
JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=en(n),s=en(r);return o.length===0&&s.length===0?{divergen:false,motivo:"no comparab\
|
|
507
|
+
le facts (free prose only)"}:rc(o,s)?{divergen:false,motivo:"the hard values agree"}:{divergen:true,motivo:"both answers satisfy the contract but disagree on at least one hard value; this is the signature \
|
|
508
|
+
of a false valid \u2014 it is a reason to look, never a verdict"}}var nc=40;function en(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\
|
|
509
|
+
an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=nc&&n.push(`s:${r.toLowerCase()}`);}else if(Array.isArray(t))for(let r of t)en(r,e+1,n);else if(t&&typeof t=="objec\
|
|
510
|
+
t")for(let r of Object.keys(t).sort())en(t[r],e+1,n);return n.sort()}function rc(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 Ts="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\
|
|
511
|
+
, because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function oc(t){if(t<=0)return "";let e=Ts;for(;e.length<t;)e+=Ts;return e.slice(
|
|
512
|
+
0,t)}function sc(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 br(t){if(t.enum&&t.enum.length>0)return {valor:sc(t.enum)};switch(t.type??(t.properties?
|
|
513
|
+
"object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:oc(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?
|
|
514
|
+
{valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=br(t.items);return n?{valor:Array.from({length:t.maxItems},()=>n.valor)}:void 0}case "ob\
|
|
515
|
+
ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let s=br(o);if(!s)return;n[r]=s.valor;}return {valor:n}}default:return}}function ic(t){let e=br(
|
|
516
|
+
t);return e?JSON.stringify(e.valor):null}function Es(t,e){let n=ic(t);return n===null?null:e(n)}var tn=16,Rs=64,ac=8,cc="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 Cs(t,e,n,r={}){
|
|
517
|
+
let o=r.minimumSavingsTokens??ac,s;try{if(vr(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};s=wr(t,0);}catch(S){return {applied:false,reason:S instanceof
|
|
518
|
+
RangeError?"schema too deep or cyclic":"schema could not be compacted"}}if(s.renamed===0&&s.coded===0)return {applied:false,reason:"nothing to compact (no renameable keys, no codeable enums)"};let i=s.node;
|
|
519
|
+
if(!i)return {applied:false,reason:"nothing to compact"};let a=S=>Je(S,i,true),c=S=>Je(S,i,false),l=mc(t),u=lc(t,s.compact,i,l);if(!u.ok)return {applied:false,reason:u.reason};let d=e(JSON.stringify(t)),f=e(JSON.stringify(
|
|
520
|
+
s.compact)),m=d-f,h=Number.POSITIVE_INFINITY;for(let S of l){let L=e(JSON.stringify(S))-e(JSON.stringify(a(S)));L<h&&(h=L);}Number.isFinite(h)||(h=0);let p=S=>S/1e3*n.inputPer1k,g=S=>S/1e3*n.outputPer1k,
|
|
521
|
+
x=p(o),b=n.outputPer1k>0?(o-m)*n.inputPer1k/n.outputPer1k:Number.NEGATIVE_INFINITY,y=Number.isFinite(b)?b.toFixed(1):"any",E=n.inputPer1k>0?`${(n.outputPer1k/n.inputPer1k).toFixed(1)}x`:"more than",C=r.
|
|
522
|
+
evidencia;if(C==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\
|
|
523
|
+
e model, not of the schema: ${cc}. Here the compact contract saves ${m} input tokens and output is billed ${E} input, so it only pays while the output delta stays above ${y} tokens. Measure yours (ben\
|
|
524
|
+
chmarks/ab-live.ts) and pass it in`};let O=C.deltaTokens;if(O<0)return {applied:false,reason:`the measured output delta is ${O} tokens: this model writes MORE from a compact contract (${C.procedencia}). T\
|
|
525
|
+
he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${E} input, so no schema is big enough to buy it back`};let T=p(m)+g(O),D=n.inputPer1k>0?T*1e3/
|
|
526
|
+
n.inputPer1k:m,R=`+${O} tokens (${O>0?"the model wrote LESS":"no measured change"}), ${C.procedencia}`;return T<x?{applied:false,reason:`net saving $${T.toFixed(9)}/request is below the floor of ${o} inp\
|
|
527
|
+
ut tokens ($${x.toFixed(9)}): the compact contract saves ${m} input tokens and the measured output delta is ${R}; break-even at ${y}`}:{applied:true,reason:`net saving $${T.toFixed(9)}/request (${D.toFixed(
|
|
528
|
+
1)} input tokens equivalent): the compact contract saves ${m} input tokens and the measured output delta is ${R}; break-even at ${y}`,plan:{compactSchema:s.compact,expand:c,compact:a,renamedKeys:s.renamed,
|
|
529
|
+
codedEnumValues:s.coded,schemaTokensOriginal:d,schemaTokensCompact:f,modelledShapeSavingTokens:h,measuredOutputDeltaTokens:O,outputDeltaProvenance:C.procedencia,breakEvenOutputDeltaTokens:b,netSavingUsd:T}}}
|
|
530
|
+
function lc(t,e,n,r){for(let o of r){if(!ae(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let s=Je(o,n,true);if(!ae(s,e).valid)return {
|
|
531
|
+
ok:false,reason:"compact witness does not validate against the compact schema"};if(!kr(Je(s,n,false),o))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function Is(t){return t.type==="ob\
|
|
532
|
+
ject"||t.type==null&&t.properties!=null}function Os(t){return t.type==="array"||t.type==null&&t.items!=null}function uc(t){let e=t.enum;return !e||e.length===0||e.length>Rs||!e.every(n=>typeof n=="stri\
|
|
533
|
+
ng")?null:e}function wr(t,e){if(e>tn)throw new RangeError("schema too deep");let n=uc(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=_s(n,true);if(!r)return {compact:t,renamed:0,
|
|
534
|
+
coded:0};let o=[...r].filter(([i,a])=>i!==a).length;if(o===0)return {compact:t,renamed:0,coded:0};let s=new Map;for(let[i,a]of r)s.set(a,i);return {compact:{...t,enum:n.map(i=>r.get(i))},node:{enumFwd:r,
|
|
535
|
+
enumBack:s},renamed:0,coded:o}}return Is(t)?dc(t,e):Os(t)?pc(t,e):{compact:t,renamed:0,coded:0}}function dc(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};
|
|
536
|
+
let r=0,o=0,s=new Map,i=new Map;for(let[f,m]of n){let h=wr(m,e+1);i.set(f,h.compact),h.node&&s.set(f,h.node),r+=h.renamed,o+=h.coded;}let a=null;t.additionalProperties===false&&(a=_s(n.map(([f])=>f),false));
|
|
537
|
+
let c={};for(let[f]of n)c[a?.get(f)??f]=i.get(f);let l={...t,properties:c};t.required&&(l.required=t.required.map(f=>a?.get(f)??f));let u={};if(a){let f=new Map;for(let[h,p]of a)f.set(p,h);let m=false;for(let[
|
|
538
|
+
h,p]of a)h!==p&&(m=true);if(m){u.keysFwd=a,u.keysBack=f;for(let[h,p]of a)h!==p&&(r+=1);}}s.size>0&&(u.props=s);let d=!u.keysFwd&&!u.props;return {compact:l,...d?{}:{node:u},renamed:r,coded:o}}function pc(t,e){
|
|
539
|
+
if(!t.items)return {compact:t,renamed:0,coded:0};let n=wr(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function _s(t,e){let n=[
|
|
540
|
+
...t].sort(),r=new Set,o=new Map;n.forEach((i,a)=>{let c=e?i.toUpperCase():i,l=i;for(let u=1;u<i.length;u++){let d=c.slice(0,u);if(!r.has(d)){l=d;break}}if(l===i){let u=a.toString(36);u.length<i.length&&
|
|
541
|
+
!r.has(u)&&(l=u);}r.add(l),o.set(i,l);});let s=new Set(t);for(let[i,a]of o)if(a!==i&&s.has(a))return null;return o}function Je(t,e,n){let r=n?e.enumFwd:e.enumBack;if(r&&typeof t=="string")return r.get(t)??
|
|
542
|
+
t;if(e.items&&Array.isArray(t))return t.map(s=>Je(s,e.items,n));let o=n?e.keysFwd:e.keysBack;if((o||e.props)&&fc(t)){let s={};for(let[i,a]of Object.entries(t)){let c=o?.get(i)??i,l=n?i:c,u=e.props?.get(
|
|
543
|
+
l);s[c]=u?Je(a,u,n):a;}return s}return t}function fc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function mc(t){let e=Math.min(Rs,Math.max(1,xr(t,0))),n=[];for(let r=0;r<e;r++)n.push(yr(t,
|
|
544
|
+
r,0));return n}function xr(t,e){if(e>tn)return 0;let n=t.enum?.length??0;for(let r of Object.values(t.properties??{}))n=Math.max(n,xr(r,e+1));return t.items&&(n=Math.max(n,xr(t.items,e+1))),n}function yr(t,e,n){
|
|
545
|
+
if(n>tn)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(Is(t)){let r={};for(let[o,s]of Object.entries(t.properties??{}))r[o]=yr(s,e,n+1);return r}if(Os(t)){if(t.maxItems===
|
|
546
|
+
0)return [];let r=Math.max(1,t.minItems??1),o=t.maxItems!=null?Math.min(r,t.maxItems):r,s=t.items;return Array.from({length:o},()=>s?yr(s,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";
|
|
547
|
+
let r=Math.max(1,t.minLength??1),o=t.maxLength!=null?Math.min(r,t.maxLength):r;return "x".repeat(o)}case "number":case "integer":{let r=t.minimum??1;return t.maximum!=null&&r>t.maximum&&(r=t.maximum),t.type===
|
|
548
|
+
"integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function vr(t,e){if(e>tn)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.
|
|
549
|
+
values(t.properties??{}))if(vr(n,e+1))return true;return !!(t.items&&vr(t.items,e+1))}function kr(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.
|
|
550
|
+
isArray(t),r=Array.isArray(e);if(n||r){if(!n||!r||t.length!==e.length)return false;for(let i=0;i<t.length;i++)if(!kr(t[i],e[i]))return false;return true}let o=Object.keys(t),s=Object.keys(e);if(o.length!==s.length)
|
|
551
|
+
return false;for(let i of o)if(!Object.prototype.hasOwnProperty.call(e,i)||!kr(t[i],e[i]))return false;return true}var hc="2026-08-14",Ds={"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 \
|
|
552
|
+
enums)",pares:8}},gc=dn(Ds);function bc(t){return un(Ds,gc,t)}var nn=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&&
|
|
553
|
+
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,
|
|
554
|
+
origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let s=bc(e);return s?{deltaTokens:s.deltaTokens,origen:"catalogue",procedencia:`measured by Bi\
|
|
555
|
+
Velio on ${e} (${hc}, ${s.pares} paired reps, ${s.contrato}, ${s.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};function Sr(t,e){if(e?.cacheTier)return e.cacheTier;let n=t.toLowerCase(),r=n.indexOf("/"),o=r>0?n.slice(0,r):"",s=r>=0?n.slice(r+1):n;return o==="openai"||o==="azure-openai"?ur:o==="anthropic"?dr:o===
|
|
556
|
+
"google"||o==="google-vertex"?pr:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(s)?ur:s.startsWith("claude")?dr:s.startsWith("gemini")?pr:bs}function As(t){let e=t.prefix!=null,n=fr({originalTokens:t.originalTokens,
|
|
557
|
+
compressedTokens:t.compressedTokens,stablePrefixTokens:t.prefix?.stableTokens??0,prefixHitRate:t.prefix?.hitRate??0,tier:t.tier,...t.compressorCostTokens!=null?{compressorCostTokens:t.compressorCostTokens}:
|
|
558
|
+
{}});if(e)return n;let r=t.tier.minimumCacheTokens;return r!=null&&t.originalTokens>=r&&t.compressedTokens<r?{...n,comprimir:false,razon:`compressing would drop the prompt out of the cacheable tier (${t.
|
|
559
|
+
compressedTokens} < ${r}) and nobody has measured the prefix hit rate, so it cannot be claimed to pay for itself. Declare it in \`compressionEconomics.prefix\` to unlock the full decision`}:n}function Ls(t){let e=u=>u/1e3*t.precio.inputPer1k,n=u=>u/1e3*t.precio.outputPer1k,r=e(t.promptTokens+t.descriptoresLigeros)+n(t.salidaDelSondeo),o=e(t.promptTokens+t.esquemasCompletos)+n(t.salidaFinal),
|
|
560
|
+
s=r+e(t.promptTokens+t.esquemasDeLaSegunda)+n(t.salidaFinal),i=o-s,a=r,c=i>0&&i>=a,l;return i<=0?l=`descubrir cuesta m\xE1s de lo que ahorra: el prompt (${t.promptTokens} tokens) se paga dos veces y l\
|
|
561
|
+
os esquemas que se evitan (${t.esquemasCompletos-t.esquemasDeLaSegunda}) no lo cubren`:c?l=`se evitan ${t.esquemasCompletos-t.esquemasDeLaSegunda} tokens de esquema en el peor caso, bastante para paga\
|
|
562
|
+
r el prompt repetido y el sondeo`:l="la ganancia no cubre el coste de degradar: si el sondeo no elige, la petici\xF3n sale igual con todos los esquemas y el sondeo es coste puro",{aplicar:c,costeDeUnaLlamada:o,
|
|
563
|
+
costeDeDosLlamadas:s,ganancia:i,perdidaSiDegrada:a,razon:l}}function Ms(t){let n=(t.description??t.intents.join("; ")).trim().split(/\r?\n/,1)[0]??"",r=n.length>Ps?n.slice(0,Ps-1).trimEnd()+"\u2026":n;
|
|
564
|
+
return {id:t.id,intents:t.intents,risk:t.risk,...r?{description:r}:{}}}var Ps=200;function Bs(t,e,n){let r=new Map(e.map(c=>[c.id,c])),o=[],s=[],i=new Set;for(let c of t){let l=r.get(c);if(!l){s.push(c);
|
|
565
|
+
continue}o.includes(l.id)||(o.push(l.id),l.risk==="read"&&i.size<Math.max(0,n)&&i.add(l.id));}return {tools:e.filter(c=>c.risk!=="read"||i.has(c.id)),reconocidos:o,ignorados:s}}function js(t,e){let n=0,
|
|
566
|
+
r=[];for(let o of t)o.risk==="read"?r.push(o.tokens):n+=o.tokens;r.sort((o,s)=>s-o);for(let o of r.slice(0,Math.max(0,e)))n+=o;return n}var zs=new WeakSet;function xc(t){typeof t=="object"&&t!==null&&zs.add(t);}function yc(t){return typeof t=="object"&&t!==null&&zs.has(t)}function Fs(t){switch(t){case "none":return vc();case "invalid":return "\
|
|
567
|
+
BiVelio license key is not valid (it does not verify). Check you pasted the WHOLE key, and that it is the license key from your dashboard \u2014 not the `bvk_` service-account key, which goes in `serviceAc\
|
|
568
|
+
countKey`. Keys: https://savings.bivelio.com/dashboard/install (license status: invalid)";case "revoked":return "BiVelio license has been revoked. If this is unexpected, check your billing status at htt\
|
|
569
|
+
ps://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 plane in time \u2014 this is\
|
|
570
|
+
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 status: stale)";case "\
|
|
571
|
+
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 license is not active\
|
|
572
|
+
. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function vc(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 the signed token from y\
|
|
573
|
+
our subscription, verified offline. This published package has no unlicensed mode. Copy your key and a ready-to-paste snippet at https://savings.bivelio.com/dashboard/install (license status: none)"}function kc(){
|
|
574
|
+
return "licenseGate must implement isActive(): a gate that cannot prove the license is live is refused. In this published package an injected gate is not a licensing path at all \u2014 pass { licenseKey } i\
|
|
575
|
+
nstead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var rn=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new Xt;verjaDeCascada;memoriaDelCodebook=new nn;constructor(e){
|
|
576
|
+
this.config=e,this.deps=gs(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>pn()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.verjaDeCascada=new Qt(e.modelCascade?.
|
|
577
|
+
exploration!=null?{exploracion:e.modelCascade.exploration}:{});}async generate(e){this.assertLicensed();let n={llamadas:0,falloDelProveedor:false};try{return await this.generateOptimized(e,n)}catch(r){if(r instanceof
|
|
578
|
+
Ae||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||yc(r))throw r;return await this.failOpenDirect(e,r)}}async llamarProveedor(e,n){n.llamadas+=1;try{return await this.config.provider.generate(
|
|
579
|
+
e)}catch(r){throw n.falloDelProveedor=true,r}}decidirMarcadoDeCache(e,n,r,o,s,i,a){let c={marcar:false,huella:"",mensajesDePrefijo:0,cacheWriteMultiplier:1},l=Oc(n,this.config.compressionEconomics);if(!l)return a.
|
|
580
|
+
record("prefix-cache","skipped",{reason:`no cache read discount for model "${n}" (unrecognised provider, or a declared tier that does not discount reads): not claiming a cacheable prefix`}),c;if(!o.setIsStable)
|
|
581
|
+
return a.record("prefix-cache","skipped",{reason:"the tool SET is selected per request; tools render first, so the prefix cannot hit. Pruning wins here (it is a measured saving); pass the tools you wa\
|
|
582
|
+
nt fixed."}),c;if(s)return a.record("prefix-cache","skipped",{reason:"savings.toolDiscovery is on: which schemas travel is decided by a non-deterministic probe, so the tool block \u2014 which renders first\
|
|
583
|
+
\u2014 varies across requests that would share a prefix fingerprint. Marking would pay the 1.25x write premium for a prefix that cannot hit. Turn tool discovery off to reclaim the prefix cache."}),c;
|
|
584
|
+
if(i<=0)return c;let u=r.slice(0,i),d=this.tokensFor(this.assemblePromptText(u,o.tools),e),f=this.tokensFor(this.assemblePromptText(r,o.tools),e),m=ie(Se({model:n,tools:(o.tools??[]).map(p=>p.id),prefijo:u.
|
|
585
|
+
map(p=>`${p.role}:${p.content}`)})),h=this.verjaDeCache.decidir(m,{totalTokens:f,stablePrefixTokens:d,tier:l});return a.record("prefix-cache",h.marcar?"marked":"skipped",{reason:h.razon,stablePrefixTokens:d,
|
|
586
|
+
breakEvenHitRate:h.umbral,observedHitRate:h.observada}),h.marcar?{marcar:true,huella:m,mensajesDePrefijo:i,cacheWriteMultiplier:l.cacheWriteMultiplier}:c}decidirCascada(e,n,r,o){let s=r.modelCascade??"o\
|
|
587
|
+
ff",i={modo:"off",modeloPedido:e.model,modeloServido:e.model,candidato:null,enruta:false,elegible:false,razon:"the model cascade is off",fuerza:"none",bucket:"",economia:null,observada:null,muestras:0,precioBarato:null,
|
|
588
|
+
tasaDeMuestreo:0};if(s==="off")return i;let a=ws({schema:e.response?.schema,tools:e.tools}),c=ks(e.model,this.config.modelCascade?.pairs??mr),l=this.precioConocido(e.model),u=c?this.precioConocido(c):
|
|
589
|
+
void 0,d=vs(u,l),f=ie(Se({tenant:n.tenantId,scope:n.authorizationScope,contract:n.contractId,schema:n.schemaVersion,fuerte:e.model,barato:c,tools:n.toolsetHash})),m=this.verjaDeCascada.estado(f),h={modo:s,
|
|
590
|
+
modeloPedido:e.model,modeloServido:e.model,candidato:c,enruta:false,elegible:false,razon:a.razon,fuerza:a.fuerza,bucket:f,economia:d,observada:m&&m.enrutadas>0?m.escaladas/m.enrutadas:null,muestras:m?.enrutadas??
|
|
591
|
+
0,precioBarato:u??null,tasaDeMuestreo:0},p=b=>(o.record("model-cascade",s==="on"?"not routed":"not eligible",{reason:b}),{...h,razon:b});if(!a.elegible)return p(a.razon);if(!c)return p(`no cheaper mod\
|
|
592
|
+
el is paired with "${e.model}"; declare one in createSavingsLayer({ modelCascade: { pairs } }) if your provider has one`);if(!d){let b=[...this.precioConocido(e.model)?[]:[e.model],...u?[]:[c]];return p(
|
|
593
|
+
`no known price for ${b.map(y=>`"${y}"`).join(" or ")||"this pair"}, so the arithmetic that decides whether routing pays cannot be run. The illustrative default price is deliberately NOT used here: it\
|
|
594
|
+
would approve a pair nobody has priced. Pass \`costModels\` for both models to enable the cascade for them`)}if(!d.viable)return p(d.razon);let g=Math.min(1,Math.max(0,this.config.modelCascade?.shadowSampleRate??
|
|
595
|
+
0));if(s==="shadow")return o.record("model-cascade","shadow",{candidateModel:c,costRatio:d.r,breakEvenEscalationRate:d.equilibrio,verifier:a.fuerza,workload:f,note:"measuring only: the request goes to\
|
|
596
|
+
the model you asked for. The escalation rate is not a quality score \u2014 a well-formed answer with wrong content passes the verifier."}),{...h,elegible:true,razon:a.razon,tasaDeMuestreo:g};let x=this.
|
|
597
|
+
verjaDeCascada.decidir(f,d);return x.enrutar?(this.avisar(`cascada:${e.model}->${c}`,`[bv-sala] model cascade ON: requests for "${e.model}" may be answered by "${c}" when a deterministic gate accepts \
|
|
598
|
+
the answer. The gate checks the SHAPE of the answer against your output contract, never its meaning, so a well-formed answer with wrong content is served and counted as a success. report.model always \
|
|
599
|
+
names the model that answered, and report.qualityStatus reads "bounded_degradation".`),o.record("model-cascade","routed",{candidateModel:c,costRatio:d.r,breakEvenEscalationRate:d.equilibrio,observedEscalationRate:x.
|
|
600
|
+
observada,verifier:a.fuerza,workload:f,reason:x.razon}),{...h,modeloServido:c,enruta:true,elegible:true,razon:x.razon,observada:x.observada,muestras:x.muestras,tasaDeMuestreo:0}):(o.record("model-cascade",
|
|
601
|
+
"off (gate)",{reason:x.razon,observedEscalationRate:x.observada,breakEvenEscalationRate:d.equilibrio}),{...h,elegible:true,razon:x.razon,observada:x.observada,muestras:x.muestras})}devOpen(){return false}assertLicensed(){
|
|
602
|
+
if(this.devOpen())return;let e=this.config.licenseGate;if(e&&typeof e.isActive=="function"){if(e.isActive())return;let n=typeof e.status=="function"?e.status():void 0;throw new Ae(Fs(n),n)}throw e?new Ae(
|
|
603
|
+
kc(),"invalid"):new Ae(Fs("none"),"none")}avisar(e,n){this.config.silenceWarnings||G(e,n);}avisarDeTruncado(e,n,r,o,s){let i=e.response?.maxOutputTokens,a=ht(e)||"(sin contractId)",c=s?" La capa lo ha \
|
|
604
|
+
APUNTADO: las siguientes peticiones de este contrato llevar\xE1n sus l\xEDmites de valor escritos en el prompt, que es lo \xFAnico que puede corregirlo sin tocarte el tope. Si aun as\xED se corta, es que la tarea\
|
|
605
|
+
no cabe en el contrato: ensancha el esquema y sube el tope con \xE9l.":"",l=o===null?" El esquema no acota la respuesta (falta `maxLength`/`maxItems`), as\xED que no hay forma de saber de antemano cu\xE1nt\
|
|
606
|
+
o necesita: ac\xF3talo y el tope deja de ser una apuesta.":i==null?` El contrato autoriza ~${o} tokens y esta petici\xF3n no declara tope, as\xED que quien cort\xF3 fue un tope del PROVEEDOR (la API de Anthrop\
|
|
607
|
+
ic exige \`max_tokens\` y el adaptador manda 4096 por defecto). Declara \`maxOutputTokens\` y el corte deja de ser una sorpresa.`:o>i?` El contrato autoriza respuestas de hasta ~${o} tokens con este m\
|
|
608
|
+
odelo (lo que permiten sus \`maxLength\`/\`maxItems\`) y el tope son ${i}: ninguna respuesta que use lo que el propio esquema permite cabe. Un tope calibrado con otro modelo NO se hereda \u2014 el esquema \
|
|
609
|
+
acota CARACTERES, que son iguales en todas partes, y el tope acota TOKENS, que son distintos en cada tokenizador.`:` El contrato autoriza ~${o} tokens y el tope son ${i}, as\xED que el tope no es el prob\
|
|
610
|
+
lema: este modelo est\xE1 escribiendo m\xE1s de lo que su propio esquema permite (ning\xFAn modo estructurado impone \`maxLength\`).${c}`;this.avisar(`salida-truncada:${a}:${n}`,`[bvsala] La respuesta\
|
|
611
|
+
se cort\xF3 al agotar \`maxOutputTokens\`${i!=null?` (${i})`:""} con el modelo ${n} y el contrato \xAB${a}\xBB: el proveedor devolvi\xF3 finish_reason "length" y ${r} tokens de salida, as\xED que el JSO\
|
|
612
|
+
N no valida. NO se reintenta: con el mismo tope volver\xEDa a cortarse y ser\xEDa una llamada pagada para el mismo fallo.${l}`);}avisarDePalancasSinConfigurar(e){this.config.silenceWarnings||((e.compression===
|
|
613
|
+
true||e.compression==="auto")&&!this.config.compressor&&this.avisar("palanca-sin-compresor","[bv-sala] se pidi\xF3 `savings.compression` pero esta capa no tiene compresor, as\xED que NO se comprime nada: el c\
|
|
614
|
+
ontexto largo viaja y se paga entero. En el informe, `report.compression` sale AUSENTE y `tokens.eliminatedInput` a 0 \u2014 lo mismo que se ve cuando no hab\xEDa nada que comprimir. El compresor es un sideca\
|
|
615
|
+
r porque a\xF1ade latencia y c\xF3mputo que solo usted debe decidir pagar: ench\xFAfelo con `createSavingsLayer({ compressor })`, cualquier objeto con `compress({ text })`. Si su plan no incluye `long_context\
|
|
616
|
+
_compression`, har\xE1 falta adem\xE1s esa funci\xF3n. El resto de la capa sigue ahorrando igual."),e.semanticCache&&!this.deps.semanticCache&&this.avisar("palanca-sin-cache-semantica",'[bv-sala] se p\
|
|
617
|
+
idi\xF3 `savings.semanticCache` pero esta capa no tiene cach\xE9 sem\xE1ntica, as\xED que toda pregunta reformulada saldr\xE1 `cache: "miss"` y se pagar\xE1 al proveedor otra vez. No viene por defecto porque necesita u\
|
|
618
|
+
n embebedor, que es coste y proveedor suyos: ench\xFAfela con `createSavingsLayer({ semanticCache: new InMemorySemanticCache({ embed }) })`. La cach\xE9 exacta y el resto de la capa siguen funcionando.'));}async generateOptimized(e,n={
|
|
619
|
+
llamadas:0,falloDelProveedor:false}){this.assertLicensed();let r=new ot(this.now),o=new Ne,s=yn(e),i=kn(s),a=e.savings??{};this.avisarDePalancasSinConfigurar(a);let c=this.decidirCascada(e,s,a,r),l=this.
|
|
620
|
+
costModelFor(c.modeloServido);r.record("canonicalize","done",{tenant:s.tenantId,contract:s.contractId}),r.record("policy",i.reasons.join("; ")||"no restrictions",{allowExactCache:i.allowExactCache,allowSemanticCache:i.
|
|
621
|
+
allowSemanticCache});let u=this.tokensFor(this.assembleBaselinePrompt(e),e),d=e.response?.maxOutputTokens??256;if(o.baselineInput=u,o.baselineOutput=d,o.baselineTools=e.tools?.length??0,a.deterministicResolvers!==
|
|
622
|
+
false){let p=this.deps.resolvers.try(s);if(p)return o.avoidCall(u,this.tokensFor(p.text,e)),r.record("resolver",p.resolver,{avoided:true}),this.finish(e,s,{text:p.text,data:p.data,storedAtMs:this.now()},"d\
|
|
623
|
+
eterministic",o,l,r,ft(),mt(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(c,{servedModel:e.model}))}let f=vn(s,{servedModel:c.modeloServido});if(i.allowExactCache&&a.exactCache!==false){let p=await this.
|
|
624
|
+
deps.exactCache.get(f);if(p)return o.avoidCall(u,this.tokensFor(p.text,e)),r.record("exact-cache","hit",{ageMs:this.now()-p.storedAtMs}),this.finish(e,s,p,"exact",o,l,r,ft(),mt(),this.now()-p.storedAtMs,
|
|
625
|
+
void 0,void 0,void 0,void 0,this.informeDeCascada(c));r.record("exact-cache","miss");}let m=Mr(s,{servedModel:c.modeloServido,deferrable:a.deferrable===true,toolDiscovery:a.toolDiscovery===true,...e.response?.
|
|
626
|
+
maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{}}),h=async()=>{try{return await this.expensivePath(n,e,s,i,a,o,l,r,f,u,c)}catch(p){throw (n.falloDelProveedor||n.llamadas>0)&&xc(p),
|
|
627
|
+
p}};if(i.allowSingleflight&&a.singleflight!==false){let{value:p,coalesced:g}=await this.deps.singleflight.run(m,h);return g?(r.record("singleflight","coalesced",{key:m}),this.asCoalescedFollower(p,u,this.
|
|
628
|
+
tokensFor(p.text??"",e),l,e)):p}return h()}async expensivePath(e,n,r,o,s,i,a,c,l,u,d){let f=this.entitled("semantic_cache");if(o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&!f&&c.record(
|
|
629
|
+
"semantic-cache","degraded: feature not licensed (free tier)"),o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&f){let k=await this.deps.semanticCache.find(r);if(k)return i.avoidCall(u,
|
|
630
|
+
this.tokensFor(k.record.answer.text,n)),c.record("semantic-cache","hit",{confidence:k.confidence,similarity:k.similarity}),this.finish(n,r,k.record.answer,"semantic",i,a,c,ft(),mt(),k.ageMs,k.confidence,
|
|
631
|
+
void 0,void 0,void 0,this.informeDeCascada(d,{servedModel:n.model}));c.record("semantic-cache","miss");}let m=s.router===false,h=m?ft():this.deps.router.classify(r);c.record("router",h.executionClass,{confidence:h.
|
|
632
|
+
confidence,reason:h.reason});let p=m?this.deps.toolSelector.passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,h.executionClass);if(i.actualTools=p.tools.length,p.droppedIds.length){
|
|
633
|
+
let k=new Set(p.droppedIds),A=(n.tools??[]).filter(j=>k.has(j.id)).reduce((j,W)=>j+this.tokensFor(Tr(W),n),0);i.eliminate(A),c.record("tool-selector",p.reason,{dropped:p.droppedIds,eliminatedTokens:A});}
|
|
634
|
+
i.baselineRetrieval=h.rounds;let g=await Vr({execution:h.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.maxRounds??h.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?
|
|
635
|
+
{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});i.actualRetrieval=g.rounds,g.retrievedCount>0&&c.record("retrieval",`kept ${g.keptCount}/${g.retrievedCount}`,
|
|
636
|
+
{rounds:g.rounds});let x=mt(),b=[...n.messages],y=Rr(n.messages),E=false,C=g.docs.length>0?{role:"system",content:`Retrieved context \u2014 answer using only this evidence and cite sources by [id]:
|
|
15
637
|
|
|
16
|
-
`+
|
|
638
|
+
`+g.docs.map((k,A)=>`[${k.source??k.id??`doc${A+1}`}]
|
|
17
639
|
${k.text}`).join(`
|
|
18
640
|
|
|
19
|
-
`)}:null,O=
|
|
20
|
-
|
|
21
|
-
|
|
641
|
+
`)}:null,O=ht(n),T=n.response?.maxOutputTokens!=null?Math.floor(n.response.maxOutputTokens*3.2):null,D=this.contratosQueIncumplen.has(O)?Er(n.response?.schema,"",T):"";if(D&>(b,{role:"system",content:`\
|
|
642
|
+
JSON limits (not API-enforced): ${D}`}),n.structuredData!==void 0){let k=JSON.stringify(n.structuredData),A=this.tokensFor(k,n);if(s.serialization!==false){x=this.deps.formatSelector.choose(n.structuredData,
|
|
643
|
+
{model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let j=this.tokensFor(x.encoded+x.instruction,n);i.compress(A,j),gt(b,{role:"system",content:(x.instruction?x.instruction+`
|
|
644
|
+
`:"")+x.encoded}),c.record("serialization",x.chosen,{reason:x.reason,jsonTokens:A,chosenTokens:j});}else gt(b,{role:"system",content:k}),c.record("serialization","json-compact",{reason:"format selector\
|
|
645
|
+
disabled; sent compact JSON"});}if(C&>(b,C),(s.compression===true||s.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let k=this.config.compressionEconomics??
|
|
646
|
+
{},A=Sr(n.model,k),j={compressorCostTokens:k.compressorCostTokens??0,...k.minimumContextTokens!=null?{minimumContextTokens:k.minimumContextTokens}:{},...k.minimumNetTokens!=null?{minimumNetTokens:k.minimumNetTokens}:
|
|
647
|
+
{}},W=0,M=0;for(let F of b)F.role==="system"?W+=1:M+=this.tokensFor(F.content,n);let ee=this.tokensFor(this.assemblePromptText(b,p.tools),n),te=_n({...j,contextTokens:M,projectedEliminable:M}),ne=0,de=0,
|
|
648
|
+
Ze=false,pe=te.reason;if(te.compress){let F=[];for(let fe of b){if(fe.role==="system"){F.push(fe);continue}let Xe=this.tokensFor(fe.content,n),Qe=await this.config.compressor.compress({text:fe.content}),
|
|
649
|
+
Ir=!Qe.skipped&&Qe.fidelityPassed&&Qr(fe.content,Qe.compressed),Or=Ir?this.tokensFor(Qe.compressed,n):Xe;Ir&&Or<Xe?(F.push({...fe,content:Qe.compressed}),ne+=Xe,de+=Or):F.push(fe);}let Cr=this.tokensFor(
|
|
650
|
+
this.assemblePromptText(F,p.tools),n),Z=_n({...j,contextTokens:M,projectedEliminable:ne-de}),cn=As({originalTokens:ee,compressedTokens:Cr,tier:A,...k.prefix?{prefix:k.prefix}:{},compressorCostTokens:j.
|
|
651
|
+
compressorCostTokens});de>=ne?pe="no fidelity-passed net reduction":Z.compress?cn.comprimir?(Ze=true,pe=cn.razon,E=F.slice(0,y).some((fe,Xe)=>fe.content!==b[Xe]?.content),b=F,i.compress(ne,de)):pe=cn.razon:
|
|
652
|
+
pe=Z.reason;}Ze||(ne=0,de=0),c.record("compression",Ze?"applied":"skipped",{reason:pe,before:ne,after:de,contextTokens:M,promptTokens:ee,cacheTierMinimum:A.minimumCacheTokens,protectedSystemMessages:W,
|
|
653
|
+
prefixRewritten:E}),i.compressionReport={originalTokens:ne,compressedTokens:de,protectedSpans:W,fidelityPassed:true};}let R=n.response?.schema,S=R&&s.outputCodebook===true?Cs(R,k=>this.tokensFor(k,n),a,{evidencia:this.
|
|
654
|
+
memoriaDelCodebook.resolver(d.modeloServido,ht(n),s.outputCodebookMeasuredOutputDeltaTokens)}):null;S&&c.record("output-codebook",S.applied?"applied":"skipped",{reason:S.reason,...S.applied?{renamedKeys:S.
|
|
655
|
+
plan.renamedKeys,codedEnumValues:S.plan.codedEnumValues,schemaTokensOriginal:S.plan.schemaTokensOriginal,schemaTokensCompact:S.plan.schemaTokensCompact,modelledShapeSavingTokens:S.plan.modelledShapeSavingTokens,
|
|
656
|
+
measuredOutputDeltaTokens:S.plan.measuredOutputDeltaTokens,outputDeltaProvenance:S.plan.outputDeltaProvenance,breakEvenOutputDeltaTokens:S.plan.breakEvenOutputDeltaTokens,netSavingUsd:S.plan.netSavingUsd,
|
|
657
|
+
pricedForModel:d.modeloServido}:{}});let L=S?.applied?S.plan.compactSchema:R,v=L?Xr(d.modeloServido,L,this.deps.constraintBackends):{backend:"none",reason:"no output contract"};c.record("constraints",
|
|
658
|
+
v.backend,{reason:v.reason});let w=this.decidirMarcadoDeCache(n,d.modeloServido,b,p,s.toolDiscovery===true,E?Rr(b,true):y,c),_=this.now(),P=await this.descubrirHerramientas(e,n,s,p.tools,b,i,a,c),B=P.tools;
|
|
659
|
+
i.actualTools=B.length;let V={messages:b,...B.length?{tools:B}:{},...L?{schema:L}:{},...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{},...n.temperature!=null?{temperature:n.
|
|
660
|
+
temperature}:{},...n.seed!=null?{seed:n.seed}:{},...s.deferrable?{deferrable:true}:{},constraintBackend:v.backend},I=await this.llamarProveedor({model:d.modeloServido,...V,...w.marcar?{stablePrefixMessages:w.
|
|
661
|
+
mensajesDePrefijo,promptCacheKey:w.huella}:{}},e);i.actualLlm+=1;let X=k=>{if(!S?.applied)return k;let A=We(k);return A.ok?JSON.stringify(S.plan.expand(A.value)):k},$=X(I.text),Q=I.usage,J=false;if(d.enruta){
|
|
662
|
+
let k=gr({texto:$,schema:R,finishReason:I.finishReason,pidioHerramientas:(I.toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!k.acepta),c.record("model-cascade",k.acepta?"accepted":"es\
|
|
663
|
+
calating",{servedModel:d.modeloServido,reason:k.motivo,checks:k.comprobaciones}),k.acepta||(J=true,i.cascadeAttempt(I.usage,d.precioBarato??a),i.actualLlm+=1,I=await this.llamarProveedor({model:n.model,
|
|
664
|
+
...V},e),$=X(I.text));}let ue=J?n.model:d.modeloServido,ve=J?this.costModelFor(n.model):a;i.actualInput+=I.usage.inputTokens,i.actualOutput+=I.usage.outputTokens,S?.applied&&c.record("output-codebook",
|
|
665
|
+
We(I.text).ok?"expanded":"not-expanded (response was not JSON)",We(I.text).ok?{localOutputTokensCompact:this.tokensFor(I.text,n),localOutputTokensExpanded:this.tokensFor($,n),creditedLedger:"none",note:"\
|
|
666
|
+
local count of the served answer in both shapes; not credited to any ledger"}:{}),R&&v.backend==="provider-native"&&I.structuredNatively===false&&(v={backend:"none",reason:"provider did not enforce the c\
|
|
667
|
+
ontract natively; the schema travelled in the prompt and the layer is the only validator"},c.record("constraints","none",{downgradedFrom:"provider-native",reason:v.reason})),i.sentInputLocal=this.tokensFor(
|
|
668
|
+
this.assemblePromptText(b,B),n),i.removedInputLocal=Math.max(0,u-i.sentInputLocal),i.sentInputLocal+=P.tokensLocalesDelSondeo,i.estimatorExact=this.estimatorEsExacto(n),I.usage.cachedInputTokens&&i.providerCached(
|
|
669
|
+
I.usage.cachedInputTokens),w.marcar&&(i.cacheWritePremium(Q.cacheWriteInputTokens??0,w.cacheWriteMultiplier,d.precioBarato??a),this.verjaDeCache.registrar(w.huella,Q),c.record("prefix-cache","measured",
|
|
670
|
+
{cacheRead:Q.cachedInputTokens??0,cacheWritePremiumTokens:Q.cacheWriteInputTokens??0}));let ke=null;if(d.modo==="shadow"&&d.elegible&&d.candidato&&d.precioBarato&&Cc(l,d.tasaDeMuestreo))try{let k=await this.
|
|
671
|
+
llamarProveedor({model:d.candidato,...V},e);i.actualLlm+=1;let A=i.extraCostUsd;i.cascadeAttempt(k.usage,d.precioBarato);let j=X(k.text),W=gr({texto:j,schema:R,finishReason:k.finishReason,pidioHerramientas:(k.
|
|
672
|
+
toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!W.acepta);let M=W.acepta?Ss(j,$):null;ke={coste:i.extraCostUsd-A,divergio:M?M.divergen:null},c.record("model-cascade",W.acepta?"sample\
|
|
673
|
+
accepted":"sample escalated",{candidateModel:d.candidato,reason:W.motivo,sampleCost:ke.coste,...M?{diverged:M.divergen,divergence:M.motivo}:{},note:"measurement only: this answer was NEVER served. Th\
|
|
674
|
+
e escalation rate it feeds is a money figure, not a quality one"});}catch(k){c.record("model-cascade","sample failed (measurement only; the answer is unaffected)",{error:k instanceof Error?k.message:String(
|
|
675
|
+
k)});}let Ge=$,_e=true,Ye=(I.toolCalls?.length??0)>0;if(Ye&&(_e=null,R&&c.record("validation","n/a: model requested tool calls (the output contract applies to the final answer)")),R&&!Ye){let k=We($),A=k.
|
|
676
|
+
ok?ae(k.value,R):{valid:false,errors:[{path:"$",message:"not valid JSON"}]};k.ok&&k.rescatado!=null&&A.valid&&($=k.rescatado,c.record("validation","rescued-locally",{reason:"the model wrapped valid JSON \
|
|
677
|
+
in prose or a markdown fence; it was extracted locally instead of paying a repair call"})),!A.valid&&Ic(A.errors)&&this.contratosQueIncumplen.add(ht(n));let j=I.finishReason==="length",W=!A.valid&&A.errors.
|
|
678
|
+
some(M=>/not a valid regular expression/.test(M.message));if(!A.valid&&W)c.record("validation","repair-skipped",{reason:"schema defect (uncompilable pattern); no output can satisfy it, a retry is a wa\
|
|
679
|
+
sted call",errors:A.errors}),this.avisar("esquema-roto","[bvsala] El contrato de respuesta tiene un `pattern` que no es un regex valido, asi que ninguna respuesta puede cumplirlo. NO se reintenta (ser\
|
|
680
|
+
ia una llamada pagada para el mismo fallo). Corrige el `pattern` del esquema.");else if(!A.valid&&j){let M=Es(R,ne=>this.tokensFor(ne,n)),ee=n.response?.maxOutputTokens??null,te=M!==null&&ee!=null&&M<=
|
|
681
|
+
ee;te&&this.contratosQueIncumplen.add(ht(n)),c.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same cap would truncate again",maxOutputTokens:n.response?.
|
|
682
|
+
maxOutputTokens??null,outputTokens:I.usage.outputTokens,model:ue,...M!==null?{schemaAllowsTokens:M}:{},learnedValueLimits:te}),this.avisarDeTruncado(n,ue,I.usage.outputTokens,M,te);}else if(!A.valid&&v.
|
|
683
|
+
backend==="none"){let M=A.errors.slice(0,5).map(Z=>`- ${Z.path}: ${Z.message}`).join(`
|
|
684
|
+
`),ee=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
|
|
22
685
|
|
|
23
686
|
Previous reply:
|
|
24
687
|
${$}
|
|
@@ -26,8 +689,99 @@ ${$}
|
|
|
26
689
|
Problems found:
|
|
27
690
|
${M}
|
|
28
691
|
|
|
29
|
-
Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],ee=this.tokensFor(this.assemblePromptText(Q),n),te=i.sentInputLocal>0?i.actualInput/i.sentInputLocal:1,de=Math.round(te*ee),Ze=Math.min(I.usage.outputTokens,n.response?.maxOutputTokens??Number.POSITIVE_INFINITY),pe=de/1e3*ye.inputPer1k+Ze/1e3*ye.outputPer1k,F=this.config.skipRepairAboveBaseline?i.estimateCost(ye):void 0;if(F!=null&&F.baselineEstimate>0&&F.actual+pe>F.baselineEstimate&&F!=null)c.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the invalid answer is served as-is and reported as invalid",errors:A.errors,baselineUsd:F.baselineEstimate,actualUsd:F.actual,repairEstimateUsd:pe}),this.avisar("reparacion-mas-cara-que-el-baseline",`[bvsala] The answer did not satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${F.baselineEstimate}, already spent ~$${F.actual}, repair ~$${pe.toFixed(6)}). The repair was skipped and the invalid answer is returned with \`constraints.structurallyValid: false\` \u2014 check it before using it. This combination is usually a request carrying both tools and an output contract; see the adapter warning for the cheaper shapes.`);else {i.retries=1,c.record("validation","repair-attempt",{errors:A.errors}),I=await this.llamarProveedor({model:ue,messages:Q,schema:R,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),i.actualLlm+=1,i.actualInput+=I.usage.inputTokens,i.actualOutput+=I.usage.outputTokens,i.repairOutput+=I.usage.outputTokens,i.repairInput+=I.usage.inputTokens,i.sentInputLocal+=ee,$=I.text;let Z=Ge($);A=Z.ok?ae(Z.value,R):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},Z.ok&&(We=Z.value,Z.rescatado!=null&&A.valid&&($=Z.rescatado));}}else k.ok&&(We=k.value);_e=A.valid,c.record("validation",_e?"valid":"invalid");}let $s=this.now()-_,Fs=vc(We),nn={text:$,data:We,rendered:Fs,storedAtMs:this.now()},ke=this.informeDeDiferido(s,I,ye);ke&&c.record("deferred-tier",ke.credited?"credited":"not-credited",{...ke.requestedTier?{requestedTier:ke.requestedTier}:{},...ke.servedTier?{servedTier:ke.servedTier}:{},creditedLedger:"none",reason:ke.reason});try{let k=P.aplicado,A=I.finishReason==="length",j=_e!==!1&&!Ye&&!k&&!A;j||c.record("cache-write",Ye?"skipped: tool-call turn (an action request must not be replayed from cache)":_e===!1?"skipped: response fails its output contract":A?'skipped: answer cut off by the output cap (finish_reason "length"); replaying half an answer would bill it as a 100% avoided call':"skipped: answered with a reduced tool view (tool discovery), so it must not be replayed");let G=J?bn(r,{servedModel:ue}):l;if(j&&o.allowExactCache&&s.exactCache!==!1){let Q=this.config.exactCacheTtlMs??864e5,ee=o.maxCacheAgeMs==null?Q:Math.min(Q,o.maxCacheAgeMs);await this.deps.exactCache.set(G,nn,ee);}let M=ue!==n.model;j&&!M&&o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache?await this.deps.semanticCache.store(r,nn):j&&M&&s.semanticCache&&c.record("cache-write","semantic write skipped: a cheaper model answered, and this cache keys on the model the caller asked for");}catch(k){c.record("cache-write","failed (non-fatal; answer already served)",{error:k instanceof Error?k.message:String(k)});}let rn=this.finish(n,r,nn,"miss",i,ye,c,m,x,void 0,void 0,_e,v.backend,$s,this.informeDeCascada(d,{servedModel:ue,...d.enruta?{escalated:J}:{},...d.elegible&&d.precioBarato?{estimatedSwapSaving:wc(i,J,d.precioBarato,this.costModelFor(n.model))}:{},...ve?{sampled:true,sampleCost:tn(ve.coste),...ve.divergio!==null?{divergedOnSample:ve.divergio}:{}}:{},...i.cascadeInput>0||i.cascadeOutput>0?{cascadeInputTokens:i.cascadeInput,cascadeOutputTokens:i.cascadeOutput}:{}}),ke);return Ye&&(rn.toolCalls=I.toolCalls),I.finishReason!==void 0&&(rn.finishReason=I.finishReason),rn}async descubrirHerramientas(e,n,r,o,s,i,a,c){let l={tools:o,tokensLocalesDelSondeo:0,aplicado:false};if(r.toolDiscovery!==true)return l;if(o.length<2)return c.record("tool-discovery","skipped (nothing to discover)",{candidates:o.length}),l;let u=h=>this.tokensFor(vr(h),n),d=o.map(As),p=Ds({promptTokens:this.tokensFor(this.assemblePromptText(s),n),esquemasCompletos:o.reduce((h,x)=>h+u(x),0),descriptoresLigeros:d.reduce((h,x)=>h+u(x),0),esquemasDeLaSegunda:Ls(o.map(h=>({risk:h.risk,tokens:u(h)})),3),salidaFinal:n.response?.maxOutputTokens??256,salidaDelSondeo:96,precio:a});if(!p.aplicar)return c.record("tool-discovery","skipped (not worth a second call)",{reason:p.razon,oneCall:p.costeDeUnaLlamada,twoCalls:p.costeDeDosLlamadas}),l;let f,m=this.tokensFor(this.assemblePromptText(s,d),n);try{f=await this.llamarProveedor({model:n.model,messages:s,tools:d,maxOutputTokens:96,...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{}},e);}catch(h){return c.record("tool-discovery","failed (falling back to a single call with every schema)",{error:h instanceof Error?h.message:String(h)}),l}i.actualLlm+=1,i.actualInput+=f.usage.inputTokens,i.actualOutput+=f.usage.outputTokens,i.discoveryInput+=f.usage.inputTokens,i.discoveryOutput+=f.usage.outputTokens;let g=Ps((f.toolCalls??[]).map(h=>h.name),o,3);return g.reconocidos.length===0?(c.record("tool-discovery","degraded: probe named no known tool",{finishReason:f.finishReason??null,...g.ignorados.length?{unknownNames:g.ignorados}:{}}),{tools:o,tokensLocalesDelSondeo:m,aplicado:false}):(c.record("tool-discovery","applied (two provider calls)",{chosen:g.reconocidos,sent:g.tools.map(h=>h.id),candidates:o.length,...g.ignorados.length?{unknownNames:g.ignorados}:{}}),{tools:g.tools,tokensLocalesDelSondeo:m,aplicado:true})}informeDeCascada(e,n={}){if(e.modo!=="off")return {mode:e.modo,servedModel:n.servedModel??e.modeloServido,eligible:e.elegible,reason:e.razon,verifier:e.fuerza,creditedLedger:"none",...e.candidato?{candidateModel:e.candidato}:{},...e.economia?{costRatio:ct(e.economia.r),breakEvenEscalationRate:ct(e.economia.equilibrio),targetEscalationRate:ct(e.economia.escaladoMaximo)}:{},...e.bucket?{workload:e.bucket}:{},...e.observada!=null?{escalationRate:ct(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,r){if(e.deferrable!==true)return;let o=n.requestedServiceTier,s=eo(n.servedServiceTier),i={...o?{requestedTier:o}:{},...s?{servedTier:s.servido}:{},credited:false,creditedLedger:"none",latency:ro(o),reason:""};if(!o)return {...i,reason:no};if(!s)return {...i,reason:`asked the provider for the "${o}" tier, and it reported none back: the rate this request was billed at cannot be known, so nothing is credited`};if(s.factor==null)return {...i,reason:`asked for "${o}" and the provider reports serving "${s.servido}", a tier this layer has no published rate for: nothing is credited`};if(!s.conDescuento)return {...i,reason:`asked for "${o}" and the provider reports serving "${s.servido}", which bills at the standard rate: this request was billed as if it had never been deferred`};let a=n.usage,c=Math.min(Math.max(0,a.cachedInputTokens??0),Math.max(0,a.inputTokens)),l=r.cachedInputPer1k??r.inputPer1k,u=(Math.max(0,a.inputTokens)-c)/1e3*r.inputPer1k+c/1e3*l+Math.max(0,a.outputTokens)/1e3*r.outputPer1k,d=to(s,u);return {...i,credited:true,discountRate:ct(s.factor),...d!=null?{estimatedTierSaving:tn(d)}:{},reason:`the provider reports serving the "${s.servido}" tier, which bills at ${(s.factor*100).toFixed(0)}% of the standard rate; the discount stacks with provider prefix caching rather than replacing it`}}diferidoSinLlamada(e){if(e.savings?.deferrable===true)return {credited:false,creditedLedger:"none",latency:"not applicable: no provider call was made for this request.",reason:"no provider call was made, so no processing tier was served and none is credited; the call was avoided outright, which is worth more than any tier discount on it"}}finish(e,n,r,o,s,i,a,c,l,u,d,p,f="none",m=0,g,h){let x=e.response?.schema,b=p===null?null:p??(x?ae(r.data,x).valid:true),y=this.buildReport(e,n,o,s,i,a,c,l,u,d,b,f,m,g,h??this.diferidoSinLlamada(e));return {requestId:y.requestId,data:r.data,text:r.text,...r.rendered!==void 0?{rendered:r.rendered}:{},report:y}}buildReport(e,n,r,o,s,i,a,c,l,u,d,p,f,m,g){let h=o.estimateCost(s),x=i.elapsed(),b=m!=null&&m.servedModel!==m.requestedModel;return {requestId:this.generateId(),model:m?.servedModel??e.model,calls:{baselineLlm:o.baselineLlm,actualLlm:o.actualLlm,avoidedLlm:o.avoidedLlm,baselineRetrieval:o.baselineRetrieval,actualRetrieval:o.actualRetrieval,baselineTools:o.baselineTools,actualTools:o.actualTools,retries:o.retries},tokens:{baselineInput:o.baselineInput,actualInput:o.actualInput,eliminatedInput:o.eliminatedInput,compressedInput:o.compressedInput,baselineOutput:o.publishedBaselineOutput,actualOutput:o.actualOutput,eliminatedOutput:o.eliminatedOutput,...o.providerCachedInput?{providerCachedInput:o.providerCachedInput}:{}},cache:{result:r,...u!==void 0?{confidence:u}:{},...l!==void 0?{ageMs:l}:{}},routing:{executionClass:a.executionClass,confidence:a.confidence,rounds:o.actualRetrieval,reason:a.reason},serialization:{chosen:c.chosen,candidateTokens:c.candidateTokens,instructionOverheadTokens:c.instructionOverheadTokens},...o.compressionReport?{compression:o.compressionReport}:{},constraints:{backend:p,schemaVersion:n.schemaVersion,...d===null?{}:{structurallyValid:d}},qualityStatus:kc(r,d,b),...m?{modelCascade:m}:{},...g?{deferred:g}:{},quality:{...r!=="miss"?{freshnessPassed:!xn(n).requiresFreshData}:{}},cost:h,latencyMs:{total:x,preprocessing:Math.max(0,x-f),provider:f},traces:i.all()}}async failOpenDirect(e,n){let r=new et(this.now);r.record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",{error:n instanceof Error?n.message:String(n)});let o=new Ne,s=this.costModelFor(e.model),i;try{i=gn(e);}catch{i={schemaVersion:e.response?.version??e.response?.contractId??"none"};}let a=e.response?.schema,c=[...e.messages];e.structuredData!==void 0&&pt(c,{role:"system",content:JSON.stringify(e.structuredData)});let l=this.now(),u=await this.config.provider.generate({model:e.model,messages:c,...e.tools?.length?{tools:e.tools}:{},...a?{schema:a}:{},...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),d=this.now()-l;o.baselineLlm=1,o.actualLlm=1,o.actualInput=u.usage.inputTokens,o.actualOutput=u.usage.outputTokens,o.baselineInput=u.usage.inputTokens,o.baselineOutput=u.usage.outputTokens,u.usage.cachedInputTokens&&o.providerCached(u.usage.cachedInputTokens);let p=u.text,f=true,m=(u.toolCalls?.length??0)>0;if(m&&(f=null),a&&!m){let h=Ge(u.text);f=h.ok?ae(h.value,a).valid:false,h.ok&&(p=h.value);}let g=this.buildReport(e,i,"miss",o,s,r,lt(),ut(),void 0,void 0,f,"none",d,void 0,e.savings?.deferrable===true?{credited:false,creditedLedger:"none",latency:"unchanged: the fail-open path asks for no processing tier, so this request was scheduled exactly as an ordinary one.",reason:"the optimizer failed and this request went out on the direct fail-open path, which asks for no cheaper tier: that tier can be refused for lack of capacity, and trading availability for a discount on a last-resort call is the wrong trade"}:void 0);return {requestId:g.requestId,data:p,text:u.text,...m?{toolCalls:u.toolCalls}:{},...u.finishReason!==void 0?{finishReason:u.finishReason}:{},report:g}}asCoalescedFollower(e,n,r,o,s){let i=new Ne;i.avoidCall(n,r);let a=i.estimateCost(o),c=this.generateId(),l=this.diferidoSinLlamada(s),u=l?{deferred:l}:{},{deferred:d,...p}=e.report;return {...e,requestId:c,report:{...p,requestId:c,calls:{...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:i.baselineInput,actualInput:i.actualInput,eliminatedInput:i.eliminatedInput,compressedInput:i.compressedInput,baselineOutput:i.publishedBaselineOutput,actualOutput:i.actualOutput,eliminatedOutput:i.eliminatedOutput,...i.providerCachedInput?{providerCachedInput:i.providerCachedInput}:{}},cache:{result:"singleflight"},...u,cost:a}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,r){let o=e.map(s=>s.content);r!==void 0&&o.push(JSON.stringify(r));for(let s of n??[])o.push(vr(s));return o.join(`
|
|
30
|
-
|
|
692
|
+
Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],te=this.tokensFor(this.assemblePromptText(ee),n),ne=i.sentInputLocal>0?i.actualInput/i.sentInputLocal:1,de=Math.
|
|
693
|
+
round(ne*te),Ze=Math.min(I.usage.outputTokens,n.response?.maxOutputTokens??Number.POSITIVE_INFINITY),pe=de/1e3*ve.inputPer1k+Ze/1e3*ve.outputPer1k,F=this.config.skipRepairAboveBaseline?i.estimateCost(
|
|
694
|
+
ve):void 0;if(F!=null&&F.baselineEstimate>0&&F.actual+pe>F.baselineEstimate&&F!=null)c.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the inva\
|
|
695
|
+
lid answer is served as-is and reported as invalid",errors:A.errors,baselineUsd:F.baselineEstimate,actualUsd:F.actual,repairEstimateUsd:pe}),this.avisar("reparacion-mas-cara-que-el-baseline",`[bvsala]\
|
|
696
|
+
The answer did not satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${F.baselineEstimate}, already spent ~$${F.actual}\
|
|
697
|
+
, repair ~$${pe.toFixed(6)}). The repair was skipped and the invalid answer is returned with \`constraints.structurallyValid: false\` \u2014 check it before using it. This combination is usually a request ca\
|
|
698
|
+
rrying both tools and an output contract; see the adapter warning for the cheaper shapes.`);else {i.retries=1,c.record("validation","repair-attempt",{errors:A.errors}),I=await this.llamarProveedor({model:ue,
|
|
699
|
+
messages:ee,schema:R,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),i.actualLlm+=1,i.actualInput+=I.usage.inputTokens,i.actualOutput+=I.usage.outputTokens,i.repairOutput+=
|
|
700
|
+
I.usage.outputTokens,i.repairInput+=I.usage.inputTokens,i.sentInputLocal+=te,$=I.text;let Z=We($);A=Z.ok?ae(Z.value,R):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},Z.ok&&(Ge=Z.value,Z.rescatado!=
|
|
701
|
+
null&&A.valid&&($=Z.rescatado));}}else k.ok&&(Ge=k.value);_e=A.valid,c.record("validation",_e?"valid":"invalid");}let Vs=this.now()-_,Us=Tc(Ge),sn={text:$,data:Ge,rendered:Us,storedAtMs:this.now()},we=this.
|
|
702
|
+
informeDeDiferido(s,I,ve);we&&c.record("deferred-tier",we.credited?"credited":"not-credited",{...we.requestedTier?{requestedTier:we.requestedTier}:{},...we.servedTier?{servedTier:we.servedTier}:{},creditedLedger:"\
|
|
703
|
+
none",reason:we.reason});try{let k=P.aplicado,A=I.finishReason==="length",j=_e!==!1&&!Ye&&!k&&!A;j||c.record("cache-write",Ye?"skipped: tool-call turn (an action request must not be replayed from cach\
|
|
704
|
+
e)":_e===!1?"skipped: response fails its output contract":A?'skipped: answer cut off by the output cap (finish_reason "length"); replaying half an answer would bill it as a 100% avoided call':"skipped\
|
|
705
|
+
: answered with a reduced tool view (tool discovery), so it must not be replayed");let W=J?vn(r,{servedModel:ue}):l;if(j&&o.allowExactCache&&s.exactCache!==!1){let ee=this.config.exactCacheTtlMs??864e5,
|
|
706
|
+
te=o.maxCacheAgeMs==null?ee:Math.min(ee,o.maxCacheAgeMs);await this.deps.exactCache.set(W,sn,te);}let M=ue!==n.model;j&&!M&&o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache?await this.deps.
|
|
707
|
+
semanticCache.store(r,sn):j&&M&&s.semanticCache&&c.record("cache-write","semantic write skipped: a cheaper model answered, and this cache keys on the model the caller asked for");}catch(k){c.record("ca\
|
|
708
|
+
che-write","failed (non-fatal; answer already served)",{error:k instanceof Error?k.message:String(k)});}let an=this.finish(n,r,sn,"miss",i,ve,c,h,x,void 0,void 0,_e,v.backend,Vs,this.informeDeCascada(d,
|
|
709
|
+
{servedModel:ue,...d.enruta?{escalated:J}:{},...d.elegible&&d.precioBarato?{estimatedSwapSaving:Rc(i,J,d.precioBarato,this.costModelFor(n.model))}:{},...ke?{sampled:true,sampleCost:on(ke.coste),...ke.divergio!==
|
|
710
|
+
null?{divergedOnSample:ke.divergio}:{}}:{},...i.cascadeInput>0||i.cascadeOutput>0?{cascadeInputTokens:i.cascadeInput,cascadeOutputTokens:i.cascadeOutput}:{}}),we);return Ye&&(an.toolCalls=I.toolCalls),
|
|
711
|
+
I.finishReason!==void 0&&(an.finishReason=I.finishReason),an}async descubrirHerramientas(e,n,r,o,s,i,a,c){let l={tools:o,tokensLocalesDelSondeo:0,aplicado:false};if(r.toolDiscovery!==true)return l;if(o.length<
|
|
712
|
+
2)return c.record("tool-discovery","skipped (nothing to discover)",{candidates:o.length}),l;let u=g=>this.tokensFor(Tr(g),n),d=o.map(Ms),f=Ls({promptTokens:this.tokensFor(this.assemblePromptText(s),n),
|
|
713
|
+
esquemasCompletos:o.reduce((g,x)=>g+u(x),0),descriptoresLigeros:d.reduce((g,x)=>g+u(x),0),esquemasDeLaSegunda:js(o.map(g=>({risk:g.risk,tokens:u(g)})),3),salidaFinal:n.response?.maxOutputTokens??256,salidaDelSondeo:96,
|
|
714
|
+
precio:a});if(!f.aplicar)return c.record("tool-discovery","skipped (not worth a second call)",{reason:f.razon,oneCall:f.costeDeUnaLlamada,twoCalls:f.costeDeDosLlamadas}),l;let m,h=this.tokensFor(this.
|
|
715
|
+
assemblePromptText(s,d),n);try{m=await this.llamarProveedor({model:n.model,messages:s,tools:d,maxOutputTokens:96,...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{}},
|
|
716
|
+
e);}catch(g){return c.record("tool-discovery","failed (falling back to a single call with every schema)",{error:g instanceof Error?g.message:String(g)}),l}i.actualLlm+=1,i.actualInput+=m.usage.inputTokens,
|
|
717
|
+
i.actualOutput+=m.usage.outputTokens,i.discoveryInput+=m.usage.inputTokens,i.discoveryOutput+=m.usage.outputTokens;let p=Bs((m.toolCalls??[]).map(g=>g.name),o,3);return p.reconocidos.length===0?(c.record(
|
|
718
|
+
"tool-discovery","degraded: probe named no known tool",{finishReason:m.finishReason??null,...p.ignorados.length?{unknownNames:p.ignorados}:{}}),{tools:o,tokensLocalesDelSondeo:h,aplicado:false}):(c.record(
|
|
719
|
+
"tool-discovery","applied (two provider calls)",{chosen:p.reconocidos,sent:p.tools.map(g=>g.id),candidates:o.length,...p.ignorados.length?{unknownNames:p.ignorados}:{}}),{tools:p.tools,tokensLocalesDelSondeo:h,
|
|
720
|
+
aplicado:true})}informeDeCascada(e,n={}){if(e.modo!=="off")return {mode:e.modo,servedModel:n.servedModel??e.modeloServido,eligible:e.elegible,reason:e.razon,verifier:e.fuerza,creditedLedger:"none",...e.candidato?
|
|
721
|
+
{candidateModel:e.candidato}:{},...e.economia?{costRatio:pt(e.economia.r),breakEvenEscalationRate:pt(e.economia.equilibrio),targetEscalationRate:pt(e.economia.escaladoMaximo)}:{},...e.bucket?{workload:e.
|
|
722
|
+
bucket}:{},...e.observada!=null?{escalationRate:pt(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,r){if(e.deferrable!==true)return;let o=n.requestedServiceTier,
|
|
723
|
+
s=ro(n.servedServiceTier),i={...o?{requestedTier:o}:{},...s?{servedTier:s.servido}:{},credited:false,creditedLedger:"none",latency:io(o),reason:""};if(!o)return {...i,reason:so};if(!s)return {...i,reason:`\
|
|
724
|
+
asked the provider for the "${o}" tier, and it reported none back: the rate this request was billed at cannot be known, so nothing is credited`};if(s.factor==null)return {...i,reason:`asked for "${o}" \
|
|
725
|
+
and the provider reports serving "${s.servido}", a tier this layer has no published rate for: nothing is credited`};if(!s.conDescuento)return {...i,reason:`asked for "${o}" and the provider reports ser\
|
|
726
|
+
ving "${s.servido}", which bills at the standard rate: this request was billed as if it had never been deferred`};let a=n.usage,c=Math.min(Math.max(0,a.cachedInputTokens??0),Math.max(0,a.inputTokens)),
|
|
727
|
+
l=r.cachedInputPer1k??r.inputPer1k,u=(Math.max(0,a.inputTokens)-c)/1e3*r.inputPer1k+c/1e3*l+Math.max(0,a.outputTokens)/1e3*r.outputPer1k,d=oo(s,u);return {...i,credited:true,discountRate:pt(s.factor),...d!=
|
|
728
|
+
null?{estimatedTierSaving:on(d)}:{},reason:`the provider reports serving the "${s.servido}" tier, which bills at ${(s.factor*100).toFixed(0)}% of the standard rate; the discount stacks with provider p\
|
|
729
|
+
refix caching rather than replacing it`}}diferidoSinLlamada(e){if(e.savings?.deferrable===true)return {credited:false,creditedLedger:"none",latency:"not applicable: no provider call was made for this reques\
|
|
730
|
+
t.",reason:"no provider call was made, so no processing tier was served and none is credited; the call was avoided outright, which is worth more than any tier discount on it"}}finish(e,n,r,o,s,i,a,c,l,u,d,f,m="\
|
|
731
|
+
none",h=0,p,g){let x=e.response?.schema,b=f===null?null:f??(x?ae(r.data,x).valid:true),y=this.buildReport(e,n,o,s,i,a,c,l,u,d,b,m,h,p,g??this.diferidoSinLlamada(e));return {requestId:y.requestId,data:r.data,
|
|
732
|
+
text:r.text,...r.rendered!==void 0?{rendered:r.rendered}:{},report:y}}buildReport(e,n,r,o,s,i,a,c,l,u,d,f,m,h,p){let g=o.estimateCost(s),x=i.elapsed(),b=h!=null&&h.servedModel!==h.requestedModel;return {
|
|
733
|
+
requestId:this.generateId(),model:h?.servedModel??e.model,calls:{baselineLlm:o.baselineLlm,actualLlm:o.actualLlm,avoidedLlm:o.avoidedLlm,baselineRetrieval:o.baselineRetrieval,actualRetrieval:o.actualRetrieval,
|
|
734
|
+
baselineTools:o.baselineTools,actualTools:o.actualTools,retries:o.retries},tokens:{baselineInput:o.baselineInput,actualInput:o.actualInput,eliminatedInput:o.eliminatedInput,compressedInput:o.compressedInput,
|
|
735
|
+
baselineOutput:o.publishedBaselineOutput,actualOutput:o.actualOutput,eliminatedOutput:o.eliminatedOutput,...o.providerCachedInput?{providerCachedInput:o.providerCachedInput}:{}},cache:{result:r,...u!==
|
|
736
|
+
void 0?{confidence:u}:{},...l!==void 0?{ageMs:l}:{}},routing:{executionClass:a.executionClass,confidence:a.confidence,rounds:o.actualRetrieval,reason:a.reason},serialization:{chosen:c.chosen,candidateTokens:c.
|
|
737
|
+
candidateTokens,instructionOverheadTokens:c.instructionOverheadTokens},...o.compressionReport?{compression:o.compressionReport}:{},constraints:{backend:f,schemaVersion:n.schemaVersion,...d===null?{}:{
|
|
738
|
+
structurallyValid:d}},qualityStatus:Ec(r,d,b),...h?{modelCascade:h}:{},...p?{deferred:p}:{},quality:{...r!=="miss"?{freshnessPassed:!kn(n).requiresFreshData}:{}},cost:g,latencyMs:{total:x,preprocessing:Math.
|
|
739
|
+
max(0,x-m),provider:m},traces:i.all()}}async failOpenDirect(e,n){let r=new ot(this.now);r.record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",{error:n instanceof Error?
|
|
740
|
+
n.message:String(n)});let o=new Ne,s=this.costModelFor(e.model),i;try{i=yn(e);}catch{i={schemaVersion:e.response?.version??e.response?.contractId??"none"};}let a=e.response?.schema,c=[...e.messages];e.structuredData!==
|
|
741
|
+
void 0&>(c,{role:"system",content:JSON.stringify(e.structuredData)});let l=this.now(),u=await this.config.provider.generate({model:e.model,messages:c,...e.tools?.length?{tools:e.tools}:{},...a?{schema:a}:
|
|
742
|
+
{},...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),d=this.now()-l;o.baselineLlm=
|
|
743
|
+
1,o.actualLlm=1,o.actualInput=u.usage.inputTokens,o.actualOutput=u.usage.outputTokens,o.baselineInput=u.usage.inputTokens,o.baselineOutput=u.usage.outputTokens,u.usage.cachedInputTokens&&o.providerCached(
|
|
744
|
+
u.usage.cachedInputTokens);let f=u.text,m=true,h=(u.toolCalls?.length??0)>0;if(h&&(m=null),a&&!h){let g=We(u.text);m=g.ok?ae(g.value,a).valid:false,g.ok&&(f=g.value);}let p=this.buildReport(e,i,"miss",o,s,r,
|
|
745
|
+
ft(),mt(),void 0,void 0,m,"none",d,void 0,e.savings?.deferrable===true?{credited:false,creditedLedger:"none",latency:"unchanged: the fail-open path asks for no processing tier, so this request was schedule\
|
|
746
|
+
d exactly as an ordinary one.",reason:"the optimizer failed and this request went out on the direct fail-open path, which asks for no cheaper tier: that tier can be refused for lack of capacity, and t\
|
|
747
|
+
rading availability for a discount on a last-resort call is the wrong trade"}:void 0);return {requestId:p.requestId,data:f,text:u.text,...h?{toolCalls:u.toolCalls}:{},...u.finishReason!==void 0?{finishReason:u.
|
|
748
|
+
finishReason}:{},report:p}}asCoalescedFollower(e,n,r,o,s){let i=new Ne;i.avoidCall(n,r);let a=i.estimateCost(o),c=this.generateId(),l=this.diferidoSinLlamada(s),u=l?{deferred:l}:{},{deferred:d,...f}=e.
|
|
749
|
+
report;return {...e,requestId:c,report:{...f,requestId:c,calls:{...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:i.baselineInput,actualInput:i.actualInput,eliminatedInput:i.eliminatedInput,
|
|
750
|
+
compressedInput:i.compressedInput,baselineOutput:i.publishedBaselineOutput,actualOutput:i.actualOutput,eliminatedOutput:i.eliminatedOutput,...i.providerCachedInput?{providerCachedInput:i.providerCachedInput}:
|
|
751
|
+
{}},cache:{result:"singleflight"},...u,cost:a}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,r){let o=e.map(s=>s.content);r!==void 0&&
|
|
752
|
+
o.push(JSON.stringify(r));for(let s of n??[])o.push(Tr(s));return o.join(`
|
|
753
|
+
`)}tokensFor(e,n){return this.config.tokenizer.count(e,{...n.tokenizer?{tokenizer:n.tokenizer}:{},model:n.model})}estimatorEsExacto(e){let n=this.config.tokenizer;if(typeof n.resolve!="function")return false;
|
|
754
|
+
try{return n.resolve({...e.tokenizer?{tokenizer:e.tokenizer}:{},model:e.model}).exact===!0}catch{return false}}entitled(e){return this.devOpen()?true:!!this.config.licenseGate&&this.config.licenseGate.isEntitled(
|
|
755
|
+
e)}precioConocido(e){let n=this.config.costModels;if(n){let r=n[e];if(r)return r;let o=e.indexOf("/");if(o>=0){let s=n[e.slice(o+1)];if(s)return s}}return bt(e)}costModelFor(e){let n=this.precioConocido(
|
|
756
|
+
e);return n||(this.config.defaultCostModel?this.config.defaultCostModel:(this.avisar(`precio-ilustrativo:${e}`,`[bv-sala] no cost model configured for "${e}"; falling back to the ILLUSTRATIVE default \
|
|
757
|
+
price. Dollar figures will not match your bill. Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),hs))}};function We(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of wc(t))try{
|
|
758
|
+
return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function wc(t){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&&
|
|
759
|
+
e.push(o);}for(let r of ["{","["]){let o=t.indexOf(r);if(o===-1)continue;let s=Sc(t,o);s&&e.push(s);}return e}function Sc(t,e){let n=t[e],r=n==="{"?"}":"]",o=0,s=false,i=false;for(let a=e;a<t.length;a+=1){let c=t[a];
|
|
760
|
+
if(s){i?i=false:c==="\\"?i=true:c==='"'&&(s=false);continue}if(c==='"'){s=true;continue}if(c===n)o+=1;else if(c===r&&(o-=1,o===0))return t.slice(e,a+1)}}function Tc(t){return typeof t=="string"?t:JSON.stringify(
|
|
761
|
+
t,null,2)}function Ec(t,e,n=false){if(e===false)return "rejected";if(n)return "bounded_degradation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "\
|
|
762
|
+
not_verified"}}function pt(t){return Math.round(t*1e6)/1e6}function on(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Rc(t,e,n,r){if(e)return on(-t.extraCostUsd);let o=s=>t.actualInput/1e3*
|
|
763
|
+
s.inputPer1k+t.actualOutput/1e3*s.outputPer1k;return on(o(r)-o(n))}function Cc(t,e){if(!(e>0))return false;if(e>=1)return true;let n=ie(`${t}:cascade-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}
|
|
764
|
+
function ft(){return {executionClass:"NO_RETRIEVAL",confidence:1,reason:"n/a (short-circuited)",rounds:0}}function mt(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,
|
|
765
|
+
reason:"no structured payload"}}function Er(t,e="",n=null){if(t==null||typeof t!="object")return "";let r=t,o=[],s=e||"the value",i=h=>typeof r[h]=="number"?r[h]:null,a=i("maxLength"),c=i("minLength"),
|
|
766
|
+
l=i("maxItems"),u=i("minItems"),d=i("maximum"),f=i("minimum");if(a!=null){let h=n!=null?Math.min(a,n):a;o.push(`${s}<=${h}ch`);}c!=null&&o.push(`${s}>=${c}ch`),l!=null&&o.push(`${s}<=${l} items`),u!=null&&
|
|
767
|
+
o.push(`${s}>=${u} items`),d!=null&&o.push(`${s}<=${d}`),f!=null&&o.push(`${s}>=${f}`),typeof r.pattern=="string"&&o.push(`${s} matches /${r.pattern}/`);let m=r.properties;if(m&&typeof m=="object")for(let[
|
|
768
|
+
h,p]of Object.entries(m)){let g=Er(p,e?`${e}.${h}`:h,n);g&&o.push(g);}if(r.items!==void 0){let h=Er(r.items,`${s} entries`,n);h&&o.push(h);}return o.join("; ")}function ht(t){let e=t.response;return e?e.
|
|
769
|
+
contractId??e.version??JSON.stringify(e.schema??{}).slice(0,200):""}function Ic(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.
|
|
770
|
+
test(e.message))}function Tr(t){return JSON.stringify({type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function gt(t,e){
|
|
771
|
+
for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}function Rr(t,e=false){if(e){let n=0;for(;n<t.length&&t[n].role==="system";)n+=1;return n}for(let n=t.length-1;n>=0;n--)
|
|
772
|
+
if(t[n].role==="user")return n;return Rr(t,true)}function Oc(t,e){let n=Sr(t,e);return n.cacheReadMultiplier<1?n:null}var _c=72*3600;function ef(t){t.licenseGate&&(console.warn("[bvsala] Ignoring the injected `licenseGate`: in the published package a license is only accepted as a `licenseKey` verified against BiVelio\
|
|
773
|
+
's embedded public key. Get yours at https://savings.bivelio.com/dashboard/install"),t={...t,licenseGate:void 0});let n={...t,tokenizer:t.tokenizer??_r},r,o;if(t.licenseKey&&!t.licenseGate){let a=cs;if(t.licenseServerUrl){let c=new qe,l=f=>Jt(f,a,{revocation:c,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??_c}),u=l(t.licenseKey);n.licenseGate=
|
|
774
|
+
{isEntitled:f=>u.isEntitled(f),isActive:()=>u.isActive(),status:()=>u.status()};let d=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;r=new Wt({url:d,publicKeyPem:a,snapshot:c,getRefreshAfter:()=>u.
|
|
775
|
+
refreshAfter?.(),...t.now?{nowSeconds:()=>Math.floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.licensePollIntervalSeconds}:
|
|
776
|
+
{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{},...t.licenseRevocation??{}}),r.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(o=new Yt({url:`${t.licenseServerUrl.replace(
|
|
777
|
+
/\/+$/,"")}/api/license/current`,serviceAccountKey:t.serviceAccountKey,publicKey:a,initialToken:t.licenseKey,revocados:c,onNewToken:f=>{u=l(f);},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?
|
|
778
|
+
{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),o.start());}else
|
|
779
|
+
n.licenseGate=fs(t.licenseKey,a,t.now);}let s=new rn(n),i;if(t.serviceAccountKey&&t.metering?.enabled!==false){let a=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/meteri\
|
|
780
|
+
ng/usage`:void 0);if(a){i=new dt({url:a,serviceAccountKey:t.serviceAccountKey,...t.metering?.orgId?{orgId:t.metering.orgId}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:
|
|
781
|
+
{},...t.metering?.maxBatch!=null?{maxBatch:t.metering.maxBatch}:{},...t.metering?.maxBuffer!=null?{maxBuffer:t.metering.maxBuffer}:{},...t.meteringFetch?{fetchImpl:t.meteringFetch}:t.licenseFetch?{fetchImpl:t.
|
|
782
|
+
licenseFetch}:{},...t.now?{now:t.now}:{},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let c=t.metering?.ci??cr();if(t.metering?.seatId)
|
|
783
|
+
i.setSeat(t.metering.seatId,c);else {let l=i;lr(t.serviceAccountKey).then(u=>l.setSeat(u,c)).catch(()=>{});}i.start();}}return {generate:async a=>{let c=await s.generate(a);if(i)try{i.record(c.report);}catch{}
|
|
784
|
+
return c},close:()=>{r?.stop(),o?.stop(),i?.stop();}}}var af="0.4.4";/*! Bundled license information:
|
|
31
785
|
|
|
32
786
|
@noble/curves/utils.js:
|
|
33
787
|
@noble/curves/abstract/modular.js:
|
|
@@ -35,4 +789,4 @@ Return ONLY the corrected JSON object. Keep the same content; fix only what is l
|
|
|
35
789
|
@noble/curves/abstract/edwards.js:
|
|
36
790
|
@noble/curves/ed25519.js:
|
|
37
791
|
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
38
|
-
*/export{
|
|
792
|
+
*/export{fo as AnthropicProvider,af as BV_SALA_VERSION,ln as CATALOGO,Pi as COMPACT_ROWS_INSTRUCTION,hs as DEFAULT_COST_MODEL,_c as DEFAULT_MAX_STALENESS_SECONDS,cs as EMBEDDED_PUBLIC_KEY,hn as ExactTokenizer,kt as ExecutionRouter,Rt as FormatSelector,fn as HeuristicEstimator,yt as InMemoryExactCache,$r as InMemorySemanticCache,Ae as LicenseError,Hc as MODELOS_POR_CODIFICACION,Dr as MODELS_BY_ENCODING,Dn as MockProvider,co as OpenAICompatibleProvider,qs as PRECIOS_AL_DIA,Mc as QUALITY_STATUSES,Sn as ResolverRegistry,Wt as RevocationPoller,qe as RevocationSnapshot,Ne as SavingsLedger,Ct as SchemaRegistry,vt as Singleflight,mn as TokenizerRegistry,wt as ToolSelector,ot as TraceCollector,jr as UMBRAL_LOCAL,dt as UsageEmitter,wi as adaptiveK,fi as arithmeticResolver,vn as buildExactKey,Mr as buildInflightKey,yn as canonicalize,Wr as compactRowsSerializer,Qr as compresionFiel,Pa as computeNextDelay,ai as cosine,Li as createCompactRowsSerializer,Fr as createDefaultResolvers,jc as createHandoff,yu as createMockProvider,ef as createSavingsLayer,Yr as csvSerializer,qr as decodeCompactRows,ki as dedupe,_r as defaultTokenizerRegistry,lr as deriveSeatId,ar as deriveStatus,cr as detectCi,Br as embebedorLocal,Pl as emptyState,_i as encodeCompactRows,gi as evalArithmetic,kn as evaluatePolicy,Vr as executeRetrievalPlan,fs as gateFromKey,je as heuristicEstimator,Oa as isKeyset,De as isStrictCompatible,Ur as jsonCompactSerializer,di as keyTokensMatch,Jt as liveGateFromKey,Ll as mergeDelta,xn as modelFamilyOf,wn as multisetEqual,nt as negationCount,pu as noopCompressor,xt as normalizeText,et as numericTokens,bt as precioDeLista,Ml as projectContext,ou as providerNativeBackend,pn as randomId,Js as registerExactTokenizer,Kc as registrarTokenizadorExacto,Ti as renderState,Xr as resolveConstraintBackend,gs as resolveDependencies,vd as resolveLicense,ie as sha256,_n as shouldCompress,Se as stableStringify,Et as uniformColumns,ae as validateAgainstSchema,ii as vectorLocal,ir as verifyCompactSignature,Ue as verifyLicenseToken,ps as verifyRevocationList,du as withProtectedSpans,tt as words};
|