@bivelio/savings-layer 0.3.0 → 0.3.1
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/README.md +4 -2
- package/dist/index.d.ts +543 -35
- package/dist/index.js +23 -23
- package/package.json +4 -2
package/dist/index.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
|
-
var
|
|
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:hs(t.model),messages:t.messages,normalizedText:r,systemPromptHash:fe(n),toolsetHash:fe(we(o)),structuredDataHash:t.structuredData!==void 0?fe(we(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 ir="n2";function ar(t){let e=we({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,modelFamily:t.modelFamily,model:t.model,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:${ir}:${fe(e)}`}function cr(t){let e=we({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,model:t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,data:t.structuredDataHash,temperature:t.temperature,seed:t.seed});return `bvsala:inflight:${ir}:${fe(e)}`}var gs=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"),bs=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 Xt(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"||gs.test(n),s=bs.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 c=o&&(t.freshnessBucket==null||t.freshnessBucket==="any"),l=t.freshnessBucket==="live",a=s&&t.principal==null,u=!i&&!c&&!l&&!a&&!r;r&&e.push("write/destructive tools \u2192 exact cache off (side effects must execute)"),l&&e.push("freshnessBucket=live \u2192 exact cache off (answer must be current)"),c&&e.push("freshness-sensitive without a freshness bucket \u2192 exact cache off"),a&&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&&!a,allowCompression:true,requiresFreshData:o,hasSideEffects:r,isPersonalized:s,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var ot=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 st=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 xs(t,e){let n=Math.min(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i++){let c=t[i],l=e[i];r+=c*l,o+=c*c,s+=l*l;}return o===0||s===0?0:r/(Math.sqrt(o)*Math.sqrt(s))}var ys=new Set(["no","not","never","none","cannot","cant","without","nor","nt","isnt","arent","wasnt","werent","dont","doesnt","didnt","wont","cant","shouldnt"]),vs=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"]);function lr(t){return (t.match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function ks(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 ur(t){return t.split(/\s+/).filter(Boolean)}function dr(t){return t.filter(e=>ys.has(e.replace(/'/g,""))||e.endsWith("n't")).length}function ws(t,e){if(!ks(lr(t),lr(e)))return false;let n=ur(t),r=ur(e);if(dr(n)!==dr(r))return false;let o=a=>a.length>1&&!vs.has(a)&&!/^\d/.test(a),s=new Set(n.filter(o)),i=new Set(r.filter(o));if(s.size===0&&i.size===0)return true;let c=0;for(let a of s)i.has(a)&&c++;let l=s.size+i.size-c;return l===0?true:c/l>=.75}var fr=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;constructor(e){this.embed=e.embed,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??.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=xs(n,o.embedding);if(s<this.similarityThreshold||!ws(e.normalizedText,o.query))continue;let i=this.verify?await this.verify(e.normalizedText,o.query):s,c=Math.min(s,i);c<this.acceptThreshold||(!r||c>r.confidence)&&(r={record:o,similarity:s,verifierScore:i,confidence:c,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 Qt=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}},Ss={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]??Ts(t.normalizedText))?.trim();if(!n)return null;let r=Rs(n);return r===null||!Number.isFinite(r)?null:{text:Es(r),data:{value:r},resolver:"arithmetic"}}};function Ts(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function Es(t){return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function Rs(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=c=>{let l=n.pop(),a=n.pop();if(a===void 0||l===void 0)return false;switch(c){case "+":return n.push(a+l),true;case "-":return n.push(a-l),true;case "*":return n.push(a*l),true;case "/":return l===0?false:(n.push(a/l),true);case "%":return l===0?false:(n.push(a%l),true);default:return false}},i=true;for(let c of e)if(/^\d/.test(c))n.push(Number(c)),i=false;else if(c==="(")r.push(c),i=true;else if(c===")"){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[c];)if(!s(r.pop()))return null;r.push(c),i=true;}for(;r.length;){let c=r.pop();if(c==="("||!s(c))return null}return n.length===1?n[0]:null}function pr(){return new Qt().register(Ss)}var Cs=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,mr=/\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,Is=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,it=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 oe("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return oe("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(Is.test(r)&&!mr.test(r))return oe("NO_RETRIEVAL",.8,"self-contained transformation",0);let s=this.classifier?.classify(r);return s&&s.confidence>=.75?oe(s.executionClass,s.confidence,"local classifier",Os(s.executionClass,this.maxRounds)):n==="single"?oe("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?oe("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):Cs.test(r)?oe("MULTI_HOP_RETRIEVAL",.7,"comparison/compound question",Math.min(this.maxRounds,2)):mr.test(r)?oe("SINGLE_RETRIEVAL",.65,"single factual lookup",1):oe("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function Os(t,e){return t==="SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function oe(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var at=class{maxTools;scoreIntentMatch;constructor(e={}){this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??_s;}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",c=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),l=new Set(c.map(u=>u.id)),a=n.filter(u=>!l.has(u.id)).map(u=>u.id);return {tools:c,droppedIds:a,reason:`selected ${c.length}/${n.length} by intent match (writes ${o?"allowed":"blocked"})`,setIsStable:a.length===0}}};function _s(t,e){let n=rt(t),r=0;for(let o of e.intents){let s=rt(o);s&&(n.includes(s)?r+=2:s.split(/\s+/).some(i=>i.length>3&&n.includes(i))&&(r+=1));}return r}function As(t){let e=new Set,n=[];for(let r of t){let o=r.hash??Ds(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function Ls(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((i,c)=>(c.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 c=(i.score??0)/o;if(s.length<n||c>=.4&&s.length<e.maxDocuments)s.push(i);else break}return s}async function hr(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 c=await e.retriever.retrieve(t.query,t.maxDocuments*2);r.push(...c);}let o=r.length;r=As(r),e.reranker&&(r=await e.reranker.rerank(t.query,r));let s=Ls(r,{maxDocuments:t.maxDocuments});return {docs:s,rounds:n,retrievedCount:o,keptCount:s.length}}function Ds(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function hc(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function gc(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"&&js(o)?Object.assign(n.userPreferences,o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let s=Bs(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],Ms(n,r);return n}function bc(t){let e=t.rawTurns??3,n=[],r=Ps(t.state);r&&n.push({role:"system",content:`Conversation state:
|
|
4
|
-
${
|
|
5
|
-
`)}function
|
|
6
|
-
`).filter(l=>l.trim().length>0).map(l=>({indent:
|
|
7
|
-
`)}function
|
|
8
|
-
`)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?
|
|
9
|
-
`)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function
|
|
10
|
-
`),
|
|
11
|
-
`+JSON.stringify(t)}var
|
|
12
|
-
`+JSON.stringify(t)}var Dr=4,mt="bvsala_contract",Pr=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 ni(o)}`);return this.leer(o,e,n.contratoNativo)}construirCuerpo(e){let{system:n,messages:r,prefijoEnMensajes:o,prefijoEnSystem:s}=ei(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(a=>({name:a.id,...a.description?{description:a.description}:{},input_schema:a.parameters??{type:"object",properties:{}}})),c=false;if(e.schema)if(i.length>0)n.push({type:"text",text:Lr(e.schema)}),J("anthropic-contrato-con-herramientas",'[bvsala] La petici\xF3n lleva herramientas del llamante Y un contrato de salida. En la API de Anthropic la forma se impone forzando una llamada a herramienta, y forzarla dejar\xEDa al modelo sin poder invocar las tuyas. Se env\xEDa el esquema por prompt: el layer valida igual, pero la garant\xEDa la da el layer, no el proveedor (`constraints.backend: "none"`).');else {let a=Se(e.schema);a||J("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."),i.push({name:mt,description:"Return the final answer in the required shape.",input_schema:e.schema,...a?{strict:true}:{}}),c=a;}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),c&&(l.tool_choice={type:"tool",name:mt}),this.marcarCache(e,n,r,o,s),{body:l,contratoNativo:c}}marcarCache(e,n,r,o,s){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return;let i=Math.min(this.opts.maxCacheBreakpoints??Dr,Dr);if(i<=0)return;let c=s>0?n[s-1]:void 0;if(c&&(c.cache_control={type:"ephemeral"},i-=1),i>0&&o>0){let l=r[Math.min(o,r.length)-1],a=l?.content[l.content.length-1];a&&(a.cache_control={type:"ephemeral"});}}async leer(e,n,r){let o=await e.json(),s=o.content??[],i=s.filter(g=>g.type==="text").map(g=>g.text??"").join(""),c=s.filter(g=>g.type==="tool_use"&&g.name!==mt).map(g=>({...g.id?{id:g.id}:{},name:g.name??"",arguments:JSON.stringify(g.input??{})})).filter(g=>g.name!==""),l=s.find(g=>g.type==="tool_use"&&g.name===mt),a=l?JSON.stringify(l.input??{}):i,u=o.usage??{},d=u.cache_read_input_tokens,p=u.cache_creation_input_tokens,m=(u.input_tokens??0)+(p??0)+(d??0),f=u.output_tokens??0,b=typeof u.input_tokens!="number",h=typeof u.output_tokens!="number";if(this.opts.requireUsage&&(b||h))throw new Error(`provider returned incomplete usage (input=${u.input_tokens??"absent"}, output=${u.output_tokens??"absent"}); cannot measure cost.`);return {text:a,...c.length>0?{toolCalls:c}:{},...o.stop_reason?{finishReason:ti(o.stop_reason)}:{},usage:{inputTokens:m,outputTokens:f,...d!=null?{cachedInputTokens:d}:{},...p!=null?{cacheWriteInputTokens:p}:{}},structuredNatively:n.schema!=null&&r,raw:o}}};function ei(t){let e=[],n=[],r=t.stablePrefixMessages??0,o=0,s=0,i=true;return t.messages.forEach((c,l)=>{if(c.role==="system"&&i){e.push({type:"text",text:c.content}),l<r&&(s=e.length);return}i=false,n.push({role:c.role==="assistant"?"assistant":"user",content:[{type:"text",text:c.content}]}),l<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 ti(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 ni(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}var Ke=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 Te=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function ln(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function ht(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 G(t,e,n=""){let r=ln(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){let i=n&&`"${n}" `,c=s?` of length ${e}`:"",l=r?`length=${o}`:`type=${typeof t}`,a=i+"expected Uint8Array"+c+", got "+l;throw r?new RangeError(a):new TypeError(a)}return t}function un(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 Mr(t,e){G(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 Je(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function gt(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var jr=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ri=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function bt(t){if(G(t),jr)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=ri[t[n]];return e}var se={_0:48,_9:57,A:65,F:70,a:97,f:102};function Br(t){if(t>=se._0&&t<=se._9)return t-se._0;if(t>=se.A&&t<=se.F)return t-(se.A-10);if(t>=se.a&&t<=se.f)return t-(se.a-10)}function Ge(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(jr)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=Br(t.charCodeAt(s)),c=Br(t.charCodeAt(s+1));if(i===void 0||c===void 0){let l=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+l+'" at index '+s)}r[o]=i*16+c;}return r}function dn(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];G(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 Nr(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 Fr(t=32){ht(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 zr=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var xt=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=gt(this.buffer);}update(e){un(this),G(e);let{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let c=Math.min(o-this.pos,s-i);if(c===o){let l=gt(e);for(;o<=s-i;i+=o)this.process(l,i);continue}r.set(e.subarray(i,i+c),this.pos),this.pos+=c,i+=c,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){un(this),Mr(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;n[i++]=128,Je(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 c=gt(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let a=l/4,u=this.get();if(a>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<a;d++)c.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:c}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=c,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};var z=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var yt=BigInt(4294967295),$r=BigInt(32);function oi(t,e=false){return e?{h:Number(t&yt),l:Number(t>>$r&yt)}:{h:Number(t>>$r&yt)|0,l:Number(t&yt)|0}}function Ur(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:c}=oi(t[s],e);[r[s],o[s]]=[i,c];}return [r,o]}var fn=(t,e,n)=>t>>>n,pn=(t,e,n)=>t<<32-n|e>>>n,Ee=(t,e,n)=>t>>>n|e<<32-n,Re=(t,e,n)=>t<<32-n|e>>>n,We=(t,e,n)=>t<<64-n|e>>>n-32,Ze=(t,e,n)=>t>>>n-32|e<<64-n;function X(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var Vr=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Hr=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,qr=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Kr=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,Jr=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Gr=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0;var Wr=Ur(["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))),ii=Wr[0],ai=Wr[1],me=new Uint32Array(80),he=new Uint32Array(80),mn=class extends xt{constructor(e){super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:c,Dl:l,Eh:a,El:u,Fh:d,Fl:p,Gh:m,Gl:f,Hh:b,Hl:h}=this;return [e,n,r,o,s,i,c,l,a,u,d,p,m,f,b,h]}set(e,n,r,o,s,i,c,l,a,u,d,p,m,f,b,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=c|0,this.Dl=l|0,this.Eh=a|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=m|0,this.Gl=f|0,this.Hh=b|0,this.Hl=h|0;}process(e,n){for(let y=0;y<16;y++,n+=4)me[y]=e.getUint32(n),he[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){let T=me[y-15]|0,O=he[y-15]|0,A=Ee(T,O,1)^Ee(T,O,8)^fn(T,O,7),E=Re(T,O,1)^Re(T,O,8)^pn(T,O,7),R=me[y-2]|0,S=he[y-2]|0,P=Ee(R,S,19)^We(R,S,61)^fn(R,S,6),D=Re(R,S,19)^Ze(R,S,61)^pn(R,S,6),v=qr(E,D,he[y-7],he[y-16]),k=Kr(v,A,P,me[y-7],me[y-16]);me[y]=k|0,he[y]=v|0;}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:c,Cl:l,Dh:a,Dl:u,Eh:d,El:p,Fh:m,Fl:f,Gh:b,Gl:h,Hh:g,Hl:x}=this;for(let y=0;y<80;y++){let T=Ee(d,p,14)^Ee(d,p,18)^We(d,p,41),O=Re(d,p,14)^Re(d,p,18)^Ze(d,p,41),A=d&m^~d&b,E=p&f^~p&h,R=Jr(x,O,E,ai[y],he[y]),S=Gr(R,g,T,A,ii[y],me[y]),P=R|0,D=Ee(r,o,28)^We(r,o,34)^We(r,o,39),v=Re(r,o,28)^Ze(r,o,34)^Ze(r,o,39),k=r&s^r&c^s&c,I=o&i^o&l^i&l;g=b|0,x=h|0,b=m|0,h=f|0,m=d|0,f=p|0,{h:d,l:p}=X(a|0,u|0,S|0,P|0),a=c|0,u=l|0,c=s|0,l=i|0,s=r|0,i=o|0;let _=Vr(P,v,I);r=Hr(_,S,D,k),o=_|0;}(({h:r,l:o}=X(this.Ah|0,this.Al|0,r|0,o|0))),{h:s,l:i}=X(this.Bh|0,this.Bl|0,s|0,i|0),{h:c,l}=X(this.Ch|0,this.Cl|0,c|0,l|0),{h:a,l:u}=X(this.Dh|0,this.Dl|0,a|0,u|0),{h:d,l:p}=X(this.Eh|0,this.El|0,d|0,p|0),{h:m,l:f}=X(this.Fh|0,this.Fl|0,m|0,f|0),{h:b,l:h}=X(this.Gh|0,this.Gl|0,b|0,h|0),{h:g,l:x}=X(this.Hh|0,this.Hl|0,g|0,x|0),this.set(r,o,s,i,c,l,a,u,d,p,m,f,b,h,g,x);}roundClean(){Je(me,he);}destroy(){this.destroyed=true,Je(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},hn=class extends mn{Ah=z[0]|0;Al=z[1]|0;Bh=z[2]|0;Bl=z[3]|0;Ch=z[4]|0;Cl=z[5]|0;Dh=z[6]|0;Dl=z[7]|0;Eh=z[8]|0;El=z[9]|0;Fh=z[10]|0;Fl=z[11]|0;Gh=z[12]|0;Gl=z[13]|0;Hh=z[14]|0;Hl=z[15]|0;constructor(){super(64);}};var vt=Nr(()=>new hn,zr(3));var j=(t,e,n)=>G(t,e,n),bn=ht,xn=bt,Q=(...t)=>dn(...t),Zr=t=>Ge(t),St=ln,Yr=t=>Fr(t),wt=BigInt(0),gn=BigInt(1);function Pe(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"expected boolean, got type="+typeof t)}return t}function ci(t){if(typeof t=="bigint"){if(!kt(t))throw new RangeError("positive bigint expected, got "+t)}else bn(t);return t}function ie(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 Xr(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?wt:BigInt("0x"+t)}function yn(t){return Xr(bt(t))}function ae(t){return Xr(bt(Ye(G(t)).reverse()))}function vn(t,e){if(ht(e),e===0)throw new RangeError("zero length");t=ci(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return Ge(n.padStart(e*2,"0"))}function Qr(t,e){return vn(t,e).reverse()}function eo(t,e){if(t=j(t),e=j(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 Ye(t){return Uint8Array.from(j(t))}var kt=t=>typeof t=="bigint"&&wt<=t;function li(t,e,n){return kt(t)&&kt(e)&&kt(n)&&e<=t&&t<n}function kn(t,e,n,r){if(!li(e,n,r))throw new RangeError("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function wn(t){if(t<wt)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>wt;t>>=gn,e+=1);return e}var to=t=>(gn<<BigInt(t))-gn;function Ce(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function r(s,i,c){if(!c&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let l=t[s];if(c&&l===void 0)return;let a=typeof l;if(a!==i||l===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${a}`)}let o=(s,i)=>Object.entries(s).forEach(([c,l])=>r(c,l,i));o(e,false),o(n,true);}var Sn=()=>{throw new Error("not implemented")};var $=BigInt(0),N=BigInt(1),Ie=BigInt(2),so=BigInt(3),io=BigInt(4),ao=BigInt(5),ui=BigInt(7),co=BigInt(8),di=BigInt(9),lo=BigInt(16);function M(t,e){if(e<=$)throw new Error("mod: expected positive modulus, got "+e);let n=t%e;return n>=$?n:e+n}function W(t,e,n){if(e<$)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >$;)r*=r,r%=n;return r}function no(t,e){if(t===$)throw new Error("invert: expected non-zero number");if(e<=$)throw new Error("invert: expected positive modulus, got "+e);let n=M(t,e),r=e,o=$,i=N;for(;n!==$;){let a=r/n,u=r-n*a,d=o-i*a;r=n,n=u,o=i,i=d;}if(r!==N)throw new Error("invert: does not exist");return M(o,e)}function Tn(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+N)/io,o=n.pow(e,r);return Tn(n,o,e),o}function fi(t,e){let n=t,r=(n.ORDER-ao)/co,o=n.mul(e,Ie),s=n.pow(o,r),i=n.mul(e,s),c=n.mul(n.mul(i,Ie),s),l=n.mul(i,n.sub(c,n.ONE));return Tn(n,l,e),l}function pi(t){let e=Ct(t),n=fo(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+ui)/lo;return((c,l)=>{let a=c,u=a.pow(l,i),d=a.mul(u,r),p=a.mul(u,o),m=a.mul(u,s),f=a.eql(a.sqr(d),l),b=a.eql(a.sqr(p),l);u=a.cmov(u,d,f),d=a.cmov(m,p,b);let h=a.eql(a.sqr(d),l),g=a.cmov(u,d,h);return Tn(a,g,l),g})}function fo(t){if(t<so)throw new Error("sqrt is not defined for small field");let e=t-N,n=0;for(;e%Ie===$;)e/=Ie,n++;let r=Ie,o=Ct(t);for(;ro(o,r)===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+N)/Ie;return function(l,a){let u=l;if(u.is0(a))return a;if(ro(u,a)!==1)throw new Error("Cannot find square root");let d=n,p=u.mul(u.ONE,s),m=u.pow(a,e),f=u.pow(a,i);for(;!u.eql(m,u.ONE);){if(u.is0(m))return u.ZERO;let b=1,h=u.sqr(m);for(;!u.eql(h,u.ONE);)if(b++,h=u.sqr(h),b===d)throw new Error("Cannot find square root");let g=N<<BigInt(d-b-1),x=u.pow(p,g);d=b,p=u.sqr(x),m=u.mul(m,p),f=u.mul(f,x);}return f}}function mi(t){return t%io===so?uo:t%co===ao?fi:t%lo===di?pi(t):fo(t)}var ce=(t,e)=>(M(t,e)&N)===N,hi=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function po(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=hi.reduce((r,o)=>(r[o]="function",r),e);if(Ce(t,n),ie(t.BYTES,"BYTES"),ie(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=N)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function gi(t,e,n){let r=t;if(n<$)throw new Error("invalid exponent, negatives unsupported");if(n===$)return r.ONE;if(n===N)return e;let o=r.ONE,s=e;for(;n>$;)n&N&&(o=r.mul(o,s)),s=r.sqr(s),n>>=N;return o}function Rt(t,e,n=false){let r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),s=e.reduce((c,l,a)=>r.is0(l)?c:(o[a]=c,r.mul(c,l)),r.ONE),i=r.inv(s);return e.reduceRight((c,l,a)=>r.is0(l)?c:(o[a]=r.mul(c,o[a]),r.mul(c,l)),i),o}function ro(t,e){let n=t,r=(n.ORDER-N)/Ie,o=n.pow(e,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),c=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!c)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function bi(t,e){if(e!==void 0&&bn(e),t<=$)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=wn(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 oo=new WeakMap,Et=class{ORDER;BITS;BYTES;isLE;ZERO=$;ONE=N;_lengths;_mod;constructor(e,n={}){if(e<=N)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}=bi(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 M(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return $<=e&&e<this.ORDER}is0(e){return e===$}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&N)===N}neg(e){return M(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return M(e*e,this.ORDER)}add(e,n){return M(e+n,this.ORDER)}sub(e,n){return M(e-n,this.ORDER)}mul(e,n){return M(e*n,this.ORDER)}pow(e,n){return gi(this,e,n)}div(e,n){return M(e*no(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 no(e,this.ORDER)}sqrt(e){let n=oo.get(this);return n||oo.set(this,n=mi(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?Qr(e,this.BYTES):vn(e,this.BYTES)}fromBytes(e,n=false){j(e);let{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:c}=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 a=new Uint8Array(o);a.set(e,s?0:a.length-e.length),e=a;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let l=s?ae(e):yn(e);if(c&&(l=M(l,i)),!n&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return Rt(this,e)}cmov(e,n,r){return Pe(r,"condition"),r?n:e}};Object.freeze(Et.prototype);function Ct(t,e={}){return new Et(t,e)}var It=BigInt(0),In=BigInt(1);function mo(t,e){let n=e.negate();return t?n:e}function _t(t,e){let n=Rt(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function xo(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function En(t,e){xo(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=to(t),i=BigInt(t);return {windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function ho(t,e,n){let{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n,c=Number(t&o),l=t>>i;c>r&&(c-=s,l+=In);let a=e*r,u=a+Math.abs(c)-1,d=c===0,p=c<0,m=e%2!==0;return {nextN:l,offset:u,isZero:d,isNeg:p,isNegF:m,offsetF:a}}var Rn=new WeakMap,yo=new WeakMap;function Cn(t){return yo.get(t)||1}function go(t){if(t!==It)throw new Error("invalid wNAF")}var Ot=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>It;)n&In&&(r=r.add(o)),o=o.double(),n>>=In;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=En(n,this.bits),s=[],i=e,c=i;for(let l=0;l<r;l++){c=i,s.push(c);for(let a=1;a<o;a++)c=c.add(i),s.push(c);i=c.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=En(e,this.bits);for(let c=0;c<i.windows;c++){let{nextN:l,offset:a,isZero:u,isNeg:d,isNegF:p,offsetF:m}=ho(r,c,i);r=l,u?s=s.add(mo(p,n[m])):o=o.add(mo(d,n[a]));}return go(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.ZERO){let s=En(e,this.bits);for(let i=0;i<s.windows&&r!==It;i++){let{nextN:c,offset:l,isZero:a,isNeg:u}=ho(r,i,s);if(r=c,!a){let d=n[l];o=o.add(u?d.negate():d);}}return go(r),o}getPrecomputes(e,n,r){let o=Rn.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Rn.set(n,o))),o}cached(e,n,r){let o=Cn(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let s=Cn(e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){xo(n,this.bits),yo.set(e,n),Rn.delete(e);}hasCache(e){return Cn(e)!==1}};function bo(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return po(e),e}else return Ct(t,{isLE:n})}function vo(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 l of ["p","n","h"]){let a=e[l];if(!(typeof a=="bigint"&&a>It))throw new Error(`CURVE.${l} must be positive bigint`)}let o=bo(e.p,n.Fp,r),s=bo(e.n,n.Fn,r),c=["Gx","Gy","a","d"];for(let l of c)if(!o.isValid(e[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function ko(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var ge=BigInt(0),F=BigInt(1),On=BigInt(2),xi=BigInt(8);function yi(t,e,n,r){let o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),c=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,c)}function wo(t,e={}){let n=e,r=vo("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r,i=r.CURVE,{h:c}=i;Ce(n,{},{uvRatio:"function"});let l=On<<BigInt(s.BYTES*8)-F,a=b=>o.create(b),u=n.uvRatio===void 0?(b,h)=>{try{return {isValid:!0,value:o.sqrt(o.div(b,h))}}catch{return {isValid:false,value:ge}}}:n.uvRatio;if(!yi(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(b,h,g=false){let x=g?F:ge;return kn("coordinate "+b,h,x,l),h}function p(b){if(!(b instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,F,a(i.Gx*i.Gy));static ZERO=new m(ge,F,F,ge);static Fp=o;static Fn=s;X;Y;Z;T;constructor(h,g,x,y){this.X=d("x",h),this.Y=d("y",g),this.Z=d("z",x,true),this.T=d("t",y),Object.freeze(this);}static CURVE(){return i}static fromAffine(h){if(h instanceof m)throw new Error("extended point not allowed");let{x:g,y:x}=h||{};return d("x",g),d("y",x),new m(g,x,F,a(g*x))}static fromBytes(h,g=false){let x=o.BYTES,{a:y,d:T}=i;h=Ye(j(h,x,"point")),Pe(g,"zip215");let O=Ye(h),A=h[x-1];O[x-1]=A&-129;let E=ae(O),R=g?l:o.ORDER;kn("point.y",E,ge,R);let S=a(E*E),P=a(S-F),D=a(T*S-y),{isValid:v,value:k}=u(P,D);if(!v)throw new Error("bad point: invalid y coordinate");let I=(k&F)===F,_=(A&128)!==0;if(!g&&k===ge&&_)throw new Error("bad point: x=0 and x_0=1");return _!==I&&(k=a(-k)),m.fromAffine({x:k,y:E})}static fromHex(h,g=false){return m.fromBytes(Zr(h),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,g=true){return f.createCache(this,h),g||this.multiply(On),this}assertValidity(){let h=this,{a:g,d:x}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:y,Y:T,Z:O,T:A}=h,E=a(y*y),R=a(T*T),S=a(O*O),P=a(S*S),D=a(E*g),v=a(S*a(D+R)),k=a(P+a(x*a(E*R)));if(v!==k)throw new Error("bad point: equation left != right (1)");let I=a(y*T),_=a(O*A);if(I!==_)throw new Error("bad point: equation left != right (2)")}equals(h){p(h);let{X:g,Y:x,Z:y}=this,{X:T,Y:O,Z:A}=h,E=a(g*A),R=a(T*y),S=a(x*A),P=a(O*y);return E===R&&S===P}is0(){return this.equals(m.ZERO)}negate(){return new m(a(-this.X),this.Y,this.Z,a(-this.T))}double(){let{a:h}=i,{X:g,Y:x,Z:y}=this,T=a(g*g),O=a(x*x),A=a(On*a(y*y)),E=a(h*T),R=g+x,S=a(a(R*R)-T-O),P=E+O,D=P-A,v=E-O,k=a(S*D),I=a(P*v),_=a(S*v),C=a(D*P);return new m(k,I,C,_)}add(h){p(h);let{a:g,d:x}=i,{X:y,Y:T,Z:O,T:A}=this,{X:E,Y:R,Z:S,T:P}=h,D=a(y*E),v=a(T*R),k=a(A*x*P),I=a(O*S),_=a((y+T)*(E+R)-D-v),C=I-k,B=I+k,V=a(v-g*D),H=a(_*C),K=a(B*V),ue=a(_*V),ee=a(C*B);return new m(H,K,ee,ue)}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:g,f:x}=f.cached(this,h,y=>_t(m,y));return _t(m,[g,x])[0]}multiplyUnsafe(h){if(!s.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===ge?m.ZERO:this.is0()||h===F?this:f.unsafe(this,h,g=>_t(m,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return f.unsafe(this,i.n).is0()}toAffine(h){let g=this,x=h,{X:y,Y:T,Z:O}=g,A=g.is0();x==null&&(x=A?xi:o.inv(O));let E=a(y*x),R=a(T*x),S=o.mul(O,x);if(A)return {x:ge,y:F};if(S!==F)throw new Error("invZ was invalid");return {x:E,y:R}}clearCofactor(){return c===F?this:this.multiplyUnsafe(c)}toBytes(){let{x:h,y:g}=this.toAffine(),x=o.toBytes(g);return x[x.length-1]|=h&F?128:0,x}toHex(){return xn(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let f=new Ot(m,s.BITS);return s.BITS>=8&&m.BASE.precompute(8),Object.freeze(m.prototype),Object.freeze(m),m}var At=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e;}static fromBytes(e){Sn();}static fromHex(e){Sn();}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 xn(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 So(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');let r=e,o=n;Ce(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:c,Fn:l}=t,a=r.outputLen,u=2*c.BYTES;if(a!==void 0&&(ie(a,"hash.outputLen"),a!==u))throw new Error(`hash.outputLen must be ${u}, got ${a}`);let d=o.randomBytes===void 0?Yr:o.randomBytes,p=o.adjustScalarBytes===void 0?v=>v:o.adjustScalarBytes,m=o.domain===void 0?(v,k,I)=>{if(Pe(I,"phflag"),k.length||I)throw new Error("Contexts/pre-hash are not supported");return v}:o.domain;function f(v){return l.create(ae(v))}function b(v){let k=E.secretKey;j(v,E.secretKey,"secretKey");let I=j(r(v),2*k,"hashedSecretKey"),_=p(I.slice(0,k)),C=I.slice(k,2*k),B=f(_);return {head:_,prefix:C,scalar:B}}function h(v){let{head:k,prefix:I,scalar:_}=b(v),C=i.multiply(_),B=C.toBytes();return {head:k,prefix:I,scalar:_,point:C,pointBytes:B}}function g(v){return h(v).pointBytes}function x(v=Uint8Array.of(),...k){let I=Q(...k);return f(r(m(I,j(v,void 0,"context"),!!s)))}function y(v,k,I={}){v=j(v,void 0,"message"),s&&(v=s(v));let{prefix:_,scalar:C,pointBytes:B}=h(k),V=x(I.context,_,v),H=i.multiply(V).toBytes(),K=x(I.context,H,B,v),ue=l.create(V+K*C);if(!l.isValid(ue))throw new Error("sign failed: invalid s");let ee=Q(H,l.toBytes(ue));return j(ee,E.signature,"result")}let T={zip215:o.zip215};function O(v,k,I,_=T){let{context:C}=_,B=_.zip215===void 0?!!T.zip215:_.zip215,V=E.signature;v=j(v,V,"signature"),k=j(k,void 0,"message"),I=j(I,E.publicKey,"publicKey"),B!==void 0&&Pe(B,"zip215"),s&&(k=s(k));let H=V/2,K=v.subarray(0,H),ue=ae(v.subarray(H,V)),ee,Oe,_e;try{ee=t.fromBytes(I,B),Oe=t.fromBytes(K,B),_e=i.multiplyUnsafe(ue);}catch{return false}if(!B&&ee.isSmallOrder())return false;let w=x(C,K,I,k);return Oe.add(ee.multiplyUnsafe(w)).subtract(_e).clearCofactor().is0()}let A=c.BYTES,E={secretKey:A,publicKey:A,signature:2*A,seed:A};function R(v){return v=v===void 0?d(E.seed):v,j(v,E.seed,"seed")}function S(v){return St(v)&&v.length===E.secretKey}function P(v,k){try{return !!t.fromBytes(v,k===void 0?T.zip215:k)}catch{return false}}let D={getExtendedPublicKey:h,randomSecretKey:R,isValidSecretKey:S,isValidPublicKey:P,toMontgomery(v){let{y:k}=t.fromBytes(v),I=E.publicKey,_=I===32;if(!_&&I!==57)throw new Error("only defined for 25519 and 448");let C=_?c.div(F+k,F-k):c.div(k-F,k+F);return c.toBytes(C)},toMontgomerySecret(v){let k=E.secretKey;j(v,k);let I=r(v.subarray(0,k));return p(I).subarray(0,k)}};return Object.freeze(E),Object.freeze(D),Object.freeze({keygen:ko(R,g),getPublicKey:g,sign:y,verify:O,utils:D,Point:t,lengths:E})}var wi=BigInt(0),le=BigInt(1),Eo=BigInt(2);var Si=BigInt(5),Ti=BigInt(8),Be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Pn={p:Be,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ti,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ei(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=Be,c=t*t%s*t%s,l=W(c,Eo,s)*c%s,a=W(l,le,s)*t%s,u=W(a,Si,s)*a%s,d=W(u,e,s)*u%s,p=W(d,n,s)*d%s,m=W(p,r,s)*p%s,f=W(m,o,s)*m%s,b=W(f,o,s)*m%s,h=W(b,e,s)*u%s;return {pow_p_5_8:W(h,Eo,s)*t%s,b2:c}}function Ri(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var An=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Bn(t,e){let n=Be,r=M(e*e*e,n),o=M(r*r*e,n),s=Ei(t*o).pow_p_5_8,i=M(t*r*s,n),c=M(e*i*i,n),l=i,a=M(i*An,n),u=c===t,d=c===M(-t,n),p=c===M(-t*An,n);return u&&(i=l),(d||p)&&(i=a),ce(i,n)&&(i=M(-i,n)),{isValid:u||d,value:i}}var xe=wo(Pn,{uvRatio:Bn}),be=xe.Fp,Io=xe.Fn;function Ci(t){return So(xe,vt,Object.assign({adjustScalarBytes:Ri,zip215:true},t))}var Oo=Ci({});var Ln=An;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Oi=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var Ro=t=>Bn(le,t),Li=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Dn=t=>be.create(ae(t)&Li);var ye=class t extends At{static BASE=new t(xe.BASE);static ZERO=new t(xe.ZERO);static Fp=be;static Fn=Io;constructor(e){super(e);}static fromAffine(e){return new t(xe.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoPoint expected")}init(e){return new t(e)}static fromBytes(e){G(e,32);let{a:n,d:r}=Pn,o=Be,s=T=>be.create(T),i=Dn(e);if(!eo(be.toBytes(i),e)||ce(i,o))throw new Error("invalid ristretto255 encoding 1");let c=s(i*i),l=s(le+n*c),a=s(le-n*c),u=s(l*l),d=s(a*a),p=s(n*r*u-d),{isValid:m,value:f}=Ro(s(p*d)),b=s(f*a),h=s(f*b*p),g=s((i+i)*b);ce(g,o)&&(g=s(-g));let x=s(l*h),y=s(g*x);if(!m||ce(y,o)||x===wi)throw new Error("invalid ristretto255 encoding 2");return new t(new xe(g,x,le,y))}static fromHex(e){return t.fromBytes(Ge(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,s=Be,i=h=>be.create(h),c=i(i(r+n)*i(r-n)),l=i(e*n),a=i(l*l),{value:u}=Ro(i(c*a)),d=i(u*c),p=i(u*l),m=i(d*p*o),f;if(ce(o*m,s)){let h=i(n*Ln),g=i(e*Ln);e=h,n=g,f=i(d*Oi);}else f=p;ce(e*m,s)&&(n=i(-n));let b=i((r-n)*f);return ce(b,s)&&(b=i(-b)),be.toBytes(b)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:s}=e.ep,i=a=>be.create(a),c=i(n*s)===i(r*o),l=i(r*s)===i(n*o);return c||l}is0(){return this.equals(t.ZERO)}};Object.freeze(ye.BASE);Object.freeze(ye.ZERO);Object.freeze(ye.prototype);Object.freeze(ye);var _o=`-----BEGIN PUBLIC KEY-----
|
|
1
|
+
var Ns="2026-08-13",rn={"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},"claude-opus-4":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"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:25e-6}};function sn(t,e,n){if(!n)return;let o=t[n];if(o)return o;let r=n.lastIndexOf("/"),s=r>=0?n.slice(r+1):n,i=t[s];if(i)return i;for(let a of e)if(s.startsWith(a)){let l=s.charAt(a.length);if(l===""||l==="-"||l==="."||l==="_")return t[a]}}function an(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var $s=an(rn);function dt(t){return sn(rn,$s,t)}var Fs=0;function cn(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let o=++Fs,r=Date.now?Date.now():0;for(let s=0;s<16;s++)e[s]=(s<6?o>>>s*8:r>>>(s-6)*8)&255;}e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=[];for(let o=0;o<16;o++)n.push(e[o].toString(16).padStart(2,"0"));return `${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}-${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var Sc=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function Ec(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 ln=class{id;exact=false;constructor(e="heuristic"){this.id=e;}count(e){if(e.length===0)return 0;let n=e.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],o=0;for(let r of n){let s=r[0];if(/\s/.test(s)){let i=(r.match(/\n/g)??[]).length;o+=i+Math.floor(Math.max(0,r.length-1)/2);}else /[A-Za-z]/.test(s)?o+=Math.max(1,Math.ceil(r.length/4)):/\d/.test(s)?o+=Math.max(1,Math.ceil(r.length/2)):o+=1;}return Math.max(o,Math.ceil(e.length/4))}},Me=new ln;var un=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=Me){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 o=this.modelToTokenizer.get(e.model);if(o){let r=this.estimators.get(o);if(r)return r}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},Eo=new un;var dn=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}},Ro={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 zs(t,e={}){let n=e.codificaciones??["o200k_base","cl100k_base"],o=false;for(let r of n){let s;try{s=await import(`gpt-tokenizer/encoding/${r}`);}catch{continue}if(typeof s.encode=="function"){t.register(new dn(r,s)),o=true;for(let i of Ro[r]??[])t.mapModel(i,r),t.mapModel(`openai/${i}`,r);}}return o}var Lc=Ro,Mc=zs;var Pe=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,o="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),o=this.removedInputLocal===0?"measured":"estimated";}else this.actualInput>0?(this.baselineInput=this.actualInput,o="measured"):(this.baselineInput=0,o="unmeasured");let r=n?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):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,l=a(this.baselineInput)+r/1e3*e.outputPer1k,c=a(this.actualInput)+this.actualOutput/1e3*e.outputPer1k+this.extraCostUsd,u=l===0?0:1-c/l;return {baselineEstimate:Co(l),actual:Co(c),netSavings:Vs(u),basis:o}}};function Co(t){return Math.round(t*1e10)/1e10}function Vs(t){return Math.round(t*1e6)/1e6}var Us=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]),qs=new TextEncoder;function oe(t,e){return t>>>e|t<<32-e}function Oo(t){let e=qs.encode(t),n=e.length*8,o=(e.length+8>>6)+1,r=new Uint8Array(o*64);r.set(e),r[e.length]=128;let s=new DataView(r.buffer);s.setUint32(r.length-8,Math.floor(n/4294967296)),s.setUint32(r.length-4,n>>>0);let i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let c=0;c<r.length;c+=64){for(let b=0;b<16;b++)a[b]=s.getUint32(c+b*4);for(let b=16;b<64;b++){let y=a[b-15],E=a[b-2],C=oe(y,7)^oe(y,18)^y>>>3,I=oe(E,17)^oe(E,19)^E>>>10;a[b]=a[b-16]+C+a[b-7]+I|0;}let u=i[0],d=i[1],p=i[2],f=i[3],m=i[4],h=i[5],g=i[6],x=i[7];for(let b=0;b<64;b++){let y=oe(m,6)^oe(m,11)^oe(m,25),E=m&h^~m&g,C=x+y+E+Us[b]+a[b]|0,I=oe(u,2)^oe(u,13)^oe(u,22),T=u&d^u&p^d&p,D=I+T|0;x=g,g=h,h=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]+h|0,i[6]=i[6]+g|0,i[7]=i[7]+x|0;}let l="";for(let c=0;c<8;c++)l+=(i[c]>>>0).toString(16).padStart(8,"0");return l}var Hs=/\s+/g,Ks=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],Js=/[¿?¡!;.,:'"·•]/g,Gs=/([a-z])\p{M}+/gu,Ws=/(^|\s)\p{M}+/gu,pn=/\p{L}/u;function Z(t){return t>="0"&&t<="9"}function pt(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,o]of Ks)e=e.replace(n,o);return e=e.normalize("NFD").replace(Gs,"$1").replace(Ws,"$1").normalize("NFC"),e=e.replace(Js,(n,o,r)=>{let s=r[o-1]??"",i=r[o+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return Z(s)&&Z(i)?n:"";case "!":return Z(s)?n:"";case ".":case ",":return Z(s)&&Z(i)||Z(i)&&!Z(s)&&!pn.test(s)?n:"";case ":":return Z(s)&&Z(i)?n:"";case "'":case '"':return pn.test(s)&&pn.test(i)||Z(s)||Z(i)?n:"";default:return Z(s)||Z(i)?n:""}}),e.replace(Hs," ").trim()}function re(t){return Oo(t)}function ye(t){return JSON.stringify(fn(t))}function fn(t){if(Array.isArray(t))return t.map(fn);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=fn(t[n]);return e}return t}function mn(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function hn(t){let e=t.context??{},n=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(`
|
|
2
|
+
`),o=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${pt(s.content)}`).join(`
|
|
3
|
+
`),r=(t.tools??[]).map(s=>({id:s.id,risk:s.risk,parameters:s.parameters??null})).sort((s,i)=>s.id.localeCompare(i.id));return {model:t.model,modelFamily:mn(t.model),messages:t.messages,normalizedText:o,systemPromptHash:re(n),toolsetHash:re(ye(r)),structuredDataHash:t.structuredData!==void 0?re(ye(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 Io="n2";function gn(t,e={}){let n=e.servedModel??t.model,o=ye({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily:mn(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:${Io}:${re(o)}`}function _o(t,e={}){let n=ye({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});return `bvsala:inflight:${Io}:${re(n)}`}var Zs=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"),Ys=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 bn(t){let e=[],n=t.normalizedText,o=(t.original.tools??[]).some(p=>p.risk==="write"||p.risk==="destructive"),r=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||Zs.test(n),s=Ys.test(n),i=(t.temperature??0)>.3&&t.seed==null;o&&e.push("write/destructive tools present"),r&&e.push("freshness-sensitive request"),s&&e.push("personalized/account-scoped request"),i&&e.push("stochastic sampling (temp>0.3, no seed)");let a=r&&(t.freshnessBucket==null||t.freshnessBucket==="any"),l=t.freshnessBucket==="live",c=s&&t.principal==null,u=!i&&!a&&!l&&!c&&!o;o&&e.push("write/destructive tools \u2192 exact cache off (side effects must execute)"),l&&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"),c&&e.push("personalized request with no principal (context.sessionId) \u2192 exact cache off");let d=!o&&!r&&!s&&!i&&t.freshnessBucket!=="day";return {allowExactCache:u,allowSemanticCache:d,allowSingleflight:!o&&!c,allowCompression:true,requiresFreshData:r,hasSideEffects:o,isPersonalized:s,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var ft=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,o){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let r=this.store.keys().next().value;r!==void 0&&this.store.delete(r);}this.store.set(e,{value:n,expiresAtMs:o!=null?this.now()+o:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};var mt=class{inflight=new Map;waiters=new Map;async run(e,n){let o=this.inflight.get(e);if(o)return this.waiters.set(e,(this.waiters.get(e)??1)+1),{value:await o,coalesced:true};let r=(async()=>n())();this.inflight.set(e,r),this.waiters.set(e,1);try{return {value:await r,coalesced:!1}}finally{this.inflight.delete(e),this.waiters.delete(e);}}get activeKeys(){return this.inflight.size}};function Xs(t,e){let n=Math.min(t.length,e.length),o=0,r=0,s=0;for(let i=0;i<n;i++){let a=t[i],l=e[i];o+=a*l,r+=a*a,s+=l*l;}return r===0||s===0?0:o/(Math.sqrt(r)*Math.sqrt(s))}var Qs=new Set(["no","not","never","none","cannot","cant","without","nor","nt","isnt","arent","wasnt","werent","dont","doesnt","didnt","wont","cant","shouldnt"]),ei=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"]);function Do(t){return (t.match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function ti(t,e){if(t.length!==e.length)return false;let n=new Map;for(let o of t)n.set(o,(n.get(o)??0)+1);for(let o of e){let r=n.get(o);if(!r)return false;n.set(o,r-1);}return true}function Ao(t){return t.split(/\s+/).filter(Boolean)}function Lo(t){return t.filter(e=>Qs.has(e.replace(/'/g,""))||e.endsWith("n't")).length}function ni(t,e){if(!ti(Do(t),Do(e)))return false;let n=Ao(t),o=Ao(e);if(Lo(n)!==Lo(o))return false;let r=c=>c.length>1&&!ei.has(c)&&!/^\d/.test(c),s=new Set(n.filter(r)),i=new Set(o.filter(r));if(s.size===0&&i.size===0)return true;let a=0;for(let c of s)i.has(c)&&a++;let l=s.size+i.size-a;return l===0?true:a/l>=.75}var Mo=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;constructor(e){this.embed=e.embed,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??.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),o=null;for(let r of this.records){if(r.tenantId!==e.tenantId||r.authorizationScope!==e.authorizationScope||r.principal!==e.principal||r.knowledgeEpoch!==e.knowledgeEpoch||r.contractId!==e.contractId||r.model!==e.model||r.systemPromptHash!==e.systemPromptHash||r.structuredDataHash!==e.structuredDataHash||r.locale!==e.locale||r.schemaVersion!==e.schemaVersion||r.safetyPolicyVersion!==e.safetyPolicyVersion||this.ttlMs!=null&&this.now()-r.storedAtMs>this.ttlMs)continue;let s=Xs(n,r.embedding);if(s<this.similarityThreshold||!ni(e.normalizedText,r.query))continue;let i=this.verify?await this.verify(e.normalizedText,r.query):s,a=Math.min(s,i);a<this.acceptThreshold||(!o||a>o.confidence)&&(o={record:r,similarity:s,verifierScore:i,confidence:a,ageMs:this.now()-r.storedAtMs});}return o}async store(e,n){let o=await this.embed(e.normalizedText);this.records.length>=this.maxRecords&&this.records.shift(),this.records.push({embedding:o,query:e.normalizedText,answer:n,tenantId:e.tenantId,authorizationScope:e.authorizationScope,principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.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 o=this.records.length-1;o>=0;o--)this.records[o].knowledgeEpoch===e&&(this.records.splice(o,1),n++);return n}get size(){return this.records.length}};var xn=class{resolvers=[];register(e){return this.resolvers.push(e),this}try(e){for(let n of this.resolvers)try{let o=n.try(e);if(o)return o}catch{}return null}get size(){return this.resolvers.length}},oi={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]??ri(t.normalizedText))?.trim();if(!n)return null;let o=ii(n);return o===null||!Number.isFinite(o)?null:{text:si(o),data:{value:o},resolver:"arithmetic"}}};function ri(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function si(t){return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function ii(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],o=[],r={"+":1,"-":1,"*":2,"/":2,"%":2},s=a=>{let l=n.pop(),c=n.pop();if(c===void 0||l===void 0)return false;switch(a){case "+":return n.push(c+l),true;case "-":return n.push(c-l),true;case "*":return n.push(c*l),true;case "/":return l===0?false:(n.push(c/l),true);case "%":return l===0?false:(n.push(c%l),true);default:return false}},i=true;for(let a of e)if(/^\d/.test(a))n.push(Number(a)),i=false;else if(a==="(")o.push(a),i=true;else if(a===")"){for(;o.length&&o[o.length-1]!=="(";)if(!s(o.pop()))return null;if(o.pop()!=="(")return null;i=false;}else {if(i)return null;for(;o.length&&o[o.length-1]!=="("&&r[o[o.length-1]]>=r[a];)if(!s(o.pop()))return null;o.push(a),i=true;}for(;o.length;){let a=o.pop();if(a==="("||!s(a))return null}return n.length===1?n[0]:null}function Po(){return new xn().register(oi)}var ai=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,Bo=/\b(who|what|when|where|which|how many|how much|define|definition|qui[eé]n|qu[eé]|cu[aá]ndo|d[oó]nde|cu[aá]nto)\b/i,ci=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,ht=class{classifier;maxRounds;constructor(e={}){this.classifier=e.classifier,this.maxRounds=e.maxRounds??2;}classify(e){let n=e.original.retrieval?.mode,o=e.normalizedText;if((e.original.tools??[]).some(i=>i.risk==="write"||i.risk==="destructive")&&/\b(create|update|delete|send|pay|book|cancel|crea|actualiza|elimina|env[ií]a|paga)\b/i.test(o))return ue("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return ue("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(ci.test(o)&&!Bo.test(o))return ue("NO_RETRIEVAL",.8,"self-contained transformation",0);let s=this.classifier?.classify(o);return s&&s.confidence>=.75?ue(s.executionClass,s.confidence,"local classifier",li(s.executionClass,this.maxRounds)):n==="single"?ue("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?ue("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):ai.test(o)?ue("MULTI_HOP_RETRIEVAL",.7,"comparison/compound question",Math.min(this.maxRounds,2)):Bo.test(o)?ue("SINGLE_RETRIEVAL",.65,"single factual lookup",1):ue("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function li(t,e){return t==="SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function ue(t,e,n,o){return {executionClass:t,confidence:e,reason:n,rounds:o}}var gt=class{maxTools;scoreIntentMatch;constructor(e={}){this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??ui;}passthrough(e){if(!e||e.length===0)return {tools:[],droppedIds:[],reason:"no tools provided",setIsStable:true};let n=e.slice(0,this.maxTools),o=e.slice(this.maxTools).map(r=>r.id);return {tools:n,droppedIds:o,reason:`router off: caller tools passed through unfiltered (${n.length}/${e.length}, capped at maxTools=${this.maxTools}; risk gating is the caller's responsibility while routing is off)`,setIsStable:true}}select(e,n,o){if(!n||n.length===0)return {tools:[],droppedIds:[],reason:"no tools provided",setIsStable:true};let r=o==="TOOL_ACTION",a=n.filter(u=>r||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),l=new Set(a.map(u=>u.id)),c=n.filter(u=>!l.has(u.id)).map(u=>u.id);return {tools:a,droppedIds:c,reason:`selected ${a.length}/${n.length} by intent match (writes ${r?"allowed":"blocked"})`,setIsStable:c.length===0}}};function ui(t,e){let n=pt(t),o=0;for(let r of e.intents){let s=pt(r);s&&(n.includes(s)?o+=2:s.split(/\s+/).some(i=>i.length>3&&n.includes(i))&&(o+=1));}return o}function di(t){let e=new Set,n=[];for(let o of t){let r=o.hash??fi(o.text);e.has(r)||(e.add(r),n.push(o));}return n}function pi(t,e={maxDocuments:5}){let n=e.minDocuments??1,o=[...t].sort((i,a)=>(a.score??0)-(i.score??0));if(o.length<=n)return o;let r=o[0]?.score??0;if(r<=0)return o.slice(0,e.maxDocuments);let s=[];for(let i of o){let a=(i.score??0)/r;if(s.length<n||a>=.4&&s.length<e.maxDocuments)s.push(i);else break}return s}async function jo(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,o=[];for(let i=0;i<n;i++){let a=await e.retriever.retrieve(t.query,t.maxDocuments*2);o.push(...a);}let r=o.length;o=di(o),e.reranker&&(o=await e.reranker.rerank(t.query,o));let s=pi(o,{maxDocuments:t.maxDocuments});return {docs:s,rounds:n,retrievedCount:r,keptCount:s.length}}function fi(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function xl(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function yl(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[o,r]of Object.entries(e.set??{}))o==="userPreferences"&&bi(r)?Object.assign(n.userPreferences,r):n.confirmedFacts[o]=r;for(let[o,r]of Object.entries(e.append??{})){let s=hi(n,o);s?s.push(...r.map(String)):n.confirmedFacts[o]=r;}for(let o of e.remove??[])delete n.confirmedFacts[o],delete n.userPreferences[o],gi(n,o);return n}function vl(t){let e=t.rawTurns??3,n=[],o=mi(t.state);o&&n.push({role:"system",content:`Conversation state:
|
|
4
|
+
${o}`});let r=t.history.slice(-e);return n.push(...r,t.current),n}function mi(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`facts: ${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("; ")}`),t.openItems.length&&e.push(`open: ${t.openItems.join("; ")}`),e.join(`
|
|
5
|
+
`)}function hi(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 gi(t,e){for(let n of ["goals","decisions","openItems","evidenceRefs"]){let o=t[n].indexOf(e);o>=0&&t[n].splice(o,1);}}function bi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var No={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function $o(t,e={}){let n=e.delimiter??",",o=e.indent??" ",s=t.split(`
|
|
6
|
+
`).filter(l=>l.trim().length>0).map(l=>({indent:xi(l,o),content:l.slice(Fo(l,o))}));if(s.length===0)return {};let i=s[0];if(i.indent===0){let l=i.content.match(/^\[(\d+)\]\{(.*)\}:\s*$/);if(l){let u=Be(l[2],n),d=Number(l[1]),p=[];for(let f=0,m=1;f<d&&m<s.length;f++,m++){let h=s[m];if(h.indent!==1)break;let g=Be(h.content,n),x={};u.forEach((b,y)=>{x[b]=Ye(g[y]??"null");}),p.push(x);}return p}let c=i.content.match(/^\[(\d+)\]:\s*(.*)$/);if(c){let u=c[2];return Number(c[1])===0||u.trim()===""?[]:Be(u,n).map(Ye)}}let[a]=zo(s,0,0,n);return a}function Fo(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}function xi(t,e){return Fo(t,e)/e.length}function zo(t,e,n,o){let r={},s=e;for(;s<t.length;){let i=t[s];if(i.indent<n)break;if(i.indent>n){s++;continue}let a=yi(i.content,o);if(!a){s++;continue}let{key:l,kind:c}=a;if(c.type==="scalar")r[l]=c.value,s++;else if(c.type==="inlineArray")r[l]=c.values,s++;else if(c.type==="emptyArray")r[l]=[],s++;else if(c.type==="table"){let u=[];s++;for(let d=0;d<c.count&&s<t.length;d++,s++){let p=t[s];if(p.indent!==n+1)break;let f=Be(p.content,o),m={};c.columns.forEach((h,g)=>{m[h]=Ye(f[g]??"null");}),u.push(m);}r[l]=u;}else {let[u,d]=zo(t,s+1,n+1,o);r[l]=u,s=d;}}return [r,s]}function yi(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:bt(n[1]),kind:{type:"table",count:Number(n[2]),columns:Be(n[3],e)}};let o=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(o){let s=Number(o[2]),i=o[3];return s===0||i.trim()===""?{key:bt(o[1]),kind:{type:"emptyArray"}}:{key:bt(o[1]),kind:{type:"inlineArray",values:Be(i,e).map(Ye)}}}let r=t.match(/^([^:]+):\s*(.*)$/);if(r){let s=bt(r[1]),i=r[2];return i===""?{key:s,kind:{type:"object"}}:{key:s,kind:{type:"scalar",value:Ye(i)}}}return null}function Be(t,e){let n=[],o="",r=false;for(let s=0;s<t.length;s++){let i=t[s];r?i==='"'?t[s+1]==='"'?(o+='"',s++):r=false:o+=i:i==='"'?r=true:i===e?(n.push(o),o=""):o+=i;}return n.push(o),n.map(s=>s.trim())}function Ye(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,'"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function bt(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,'"'):e}function vi(t,e={}){let n=e.delimiter??",",o=e.indent??" ",r=[];return kn(null,t,0,r,n,o),r.join(`
|
|
7
|
+
`)}function kn(t,e,n,o,r,s){let i=s.repeat(n),a=t===null?"":`${wi(t)}`;if(Array.isArray(e)){ki(a,e,n,o,r,s);return}if(vn(e)){t!==null&&o.push(`${i}${a}:`);let l=t===null?n:n+1;for(let[c,u]of Object.entries(e))kn(c,u,l,o,r,s);return}o.push(`${i}${a}: ${xt(e,r)}`);}function ki(t,e,n,o,r,s){let i=s.repeat(n),a=t===""?"":t;if(e.length===0){o.push(`${i}${a}[0]:`);return}if(e.every(yn)){let d=e.map(p=>xt(p,r)).join(r);o.push(`${i}${a}[${e.length}]: ${d}`);return}let l=yt(e);if(l){o.push(`${i}${a}[${e.length}]{${l.join(r)}}:`);let d=s.repeat(n+1);for(let p of e){let f=l.map(m=>xt(p[m],r)).join(r);o.push(`${d}${f}`);}return}o.push(`${i}${a}[${e.length}]:`);let c=n+1,u=s.repeat(c);for(let d of e)if(yn(d))o.push(`${u}- ${xt(d,r)}`);else {let p=[];kn(null,d,0,p,r,s);let[f,...m]=p;o.push(`${u}- ${f??""}`);for(let h of m)o.push(`${u}${s}${h}`);}}function yt(t){if(t.length===0)return null;let e=t[0];if(!vn(e))return null;let n=Object.keys(e);if(n.length===0)return null;let o=n.slice().sort().join("\0");for(let r of t){if(!vn(r))return null;let s=Object.keys(r);if(s.slice().sort().join("\0")!==o)return null;for(let i of s)if(!yn(r[i]))return null}return n}function wi(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:Vo(t)}function xt(t,e){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(`
|
|
8
|
+
`)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?Vo(n):n}function Vo(t){return `"${t.replace(/"/g,'""')}"`}function yn(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function vn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Si="Data is the compact encoder: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; each 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 Ti(t={}){return {format:"compact-rows",supports(){return true},encode(e){return vi(e,t)},instruction(){return Si},decode(e){return $o(e,t)}}}var Uo=Ti();var Ho={format:"csv",supports(t){return Array.isArray(t)&&yt(t)!==null},encode(t){let e=t,n=yt(e),o=n.map(qo).join(","),r=e.map(s=>n.map(i=>qo(s[i])).join(","));return [o,...r].join(`
|
|
9
|
+
`)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function qo(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}var vt=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[No,Uo,Ho],this.minSavingsTokens=e.minimumSavingsTokens??64,this.minSavingsRatio=e.minimumSavingsRatio??.08,this.qualityPenalty=e.qualityPenalty??(()=>0);}choose(e,n){let o={model:n.model,tokenizer:n.tokenizer},r=[];for(let c of this.serializers){if(!c.supports(e))continue;let u=c.encode(e);if(c.format!=="json-compact"&&!Ei(c,u,e))continue;let d=c.instruction(e),p=this.tokenizer.count(u,o),f=d?this.tokenizer.count(d,o):0,m=this.qualityPenalty(n.model??"",c.format);r.push({format:c.format,encoded:u,instruction:d,payloadTokens:p,instructionTokens:f,penalty:m,total:p+f+m});}let s=r.find(c=>c.format==="json-compact"),i={};for(let c of r)i[c.format]=c.total;if(!s){let c=r[0];return c?Ko(c,i,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:i,instructionOverheadTokens:0,reason:"no serializer supported payload; defaulted to JSON"}}let a=s,l="json baseline (no challenger cleared thresholds)";for(let c of r){if(c.format==="json-compact")continue;let u=s.total-c.total,d=s.total===0?0:u/s.total;u>=this.minSavingsTokens&&d>=this.minSavingsRatio&&c.total<a.total&&(a=c,l=`${c.format} saved ${u} tokens (${(d*100).toFixed(1)}%) vs json`);}return Ko(a,i,l)}};function Ei(t,e,n){if(!t.decode)return false;try{return wn(t.decode(e),n)}catch{return false}}function wn(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.isArray(t),o=Array.isArray(e);if(n||o){if(!n||!o||t.length!==e.length)return false;for(let i=0;i<t.length;i++)if(!wn(t[i],e[i]))return false;return true}let r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return false;for(let i of r)if(!Object.prototype.hasOwnProperty.call(e,i)||!wn(t[i],e[i]))return false;return true}function Ko(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function se(t,e,n="$"){let o=[];return Sn(t,e,n,o),{valid:o.length===0,errors:o}}function Ri(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function Sn(t,e,n,o){switch(e.enum&&!e.enum.some(s=>Di(s,t))&&o.push({path:n,message:"value not in enum"}),e.type??Ri(t)){case "object":Ci(t,e,n,o);break;case "array":Oi(t,e,n,o);break;case "string":Ii(t,e,n,o);break;case "number":case "integer":_i(t,e,n,o);break;case "boolean":typeof t!="boolean"&&o.push({path:n,message:"expected boolean"});break;case "null":t!==null&&o.push({path:n,message:"expected null"});break;}}function Ci(t,e,n,o){if(typeof t!="object"||t===null||Array.isArray(t)){o.push({path:n,message:"expected object"});return}let r=t;for(let s of e.required??[])s in r||o.push({path:`${n}.${s}`,message:"missing required property"});if(e.additionalProperties===false&&e.properties){let s=new Set(Object.keys(e.properties));for(let i of Object.keys(r))s.has(i)||o.push({path:`${n}.${i}`,message:"additional property not allowed"});}if(e.properties)for(let[s,i]of Object.entries(e.properties))s in r&&Sn(r[s],i,`${n}.${s}`,o);}function Oi(t,e,n,o){if(!Array.isArray(t)){o.push({path:n,message:"expected array"});return}e.maxItems!=null&&t.length>e.maxItems&&o.push({path:n,message:`array exceeds maxItems ${e.maxItems}`}),e.minItems!=null&&t.length<e.minItems&&o.push({path:n,message:`array below minItems ${e.minItems}`}),e.items&&t.forEach((r,s)=>Sn(r,e.items,`${n}[${s}]`,o));}function Ii(t,e,n,o){if(typeof t!="string"){o.push({path:n,message:"expected string"});return}if(e.maxLength!=null&&t.length>e.maxLength&&o.push({path:n,message:`string exceeds maxLength ${e.maxLength}`}),e.minLength!=null&&t.length<e.minLength&&o.push({path:n,message:`string below minLength ${e.minLength}`}),e.pattern){let r=null;try{r=new RegExp(e.pattern);}catch{o.push({path:n,message:`schema pattern is not a valid regular expression: ${e.pattern}`});}r&&!r.test(t)&&o.push({path:n,message:"string does not match pattern"});}}function _i(t,e,n,o){if(typeof t!="number"||Number.isNaN(t)){o.push({path:n,message:"expected number"});return}e.type==="integer"&&!Number.isInteger(t)&&o.push({path:n,message:"expected integer"}),e.maximum!=null&&t>e.maximum&&o.push({path:n,message:`number exceeds maximum ${e.maximum}`}),e.minimum!=null&&t<e.minimum&&o.push({path:n,message:`number below minimum ${e.minimum}`});}function Di(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var kt=class{contracts=new Map;register(e){return this.contracts.set(e.contractId,e),this}resolve(e){return this.contracts.get(e)}has(e){return this.contracts.has(e)}static lint(e,n="$"){let o=[];return Tn(e,n,o),o}};function Tn(t,e,n){if(t.type==="object"){t.additionalProperties!==false&&n.push(`${e}: object should set additionalProperties:false`);for(let[o,r]of Object.entries(t.properties??{}))Tn(r,`${e}.${o}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&Tn(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: string should set maxLength or use an enum`);}function Jo(t,e,n){for(let o of n)if(o.supports(t,e))return {backend:o.id,reason:`first supporting backend: ${o.id}`};return {backend:"none",reason:"no constrained-decoding backend available; will validate + repair"}}function Ul(t=()=>true){return {id:"provider-native",supports:t}}function En(t){let e=t.minimumContextTokens??2e3,n=t.minimumNetTokens??200;if(t.contextTokens<e)return {compress:false,reason:`context ${t.contextTokens} < ${e} min`};let o=t.projectedEliminable-t.compressorCostTokens;return o<n?{compress:false,reason:`net saving ${o} < ${n} min`}:{compress:true,reason:`net saving ${o} tokens`}}function Wl(t){return {async compress(e){let n=e.protectedSpans??[],o=e.text,r=[];n.forEach((l,c)=>{let u=`\0PROTECT_${c}\0`;r.push({token:u,span:l}),o=o.split(l.text).join(u);});let s=await t.compress({text:o,...e.targetRatio!=null?{targetRatio:e.targetRatio}:{}}),i=s.compressed,a=true;for(let{token:l,span:c}of r){if(!i.includes(l)){a=false;break}i=i.split(l).join(c.text);}return a?{...s,compressed:i,protectedSpans:n.length,fidelityPassed:true}:{compressed:e.text,originalTokens:s.originalTokens,compressedTokens:s.originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var Zl={async compress(t){return {compressed:t.text,originalTokens:0,compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};var Go=new WeakSet;function Wo(t){Go.add(t);}var Rn=class{id="mock";options;constructor(e={}){this.options=e,Wo(this);}async generate(e){let n=e.messages.map(a=>a.content).join(`
|
|
10
|
+
`),o=Me.count(n);if(e.tools&&e.tools.length>0){let a=JSON.stringify(e.tools.map(l=>({name:l.id,description:l.description,parameters:l.parameters??{}})));o+=Me.count(a);}let r,s=false;if(e.schema){let a=this.options.data??wt(e.schema);r=JSON.stringify(a),s=true;}else r=this.options.answer??`mock-response(${e.model})`;let i=Math.min(e.maxOutputTokens??Number.MAX_SAFE_INTEGER,Me.count(r));return {text:r,usage:{inputTokens:o,outputTokens:i,...this.options.cachedInputTokens!=null?{cachedInputTokens:this.options.cachedInputTokens}:{}},structuredNatively:s}}};function wt(t){if(t.enum&&t.enum.length>0)return t.enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let o=t.properties?.[n];e[n]=o?wt(o):null;}for(let[n,o]of Object.entries(t.properties??{}))n in e||(e[n]=wt(o));return e}case "array":return t.items?[wt(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 ou(t){return new Rn(t)}var Ai={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},St="flex";function Yo(t){if(t==null||t==="")return null;let e=Ai[t];return e==null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}function Xo(t,e){return !t||t.factor==null||!t.conDescuento||!Number.isFinite(e)||e<=0?null:e*(1-t.factor)}var Li="slower and variable: OpenAI publishes no latency commitment for the flex tier. What IS documented is the failure shape \u2014 the default SDK timeout is 10 minutes and a request that exceeds it returns 408, and when flex capacity is short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",Mi="unchanged: this provider has no cheaper synchronous processing tier, so nothing was asked for and the request was scheduled exactly as it would have been.",Qo="this provider has no cheaper synchronous processing tier, so the request was sent unchanged and nothing is credited; on this provider the deferred discount lives only in the asynchronous batch API, which is not a request/response call";function er(t){return t==null||t===""?Mi:t===St?Li:`unknown: this layer has no published latency statement for the "${t}" tier.`}var tr=new Set;function G(t,e){tr.has(t)||(tr.add(t),console.warn(e));}function Oe(t){if(t==null||typeof t!="object")return true;let e=t,n=e.properties;if(n&&typeof n=="object"){if(e.additionalProperties!==false)return false;let r=Object.keys(n),s=Array.isArray(e.required)?e.required.map(String):[];if(r.some(i=>!s.includes(i)))return false;for(let i of Object.values(n))if(!Oe(i))return false}if(e.items!==void 0&&!Oe(e.items))return false;for(let r of ["anyOf","oneOf","allOf"]){let s=e[r];if(Array.isArray(s)&&s.some(i=>!Oe(i)))return false}let o=e.$defs??e.definitions;return !(o&&typeof o=="object"&&Object.values(o).some(r=>!Oe(r)))}function Pi(t){return !/response_format/i.test(t)||/invalid schema/i.test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.test(t)}function Bi(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:
|
|
11
|
+
`+JSON.stringify(t)}var nr=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.opts.stripProviderPrefix?e.model.replace(/^[^/]+\//,""):e.model,o=e.schema!=null&&!this.sinResponseFormat.has(n),r=await this.enviar(n,e,o);if(!r.ok&&r.status===400&&o){let s=await or(r);if(!Pi(s))throw new Error(`provider ${r.status}: ${s}`);this.sinResponseFormat.add(n),G(`sin-response-format:${n}`,`[bvsala] El modelo "${n}" rechaza \`response_format\` con un 400: no tiene structured outputs. Se repite la petici\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 proveedor, y el informe lo dice: \`constraints.backend: "none"\`. Para recuperar la garant\xEDa nativa, usa un modelo con structured outputs (gpt-4o o posterior).`),o=false,r=await this.enviar(n,e,false);}if(!r.ok){let s=await or(r);throw new Error(`provider ${r.status}: ${s}`)}return this.leer(r,e,o)}async enviar(e,n,o){let r=n.messages.map(i=>({role:i.role,content:i.content}));n.schema&&!o&&r.push({role:"system",content:Bi(n.schema)});let s={model:e,messages:r};if(n.maxOutputTokens!=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&&(s.service_tier=St),n.schema&&o){let i=Oe(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 claves 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, 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&&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(`${this.opts.baseUrl.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.headers},body:JSON.stringify(s)})}async leer(e,n,o){let r=await e.json(),s=r.choices?.[0]?.message,i=s?.content??"",a=(s?.tool_calls??[]).map(h=>({...h.id?{id:h.id}:{},name:h.function?.name??"",arguments:h.function?.arguments??""})).filter(h=>h.name!==""),l=r.usage??{},c=l.prompt_tokens??0,u=l.completion_tokens??0,d=typeof l.prompt_tokens!="number",p=typeof l.completion_tokens!="number";if(this.opts.requireUsage&&(d||p))throw new Error(`provider returned incomplete usage (prompt=${l.prompt_tokens??"absent"}, completion=${l.completion_tokens??"absent"}); cannot measure cost. For gateways/streaming, ensure usage reporting is enabled.`);let f=r.choices?.[0]?.finish_reason,m=typeof r.service_tier=="string"&&r.service_tier!==""?r.service_tier:void 0;return {text:i,...a.length>0?{toolCalls:a}:{},...f?{finishReason:f}:{},...m?{servedServiceTier:m}:{},...n.deferrable===true?{requestedServiceTier:St}:{},usage:{inputTokens:c,outputTokens:u,...l.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:l.prompt_tokens_details.cached_tokens}:{}},structuredNatively:n.schema!=null&&o,raw:r}}};async function or(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function rr(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:
|
|
12
|
+
`+JSON.stringify(t)}var sr=4,je="bvsala_contract",ir=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),o=(this.opts.baseUrl??"https://api.anthropic.com/v1").replace(/\/$/,""),r=await this.fetchImpl(`${o}/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(!r.ok)throw new Error(`provider ${r.status}: ${await $i(r)}`);return this.leer(r,e,n.contratoNativo)}construirCuerpo(e){let{system:n,messages:o,prefijoEnMensajes:r,prefijoEnSystem:s}=ji(e);if(o.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(c=>({name:c.id,...c.description?{description:c.description}:{},input_schema:c.parameters??{type:"object",properties:{}}})),a=false;if(e.schema){let c=i.length>0,u=i.some(p=>p.name===je),d=Oe(e.schema);u?(n.push({type:"text",text:rr(e.schema)}),G("anthropic-contrato-nombre-ocupado",`[bvsala] One of your tools is already named \`${je}\`, 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.`)):(!d&&!c&&G("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=d&&!c,i.push({name:je,description:c?"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}:{}}),c&&G("anthropic-contrato-con-herramientas","[bvsala] This request carries BOTH your tools and an output contract. On Anthropic's Messages API a shape is only GUARANTEED by forcing a tool call, and forcing ours would leave the model unable to call yours. The contract travels as one extra, non-forced tool: cheaper than sending the schema as prompt text and it keeps your tool turn intact, but the guarantee is the layer's, not the provider's (`constraints.backend: \"none\"`). If the model answers in prose anyway, 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:o};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:je}),e.deferrable===true&&G("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,o,r,s),{body:l,contratoNativo:a}}marcarCache(e,n,o,r,s){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return;let i=Math.min(this.opts.maxCacheBreakpoints??sr,sr);if(i<=0)return;let a=s>0?n[s-1]:void 0;if(a&&(a.cache_control={type:"ephemeral"},i-=1),i>0&&r>0){let l=o[Math.min(r,o.length)-1],c=l?.content[l.content.length-1];c&&(c.cache_control={type:"ephemeral"});}}async leer(e,n,o){let r=await e.json(),s=r.content??[],i=s.filter(b=>b.type==="text").map(b=>b.text??"").join(""),a=s.filter(b=>b.type==="tool_use"&&b.name!==je).map(b=>({...b.id?{id:b.id}:{},name:b.name??"",arguments:JSON.stringify(b.input??{})})).filter(b=>b.name!==""),l=s.find(b=>b.type==="tool_use"&&b.name===je),c=l?JSON.stringify(l.input??{}):i,u=r.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,h=typeof u.input_tokens!="number",g=typeof u.output_tokens!="number";if(this.opts.requireUsage&&(h||g))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:c,...a.length>0?{toolCalls:a}:{},...r.stop_reason?{finishReason:Ni(r.stop_reason)}:{},...x?{servedServiceTier:x}:{},usage:{inputTokens:f,outputTokens:m,...d!=null?{cachedInputTokens:d}:{},...p!=null?{cacheWriteInputTokens:p}:{}},structuredNatively:n.schema!=null&&o,raw:r}}};function ji(t){let e=[],n=[],o=t.stablePrefixMessages??0,r=0,s=0,i=true;return t.messages.forEach((a,l)=>{if(a.role==="system"&&i){e.push({type:"text",text:a.content}),l<o&&(s=e.length);return}i=false,n.push({role:a.role==="assistant"?"assistant":"user",content:[{type:"text",text:a.content}]}),l<o&&(r=n.length);}),n.length>0&&n[0].role==="assistant"&&(n.unshift({role:"user",content:[{type:"text",text:"(continue)"}]}),r>0&&(r+=1)),{system:e,messages:n,prefijoEnMensajes:r,prefijoEnSystem:s}}function Ni(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 $i(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}var Xe=class{events=[];start;now;constructor(e=()=>Date.now()){this.now=e,this.start=e();}record(e,n,o){this.events.push({stage:e,outcome:n,...o?{detail:o}:{},atMs:this.now()-this.start});}elapsed(){return this.now()-this.start}all(){return this.events}};var Ie=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function Cn(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Tt(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 ee(t,e,n=""){let o=Cn(t),r=t?.length,s=e!==void 0;if(!o||s&&r!==e){let i=n&&`"${n}" `,a=s?` of length ${e}`:"",l=o?`length=${r}`:`type=${typeof t}`,c=i+"expected Uint8Array"+a+", got "+l;throw o?new RangeError(c):new TypeError(c)}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 cr(t,e){ee(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 Qe(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function Et(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var lr=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Fi=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Rt(t){if(ee(t),lr)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Fi[t[n]];return e}var de={_0:48,_9:57,A:65,F:70,a:97,f:102};function ar(t){if(t>=de._0&&t<=de._9)return t-de._0;if(t>=de.A&&t<=de.F)return t-(de.A-10);if(t>=de.a&&t<=de.f)return t-(de.a-10)}function et(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(lr)try{return Uint8Array.fromHex(t)}catch(r){throw r instanceof SyntaxError?new RangeError(r.message):r}let e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let o=new Uint8Array(n);for(let r=0,s=0;r<n;r++,s+=2){let i=ar(t.charCodeAt(s)),a=ar(t.charCodeAt(s+1));if(i===void 0||a===void 0){let l=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+l+'" at index '+s)}o[r]=i*16+a;}return o}function In(...t){let e=0;for(let o=0;o<t.length;o++){let r=t[o];ee(r),e+=r.length;}let n=new Uint8Array(e);for(let o=0,r=0;o<t.length;o++){let s=t[o];n.set(s,r),r+=s.length;}return n}function ur(t,e={}){let n=(r,s)=>t(s).update(r).digest(),o=t(void 0);return n.outputLen=o.outputLen,n.blockLen=o.blockLen,n.canXOF=o.canXOF,n.create=r=>t(r),Object.assign(n,e),Object.freeze(n)}function dr(t=32){Tt(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 pr=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var Ct=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(e,n,o,r){this.blockLen=e,this.outputLen=n,this.padOffset=o,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Et(this.buffer);}update(e){On(this),ee(e);let{view:n,buffer:o,blockLen:r}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(r-this.pos,s-i);if(a===r){let l=Et(e);for(;r<=s-i;i+=r)this.process(l,i);continue}o.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===r&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){On(this),cr(e,this),this.finished=true;let{buffer:n,view:o,blockLen:r,isLE:s}=this,{pos:i}=this;n[i++]=128,Qe(this.buffer.subarray(i)),this.padOffset>r-i&&(this.process(o,0),i=0);for(let d=i;d<r;d++)n[d]=0;o.setBigUint64(r-8,BigInt(this.length*8),s),this.process(o,0);let a=Et(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=l/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)a.setUint32(4*d,u[d],s);}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let o=e.slice(0,n);return this.destroy(),o}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:n,buffer:o,length:r,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=r,e.pos=a,r%n&&e.buffer.set(o),e}clone(){return this._cloneInto()}};var q=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Ot=BigInt(4294967295),fr=BigInt(32);function zi(t,e=false){return e?{h:Number(t&Ot),l:Number(t>>fr&Ot)}:{h:Number(t>>fr&Ot)|0,l:Number(t&Ot)|0}}function mr(t,e=false){let n=t.length,o=new Uint32Array(n),r=new Uint32Array(n);for(let s=0;s<n;s++){let{h:i,l:a}=zi(t[s],e);[o[s],r[s]]=[i,a];}return [o,r]}var _n=(t,e,n)=>t>>>n,Dn=(t,e,n)=>t<<32-n|e>>>n,_e=(t,e,n)=>t>>>n|e<<32-n,De=(t,e,n)=>t<<32-n|e>>>n,tt=(t,e,n)=>t<<64-n|e>>>n-32,nt=(t,e,n)=>t>>>n-32|e<<64-n;function ie(t,e,n,o){let r=(e>>>0)+(o>>>0);return {h:t+n+(r/2**32|0)|0,l:r|0}}var hr=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),gr=(t,e,n,o)=>e+n+o+(t/2**32|0)|0,br=(t,e,n,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),xr=(t,e,n,o,r)=>e+n+o+r+(t/2**32|0)|0,yr=(t,e,n,o,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0)+(r>>>0),vr=(t,e,n,o,r,s)=>e+n+o+r+s+(t/2**32|0)|0;var kr=mr(["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))),Ui=kr[0],qi=kr[1],ve=new Uint32Array(80),ke=new Uint32Array(80),An=class extends Ct{constructor(e){super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:o,Bl:r,Ch:s,Cl:i,Dh:a,Dl:l,Eh:c,El:u,Fh:d,Fl:p,Gh:f,Gl:m,Hh:h,Hl:g}=this;return [e,n,o,r,s,i,a,l,c,u,d,p,f,m,h,g]}set(e,n,o,r,s,i,a,l,c,u,d,p,f,m,h,g){this.Ah=e|0,this.Al=n|0,this.Bh=o|0,this.Bl=r|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=l|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=f|0,this.Gl=m|0,this.Hh=h|0,this.Hl=g|0;}process(e,n){for(let y=0;y<16;y++,n+=4)ve[y]=e.getUint32(n),ke[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){let E=ve[y-15]|0,C=ke[y-15]|0,I=_e(E,C,1)^_e(E,C,8)^_n(E,C,7),T=De(E,C,1)^De(E,C,8)^Dn(E,C,7),D=ve[y-2]|0,R=ke[y-2]|0,S=_e(D,R,19)^tt(D,R,61)^_n(D,R,6),M=De(D,R,19)^nt(D,R,61)^Dn(D,R,6),v=br(T,M,ke[y-7],ke[y-16]),w=xr(v,I,S,ve[y-7],ve[y-16]);ve[y]=w|0,ke[y]=v|0;}let{Ah:o,Al:r,Bh:s,Bl:i,Ch:a,Cl:l,Dh:c,Dl:u,Eh:d,El:p,Fh:f,Fl:m,Gh:h,Gl:g,Hh:x,Hl:b}=this;for(let y=0;y<80;y++){let E=_e(d,p,14)^_e(d,p,18)^tt(d,p,41),C=De(d,p,14)^De(d,p,18)^nt(d,p,41),I=d&f^~d&h,T=p&m^~p&g,D=yr(b,C,T,qi[y],ke[y]),R=vr(D,x,E,I,Ui[y],ve[y]),S=D|0,M=_e(o,r,28)^tt(o,r,34)^tt(o,r,39),v=De(o,r,28)^nt(o,r,34)^nt(o,r,39),w=o&s^o&a^s&a,_=r&i^r&l^i&l;x=h|0,b=g|0,h=f|0,g=m|0,f=d|0,m=p|0,{h:d,l:p}=ie(c|0,u|0,R|0,S|0),c=a|0,u=l|0,a=s|0,l=i|0,s=o|0,i=r|0;let A=hr(S,v,_);o=gr(A,R,M,w),r=A|0;}(({h:o,l:r}=ie(this.Ah|0,this.Al|0,o|0,r|0))),{h:s,l:i}=ie(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l}=ie(this.Ch|0,this.Cl|0,a|0,l|0),{h:c,l:u}=ie(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l:p}=ie(this.Eh|0,this.El|0,d|0,p|0),{h:f,l:m}=ie(this.Fh|0,this.Fl|0,f|0,m|0),{h,l:g}=ie(this.Gh|0,this.Gl|0,h|0,g|0),{h:x,l:b}=ie(this.Hh|0,this.Hl|0,x|0,b|0),this.set(o,r,s,i,a,l,c,u,d,p,f,m,h,g,x,b);}roundClean(){Qe(ve,ke);}destroy(){this.destroyed=true,Qe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},Ln=class extends An{Ah=q[0]|0;Al=q[1]|0;Bh=q[2]|0;Bl=q[3]|0;Ch=q[4]|0;Cl=q[5]|0;Dh=q[6]|0;Dl=q[7]|0;Eh=q[8]|0;El=q[9]|0;Fh=q[10]|0;Fl=q[11]|0;Gh=q[12]|0;Gl=q[13]|0;Hh=q[14]|0;Hl=q[15]|0;constructor(){super(64);}};var It=ur(()=>new Ln,pr(3));var $=(t,e,n)=>ee(t,e,n),Pn=Tt,Bn=Rt,ae=(...t)=>In(...t),wr=t=>et(t),At=Cn,Sr=t=>dr(t),Dt=BigInt(0),Mn=BigInt(1);function Ne(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"expected boolean, got type="+typeof t)}return t}function Hi(t){if(typeof t=="bigint"){if(!_t(t))throw new RangeError("positive bigint expected, got "+t)}else Pn(t);return t}function pe(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 Tr(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Dt:BigInt("0x"+t)}function jn(t){return Tr(Rt(t))}function fe(t){return Tr(Rt(ot(ee(t)).reverse()))}function Nn(t,e){if(Tt(e),e===0)throw new RangeError("zero length");t=Hi(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return et(n.padStart(e*2,"0"))}function Er(t,e){return Nn(t,e).reverse()}function Rr(t,e){if(t=$(t),e=$(e),t.length!==e.length)return false;let n=0;for(let o=0;o<t.length;o++)n|=t[o]^e[o];return n===0}function ot(t){return Uint8Array.from($(t))}var _t=t=>typeof t=="bigint"&&Dt<=t;function Ki(t,e,n){return _t(t)&&_t(e)&&_t(n)&&e<=t&&t<n}function $n(t,e,n,o){if(!Ki(e,n,o))throw new RangeError("expected valid "+t+": "+n+" <= n < "+o+", got "+e)}function Fn(t){if(t<Dt)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>Dt;t>>=Mn,e+=1);return e}var Cr=t=>(Mn<<BigInt(t))-Mn;function Ae(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function o(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let l=t[s];if(a&&l===void 0)return;let c=typeof l;if(c!==i||l===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${c}`)}let r=(s,i)=>Object.entries(s).forEach(([a,l])=>o(a,l,i));r(e,false),r(n,true);}var zn=()=>{throw new Error("not implemented")};var H=BigInt(0),z=BigInt(1),Le=BigInt(2),Dr=BigInt(3),Ar=BigInt(4),Lr=BigInt(5),Ji=BigInt(7),Mr=BigInt(8),Gi=BigInt(9),Pr=BigInt(16);function N(t,e){if(e<=H)throw new Error("mod: expected positive modulus, got "+e);let n=t%e;return n>=H?n:e+n}function te(t,e,n){if(e<H)throw new Error("pow2: expected non-negative exponent, got "+e);let o=t;for(;e-- >H;)o*=o,o%=n;return o}function Or(t,e){if(t===H)throw new Error("invert: expected non-zero number");if(e<=H)throw new Error("invert: expected positive modulus, got "+e);let n=N(t,e),o=e,r=H,i=z;for(;n!==H;){let c=o/n,u=o-n*c,d=r-i*c;o=n,n=u,r=i,i=d;}if(o!==z)throw new Error("invert: does not exist");return N(r,e)}function Vn(t,e,n){let o=t;if(!o.eql(o.sqr(e),n))throw new Error("Cannot find square root")}function Br(t,e){let n=t,o=(n.ORDER+z)/Ar,r=n.pow(e,o);return Vn(n,r,e),r}function Wi(t,e){let n=t,o=(n.ORDER-Lr)/Mr,r=n.mul(e,Le),s=n.pow(r,o),i=n.mul(e,s),a=n.mul(n.mul(i,Le),s),l=n.mul(i,n.sub(a,n.ONE));return Vn(n,l,e),l}function Zi(t){let e=Bt(t),n=jr(t),o=n(e,e.neg(e.ONE)),r=n(e,o),s=n(e,e.neg(o)),i=(t+Ji)/Pr;return((a,l)=>{let c=a,u=c.pow(l,i),d=c.mul(u,o),p=c.mul(u,r),f=c.mul(u,s),m=c.eql(c.sqr(d),l),h=c.eql(c.sqr(p),l);u=c.cmov(u,d,m),d=c.cmov(f,p,h);let g=c.eql(c.sqr(d),l),x=c.cmov(u,d,g);return Vn(c,x,l),x})}function jr(t){if(t<Dr)throw new Error("sqrt is not defined for small field");let e=t-z,n=0;for(;e%Le===H;)e/=Le,n++;let o=Le,r=Bt(t);for(;Ir(r,o)===1;)if(o++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Br;let s=r.pow(o,e),i=(e+z)/Le;return function(l,c){let u=l;if(u.is0(c))return c;if(Ir(u,c)!==1)throw new Error("Cannot find square root");let d=n,p=u.mul(u.ONE,s),f=u.pow(c,e),m=u.pow(c,i);for(;!u.eql(f,u.ONE);){if(u.is0(f))return u.ZERO;let h=1,g=u.sqr(f);for(;!u.eql(g,u.ONE);)if(h++,g=u.sqr(g),h===d)throw new Error("Cannot find square root");let x=z<<BigInt(d-h-1),b=u.pow(p,x);d=h,p=u.sqr(b),f=u.mul(f,p),m=u.mul(m,b);}return m}}function Yi(t){return t%Ar===Dr?Br:t%Mr===Lr?Wi:t%Pr===Gi?Zi(t):jr(t)}var me=(t,e)=>(N(t,e)&z)===z,Xi=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Nr(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=Xi.reduce((o,r)=>(o[r]="function",o),e);if(Ae(t,n),pe(t.BYTES,"BYTES"),pe(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=z)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Qi(t,e,n){let o=t;if(n<H)throw new Error("invalid exponent, negatives unsupported");if(n===H)return o.ONE;if(n===z)return e;let r=o.ONE,s=e;for(;n>H;)n&z&&(r=o.mul(r,s)),s=o.sqr(s),n>>=z;return r}function Pt(t,e,n=false){let o=t,r=new Array(e.length).fill(n?o.ZERO:void 0),s=e.reduce((a,l,c)=>o.is0(l)?a:(r[c]=a,o.mul(a,l)),o.ONE),i=o.inv(s);return e.reduceRight((a,l,c)=>o.is0(l)?a:(r[c]=o.mul(a,r[c]),o.mul(a,l)),i),r}function Ir(t,e){let n=t,o=(n.ORDER-z)/Le,r=n.pow(e,o),s=n.eql(r,n.ONE),i=n.eql(r,n.ZERO),a=n.eql(r,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function ea(t,e){if(e!==void 0&&Pn(e),t<=H)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=Fn(t);if(e!==void 0&&e<n)throw new Error(`invalid n length: expected bit length (${n}) >= n.length (${e})`);let o=e!==void 0?e:n,r=Math.ceil(o/8);return {nBitLength:o,nByteLength:r}}var _r=new WeakMap,Mt=class{ORDER;BITS;BYTES;isLE;ZERO=H;ONE=z;_lengths;_mod;constructor(e,n={}){if(e<=z)throw new Error("invalid field: expected ORDER > 1, got "+e);let o;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(o=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:true}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:r,nByteLength:s}=ea(e,o);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=r,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 H<=e&&e<this.ORDER}is0(e){return e===H}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&z)===z}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 Qi(this,e,n)}div(e,n){return N(e*Or(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 Or(e,this.ORDER)}sqrt(e){let n=_r.get(this);return n||_r.set(this,n=Yi(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?Er(e,this.BYTES):Nn(e,this.BYTES)}fromBytes(e,n=false){$(e);let{_lengths:o,BYTES:r,isLE:s,ORDER:i,_mod:a}=this;if(o){if(e.length<1||!o.includes(e.length)||e.length>r)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=new Uint8Array(r);c.set(e,s?0:c.length-e.length),e=c;}if(e.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=s?fe(e):jn(e);if(a&&(l=N(l,i)),!n&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return Pt(this,e)}cmov(e,n,o){return Ne(o,"condition"),o?n:e}};Object.freeze(Mt.prototype);function Bt(t,e={}){return new Mt(t,e)}var jt=BigInt(0),Kn=BigInt(1);function $r(t,e){let n=e.negate();return t?n:e}function $t(t,e){let n=Pt(t.Fp,e.map(o=>o.Z));return e.map((o,r)=>t.fromAffine(o.toAffine(n[r])))}function Ur(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Un(t,e){Ur(t,e);let n=Math.ceil(e/t)+1,o=2**(t-1),r=2**t,s=Cr(t),i=BigInt(t);return {windows:n,windowSize:o,mask:s,maxNumber:r,shiftBy:i}}function Fr(t,e,n){let{windowSize:o,mask:r,maxNumber:s,shiftBy:i}=n,a=Number(t&r),l=t>>i;a>o&&(a-=s,l+=Kn);let c=e*o,u=c+Math.abs(a)-1,d=a===0,p=a<0,f=e%2!==0;return {nextN:l,offset:u,isZero:d,isNeg:p,isNegF:f,offsetF:c}}var qn=new WeakMap,qr=new WeakMap;function Hn(t){return qr.get(t)||1}function zr(t){if(t!==jt)throw new Error("invalid wNAF")}var Nt=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,o=this.ZERO){let r=e;for(;n>jt;)n&Kn&&(o=o.add(r)),r=r.double(),n>>=Kn;return o}precomputeWindow(e,n){let{windows:o,windowSize:r}=Un(n,this.bits),s=[],i=e,a=i;for(let l=0;l<o;l++){a=i,s.push(a);for(let c=1;c<r;c++)a=a.add(i),s.push(a);i=a.double();}return s}wNAF(e,n,o){if(!this.Fn.isValid(o))throw new Error("invalid scalar");let r=this.ZERO,s=this.BASE,i=Un(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:l,offset:c,isZero:u,isNeg:d,isNegF:p,offsetF:f}=Fr(o,a,i);o=l,u?s=s.add($r(p,n[f])):r=r.add($r(d,n[c]));}return zr(o),{p:r,f:s}}wNAFUnsafe(e,n,o,r=this.ZERO){let s=Un(e,this.bits);for(let i=0;i<s.windows&&o!==jt;i++){let{nextN:a,offset:l,isZero:c,isNeg:u}=Fr(o,i,s);if(o=a,!c){let d=n[l];r=r.add(u?d.negate():d);}}return zr(o),r}getPrecomputes(e,n,o){let r=qn.get(n);return r||(r=this.precomputeWindow(n,e),e!==1&&(typeof o=="function"&&(r=o(r)),qn.set(n,r))),r}cached(e,n,o){let r=Hn(e);return this.wNAF(r,this.getPrecomputes(r,e,o),n)}unsafe(e,n,o,r){let s=Hn(e);return s===1?this._unsafeLadder(e,n,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,o),n,r)}createCache(e,n){Ur(n,this.bits),qr.set(e,n),qn.delete(e);}hasCache(e){return Hn(e)!==1}};function Vr(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Nr(e),e}else return Bt(t,{isLE:n})}function Hr(t,e,n={},o){if(o===void 0&&(o=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let l of ["p","n","h"]){let c=e[l];if(!(typeof c=="bigint"&&c>jt))throw new Error(`CURVE.${l} must be positive bigint`)}let r=Vr(e.p,n.Fp,o),s=Vr(e.n,n.Fn,o),a=["Gx","Gy","a","d"];for(let l of a)if(!r.isValid(e[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:s}}function Kr(t,e){return function(o){let r=t(o);return {secretKey:r,publicKey:e(r)}}}var we=BigInt(0),V=BigInt(1),Jn=BigInt(2),ta=BigInt(8);function na(t,e,n,o){let r=t.sqr(n),s=t.sqr(o),i=t.add(t.mul(e.a,r),s),a=t.add(t.ONE,t.mul(e.d,t.mul(r,s)));return t.eql(i,a)}function Jr(t,e={}){let n=e,o=Hr("edwards",t,n,n.FpFnLE),{Fp:r,Fn:s}=o,i=o.CURVE,{h:a}=i;Ae(n,{},{uvRatio:"function"});let l=Jn<<BigInt(s.BYTES*8)-V,c=h=>r.create(h),u=n.uvRatio===void 0?(h,g)=>{try{return {isValid:!0,value:r.sqrt(r.div(h,g))}}catch{return {isValid:false,value:we}}}:n.uvRatio;if(!na(r,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(h,g,x=false){let b=x?V:we;return $n("coordinate "+h,g,b,l),g}function p(h){if(!(h instanceof f))throw new Error("EdwardsPoint expected")}class f{static BASE=new f(i.Gx,i.Gy,V,c(i.Gx*i.Gy));static ZERO=new f(we,V,V,we);static Fp=r;static Fn=s;X;Y;Z;T;constructor(g,x,b,y){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 f)throw new Error("extended point not allowed");let{x,y:b}=g||{};return d("x",x),d("y",b),new f(x,b,V,c(x*b))}static fromBytes(g,x=false){let b=r.BYTES,{a:y,d:E}=i;g=ot($(g,b,"point")),Ne(x,"zip215");let C=ot(g),I=g[b-1];C[b-1]=I&-129;let T=fe(C),D=x?l:r.ORDER;$n("point.y",T,we,D);let R=c(T*T),S=c(R-V),M=c(E*R-y),{isValid:v,value:w}=u(S,M);if(!v)throw new Error("bad point: invalid y coordinate");let _=(w&V)===V,A=(I&128)!==0;if(!x&&w===we&&A)throw new Error("bad point: x=0 and x_0=1");return A!==_&&(w=c(-w)),f.fromAffine({x:w,y:T})}static fromHex(g,x=false){return f.fromBytes(wr(g),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,x=true){return m.createCache(this,g),x||this.multiply(Jn),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:I}=g,T=c(y*y),D=c(E*E),R=c(C*C),S=c(R*R),M=c(T*x),v=c(R*c(M+D)),w=c(S+c(b*c(T*D)));if(v!==w)throw new Error("bad point: equation left != right (1)");let _=c(y*E),A=c(C*I);if(_!==A)throw new Error("bad point: equation left != right (2)")}equals(g){p(g);let{X:x,Y:b,Z:y}=this,{X:E,Y:C,Z:I}=g,T=c(x*I),D=c(E*y),R=c(b*I),S=c(C*y);return T===D&&R===S}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:g}=i,{X:x,Y:b,Z:y}=this,E=c(x*x),C=c(b*b),I=c(Jn*c(y*y)),T=c(g*E),D=x+b,R=c(c(D*D)-E-C),S=T+C,M=S-I,v=T-C,w=c(R*M),_=c(S*v),A=c(R*v),B=c(M*S);return new f(w,_,B,A)}add(g){p(g);let{a:x,d:b}=i,{X:y,Y:E,Z:C,T:I}=this,{X:T,Y:D,Z:R,T:S}=g,M=c(y*T),v=c(E*D),w=c(I*b*S),_=c(C*R),A=c((y+E)*(T+D)-M-v),B=_-w,F=_+w,O=c(v-x*M),X=c(A*B),U=c(F*O),ne=c(A*O),K=c(B*F);return new f(X,U,K,ne)}subtract(g){return p(g),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}=m.cached(this,g,y=>$t(f,y));return $t(f,[x,b])[0]}multiplyUnsafe(g){if(!s.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===we?f.ZERO:this.is0()||g===V?this:m.unsafe(this,g,x=>$t(f,x))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return m.unsafe(this,i.n).is0()}toAffine(g){let x=this,b=g,{X:y,Y:E,Z:C}=x,I=x.is0();b==null&&(b=I?ta:r.inv(C));let T=c(y*b),D=c(E*b),R=r.mul(C,b);if(I)return {x:we,y:V};if(R!==V)throw new Error("invZ was invalid");return {x:T,y:D}}clearCofactor(){return a===V?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:x}=this.toAffine(),b=r.toBytes(x);return b[b.length-1]|=g&V?128:0,b}toHex(){return Bn(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=new Nt(f,s.BITS);return s.BITS>=8&&f.BASE.precompute(8),Object.freeze(f.prototype),Object.freeze(f),f}var Ft=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e;}static fromBytes(e){zn();}static fromHex(e){zn();}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 Bn(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 Gr(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');let o=e,r=n;Ae(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=r,{BASE:i,Fp:a,Fn:l}=t,c=o.outputLen,u=2*a.BYTES;if(c!==void 0&&(pe(c,"hash.outputLen"),c!==u))throw new Error(`hash.outputLen must be ${u}, got ${c}`);let d=r.randomBytes===void 0?Sr:r.randomBytes,p=r.adjustScalarBytes===void 0?v=>v:r.adjustScalarBytes,f=r.domain===void 0?(v,w,_)=>{if(Ne(_,"phflag"),w.length||_)throw new Error("Contexts/pre-hash are not supported");return v}:r.domain;function m(v){return l.create(fe(v))}function h(v){let w=T.secretKey;$(v,T.secretKey,"secretKey");let _=$(o(v),2*w,"hashedSecretKey"),A=p(_.slice(0,w)),B=_.slice(w,2*w),F=m(A);return {head:A,prefix:B,scalar:F}}function g(v){let{head:w,prefix:_,scalar:A}=h(v),B=i.multiply(A),F=B.toBytes();return {head:w,prefix:_,scalar:A,point:B,pointBytes:F}}function x(v){return g(v).pointBytes}function b(v=Uint8Array.of(),...w){let _=ae(...w);return m(o(f(_,$(v,void 0,"context"),!!s)))}function y(v,w,_={}){v=$(v,void 0,"message"),s&&(v=s(v));let{prefix:A,scalar:B,pointBytes:F}=g(w),O=b(_.context,A,v),X=i.multiply(O).toBytes(),U=b(_.context,X,F,v),ne=l.create(O+U*B);if(!l.isValid(ne))throw new Error("sign failed: invalid s");let K=ae(X,l.toBytes(ne));return $(K,T.signature,"result")}let E={zip215:r.zip215};function C(v,w,_,A=E){let{context:B}=A,F=A.zip215===void 0?!!E.zip215:A.zip215,O=T.signature;v=$(v,O,"signature"),w=$(w,void 0,"message"),_=$(_,T.publicKey,"publicKey"),F!==void 0&&Ne(F,"zip215"),s&&(w=s(w));let X=O/2,U=v.subarray(0,X),ne=fe(v.subarray(X,O)),K,ce,Ke;try{K=t.fromBytes(_,F),ce=t.fromBytes(U,F),Ke=i.multiplyUnsafe(ne);}catch{return false}if(!F&&K.isSmallOrder())return false;let ge=b(B,U,_,w);return ce.add(K.multiplyUnsafe(ge)).subtract(Ke).clearCofactor().is0()}let I=a.BYTES,T={secretKey:I,publicKey:I,signature:2*I,seed:I};function D(v){return v=v===void 0?d(T.seed):v,$(v,T.seed,"seed")}function R(v){return At(v)&&v.length===T.secretKey}function S(v,w){try{return !!t.fromBytes(v,w===void 0?E.zip215:w)}catch{return false}}let M={getExtendedPublicKey:g,randomSecretKey:D,isValidSecretKey:R,isValidPublicKey:S,toMontgomery(v){let{y:w}=t.fromBytes(v),_=T.publicKey,A=_===32;if(!A&&_!==57)throw new Error("only defined for 25519 and 448");let B=A?a.div(V+w,V-w):a.div(w-V,w+V);return a.toBytes(B)},toMontgomerySecret(v){let w=T.secretKey;$(v,w);let _=o(v.subarray(0,w));return p(_).subarray(0,w)}};return Object.freeze(T),Object.freeze(M),Object.freeze({keygen:Kr(D,x),getPublicKey:x,sign:y,verify:C,utils:M,Point:t,lengths:T})}var sa=BigInt(0),he=BigInt(1),Zr=BigInt(2);var ia=BigInt(5),aa=BigInt(8),$e=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Xn={p:$e,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:aa,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ca(t){let e=BigInt(10),n=BigInt(20),o=BigInt(40),r=BigInt(80),s=$e,a=t*t%s*t%s,l=te(a,Zr,s)*a%s,c=te(l,he,s)*t%s,u=te(c,ia,s)*c%s,d=te(u,e,s)*u%s,p=te(d,n,s)*d%s,f=te(p,o,s)*p%s,m=te(f,r,s)*f%s,h=te(m,r,s)*f%s,g=te(h,e,s)*u%s;return {pow_p_5_8:te(g,Zr,s)*t%s,b2:a}}function la(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var Wn=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Qn(t,e){let n=$e,o=N(e*e*e,n),r=N(o*o*e,n),s=ca(t*r).pow_p_5_8,i=N(t*o*s,n),a=N(e*i*i,n),l=i,c=N(i*Wn,n),u=a===t,d=a===N(-t,n),p=a===N(-t*Wn,n);return u&&(i=l),(d||p)&&(i=c),me(i,n)&&(i=N(-i,n)),{isValid:u||d,value:i}}var Te=Jr(Xn,{uvRatio:Qn}),Se=Te.Fp,Qr=Te.Fn;function ua(t){return Gr(Te,It,Object.assign({adjustScalarBytes:la,zip215:true},t))}var es=ua({});var Zn=Wn;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var pa=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var Yr=t=>Qn(he,t),ha=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Yn=t=>Se.create(fe(t)&ha);var Ee=class t extends Ft{static BASE=new t(Te.BASE);static ZERO=new t(Te.ZERO);static Fp=Se;static Fn=Qr;constructor(e){super(e);}static fromAffine(e){return new t(Te.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoPoint expected")}init(e){return new t(e)}static fromBytes(e){ee(e,32);let{a:n,d:o}=Xn,r=$e,s=E=>Se.create(E),i=Yn(e);if(!Rr(Se.toBytes(i),e)||me(i,r))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),l=s(he+n*a),c=s(he-n*a),u=s(l*l),d=s(c*c),p=s(n*o*u-d),{isValid:f,value:m}=Yr(s(p*d)),h=s(m*c),g=s(m*h*p),x=s((i+i)*h);me(x,r)&&(x=s(-x));let b=s(l*g),y=s(x*b);if(!f||me(y,r)||b===sa)throw new Error("invalid ristretto255 encoding 2");return new t(new Te(x,b,he,y))}static fromHex(e){return t.fromBytes(et(e))}toBytes(){let{X:e,Y:n,Z:o,T:r}=this.ep,s=$e,i=g=>Se.create(g),a=i(i(o+n)*i(o-n)),l=i(e*n),c=i(l*l),{value:u}=Yr(i(a*c)),d=i(u*a),p=i(u*l),f=i(d*p*r),m;if(me(r*f,s)){let g=i(n*Zn),x=i(e*Zn);e=g,n=x,m=i(d*pa);}else m=p;me(e*f,s)&&(n=i(-n));let h=i((o-n)*m);return me(h,s)&&(h=i(-h)),Se.toBytes(h)}equals(e){this.assertSame(e);let{X:n,Y:o}=this.ep,{X:r,Y:s}=e.ep,i=c=>Se.create(c),a=i(n*s)===i(o*r),l=i(o*s)===i(n*r);return a||l}is0(){return this.equals(t.ZERO)}};Object.freeze(Ee.BASE);Object.freeze(Ee.ZERO);Object.freeze(Ee.prototype);Object.freeze(Ee);var ts=`-----BEGIN PUBLIC KEY-----
|
|
13
13
|
MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
|
|
14
|
-
-----END PUBLIC KEY-----`;function Ao(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 Mn(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4?"=".repeat(4-e.length%4):"";return Ao(e+n)}function Pi(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Ao(e);return n.subarray(n.length-32)}var Bi=new TextEncoder,Lo=new TextDecoder;function Mi(t){return typeof t=="object"&&t!==null&&"keys"in t}function jn(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(Lo.decode(Mn(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let c;if(Mi(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}"`};c=d;}else {if(!e)return {ok:false,reason:"no verification key"};c=e;}let l;try{if(l=Pi(c),l.length!==32)return {ok:!1,reason:"invalid public key"}}catch{return {ok:false,reason:"invalid public key"}}let a=false;try{a=Oo.verify(Mn(s),Bi.encode(`${r}.${o}`),l);}catch{return {ok:false,reason:"signature verification error"}}return a?{ok:true,header:i,payloadBytes:Mn(o)}:{ok:false,reason:"bad signature"}}function Me(t,e){let n=jn(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(Lo.decode(n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function Nn(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 Ql(t,e,n={}){let r=Me(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=Nn(o,s,n.revoked);return i==="revoked"?{status:i,payload:o,reason:"license revoked"}:{status:i,payload:o}}var Do="BVSALA-REVOC",ji=300,Ni=new TextDecoder;function Po(t,e,n={}){let r=a=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:a}),o=jn(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");if(o.header?.typ!==Do)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${Do})`);let s;try{s=JSON.parse(Ni.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 c=n.nowSeconds??Math.floor(Date.now()/1e3),l=n.maxSkewSeconds??ji;return s.asOf>c+l?r(`asOf too far in the future (${s.asOf} > ${c+l})`):{ok:true,seq:s.seq,asOf:s.asOf,revoked:new Set(s.revoked)}}var je=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 Lt(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),s=Me(t,e),i=s.signatureValid?s.payload:void 0,c=new Set(i?.features??[]),l=()=>{if(!i)return "invalid";let u=Nn(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),m=Math.max(n.revocation.lastContactAt,p);if(r()-m>n.maxStalenessSeconds)return "stale"}return u},a=()=>{let u=l();return u==="active"||u==="grace"};return {isEntitled:u=>a()&&c.has(u),isActive:()=>a(),status:l,refreshAfter:()=>{if(i)return Math.min(i.expires_at,r()+86400)}}}function Bo(t,e,n){return Lt(t,e,{revocation:new je,...n?{now:n}:{}})}var Ne={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Mo=3,Fi=12;function zi(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 $i=10,Dt=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??Ne.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>=$i&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!i.ok)throw new Error(`revocations HTTP ${i.status}`);let c=i.headers.get("etag"),l=await i.json();if(!l.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let a=Po(l.list,this.opts.publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??Ne.maxSkewSeconds});if(!a.ok){let d=a.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}c&&(this.lastEtag=c),this.opts.snapshot.markContact(this.now());let u=this.opts.snapshot.apply(a);this.opts.onEvent?.(u?{type:"applied",seq:a.seq,size:this.opts.snapshot.snapshot().size}:{type:"unchanged",seq:a.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()||J(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;let n=this.consecutiveFailures;if(n<Mo||(n-Mo)%Fi!==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=zi({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??Ne.floorSeconds,pollIntervalSeconds:this.opts.pollIntervalSeconds??Ne.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??Ne.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??Ne.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 Qe=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;flushing=false;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 flush(){if(this.flushing||this.buffer.length===0)return;let e=this.options.fetchImpl??globalThis.fetch;if(!e)return;this.flushing=true;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?(J(`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");}finally{this.flushing=false;}}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 Pt(){return globalThis.process}function Ui(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 Vi(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 Hi(){if(Pt()?.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 qi(t,e=Hi){if(t.KUBERNETES_SERVICE_HOST||Vi(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||Ui(n)))return n}async function Ki(){let t=Pt();if(!t||!t.env)return;let e=t.env,n=await qi(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 Ji=["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 Fn(){let t=Pt()?.env;if(!t)return false;for(let e of Ji){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function Gi(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"]),c=await n.subtle.sign("HMAC",i,r.encode(e));return [...new Uint8Array(c)].map(l=>l.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 zn(t){let n=Pt()?.env?.BVSALA_SEAT_ID;if(n&&Wi.test(n))return n;let r=await Ki();if(!r)return;let o=await Gi(t,r);if(o)return `m-${o.slice(0,32)}`}var Wi=/^[A-Za-z0-9._:/-]{1,128}$/;var jo={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function No(t){return {exactCache:t.exactCache??new ot,semanticCache:t.semanticCache,singleflight:t.singleflight??new st,resolvers:t.resolvers??pr(),router:t.router??new it,toolSelector:t.toolSelector??new at,formatSelector:t.formatSelector??new dt({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new ft,constraintBackends:t.constraintBackends??[]}}var Zi=36e5,Yi=7*86400,Xi=3e4,Bt=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??Zi,this.refreshLeadSeconds=e.refreshLeadSeconds??Yi;let n=Me(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??Xi);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=Me(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 $n={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},Un={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25};var Fo={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function Mt(t,e,n,r){let o=r.minimumCacheTokens;if(o==null||t<o)return t;let s=Math.min(e,t),i=t-s,c=Math.min(1,Math.max(0,n)),l=c*s*r.cacheReadMultiplier+(1-c)*s*r.cacheWriteMultiplier;return i+l}function Vn(t){let e=Mt(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=Mt(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,c;if(r<=0){let l=e<t.originalTokens;c=i?`compressing drops the prompt out of the cacheable tier (${t.compressedTokens} < ${o}) and costs more than it saves`:l?`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?c=`pays off even after losing the prefix cache (${(t.prefixHitRate*100).toFixed(0)}% hit rate)`:c="pays off and does not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:c}}function zo(t){let e=o=>Vn({...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 Qi(t){let e=zo({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(Mt(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.totalTokens?null:1)}var jt=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=Qi(n),o=this.estados.get(e),s=ea(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 ${Fe(s)} did not reach the ${Fe(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 ${Fe(s)} beats the ${Fe(r)} break-even`,umbral:r,observada:s}:(o.apagada=true,{marcar:false,razon:`prefix-cache marking OFF: measured hit rate ${Fe(s)} did not reach the ${Fe(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 ea(t){if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function Fe(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var Nt=16,$o=64,ta=8;function Uo(t,e,n={}){let r=n.minimumSavingsTokens??ta,o;try{if(Kn(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};o=Gn(t,0);}catch(b){return {applied:false,reason:b instanceof RangeError?"schema too deep or cyclic":"schema could not be compacted"}}if(o.renamed===0&&o.coded===0)return {applied:false,reason:"nothing to compact (no renameable keys, no codeable enums)"};let s=o.node;if(!s)return {applied:false,reason:"nothing to compact"};let i=b=>ze(b,s,true),c=b=>ze(b,s,false),l=aa(t),a=na(t,o.compact,s,l);if(!a.ok)return {applied:false,reason:a.reason};let u=e(JSON.stringify(t)),d=e(JSON.stringify(o.compact)),p=d-u,m=Number.POSITIVE_INFINITY;for(let b of l){let h=e(JSON.stringify(b))-e(JSON.stringify(i(b)));h<m&&(m=h);}Number.isFinite(m)||(m=0);let f=m-p;return f<r?{applied:false,reason:`net saving ${f} tokens is below the ${r}-token floor (output ${m}, schema ${p>0?"+":""}${p})`}:{applied:true,reason:`output ${m} tokens, schema ${p>0?"+":""}${p}, net ${f}`,plan:{compactSchema:o.compact,expand:c,compact:i,renamedKeys:o.renamed,codedEnumValues:o.coded,schemaTokensOriginal:u,schemaTokensCompact:d,modelledOutputSavingTokens:m}}}function na(t,e,n,r){for(let o of r){if(!pe(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let s=ze(o,n,true);if(!pe(s,e).valid)return {ok:false,reason:"compact witness does not validate against the compact schema"};if(!Jn(ze(s,n,false),o))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function Vo(t){return t.type==="object"||t.type==null&&t.properties!=null}function Ho(t){return t.type==="array"||t.type==null&&t.items!=null}function ra(t){let e=t.enum;return !e||e.length===0||e.length>$o||!e.every(n=>typeof n=="string")?null:e}function Gn(t,e){if(e>Nt)throw new RangeError("schema too deep");let n=ra(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=qo(n,true);if(!r)return {compact:t,renamed:0,coded:0};let o=[...r].filter(([i,c])=>i!==c).length;if(o===0)return {compact:t,renamed:0,coded:0};let s=new Map;for(let[i,c]of r)s.set(c,i);return {compact:{...t,enum:n.map(i=>r.get(i))},node:{enumFwd:r,enumBack:s},renamed:0,coded:o}}return Vo(t)?oa(t,e):Ho(t)?sa(t,e):{compact:t,renamed:0,coded:0}}function oa(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,m]of n){let f=Gn(m,e+1);i.set(p,f.compact),f.node&&s.set(p,f.node),r+=f.renamed,o+=f.coded;}let c=null;t.additionalProperties===false&&(c=qo(n.map(([p])=>p),false));let l={};for(let[p]of n)l[c?.get(p)??p]=i.get(p);let a={...t,properties:l};t.required&&(a.required=t.required.map(p=>c?.get(p)??p));let u={};if(c){let p=new Map;for(let[f,b]of c)p.set(b,f);let m=false;for(let[f,b]of c)f!==b&&(m=true);if(m){u.keysFwd=c,u.keysBack=p;for(let[f,b]of c)f!==b&&(r+=1);}}s.size>0&&(u.props=s);let d=!u.keysFwd&&!u.props;return {compact:a,...d?{}:{node:u},renamed:r,coded:o}}function sa(t,e){if(!t.items)return {compact:t,renamed:0,coded:0};let n=Gn(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function qo(t,e){let n=[...t].sort(),r=new Set,o=new Map;n.forEach((i,c)=>{let l=e?i.toUpperCase():i,a=i;for(let u=1;u<i.length;u++){let d=l.slice(0,u);if(!r.has(d)){a=d;break}}if(a===i){let u=c.toString(36);u.length<i.length&&!r.has(u)&&(a=u);}r.add(a),o.set(i,a);});let s=new Set(t);for(let[i,c]of o)if(c!==i&&s.has(c))return null;return o}function ze(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=>ze(s,e.items,n));let o=n?e.keysFwd:e.keysBack;if((o||e.props)&&ia(t)){let s={};for(let[i,c]of Object.entries(t)){let l=o?.get(i)??i,a=n?i:l,u=e.props?.get(a);s[l]=u?ze(c,u,n):c;}return s}return t}function ia(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function aa(t){let e=Math.min($o,Math.max(1,Hn(t,0))),n=[];for(let r=0;r<e;r++)n.push(qn(t,r,0));return n}function Hn(t,e){if(e>Nt)return 0;let n=t.enum?.length??0;for(let r of Object.values(t.properties??{}))n=Math.max(n,Hn(r,e+1));return t.items&&(n=Math.max(n,Hn(t.items,e+1))),n}function qn(t,e,n){if(n>Nt)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(Vo(t)){let r={};for(let[o,s]of Object.entries(t.properties??{}))r[o]=qn(s,e,n+1);return r}if(Ho(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?qn(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 Kn(t,e){if(e>Nt)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.values(t.properties??{}))if(Kn(n,e+1))return true;return !!(t.items&&Kn(t.items,e+1))}function Jn(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(!Jn(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)||!Jn(t[i],e[i]))return false;return true}function Wn(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"?$n:o==="anthropic"?Un:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(s)?$n:s.startsWith("claude")?Un:Fo}function Ko(t){let e=t.prefix!=null,n=Vn({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 Go(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,c=r,l=i>0&&i>=c,a;return i<=0?a=`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`:l?a=`se evitan ${t.esquemasCompletos-t.esquemasDeLaSegunda} tokens de esquema en el peor caso, bastante para pagar el prompt repetido y el sondeo`:a="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:l,costeDeUnaLlamada:o,costeDeDosLlamadas:s,ganancia:i,perdidaSiDegrada:c,razon:a}}function Wo(t){let n=(t.description??t.intents.join("; ")).trim().split(/\r?\n/,1)[0]??"",r=n.length>Jo?n.slice(0,Jo-1).trimEnd()+"\u2026":n;return {id:t.id,intents:t.intents,risk:t.risk,...r?{description:r}:{}}}var Jo=200;function Zo(t,e,n){let r=new Map(e.map(l=>[l.id,l])),o=[],s=[],i=new Set;for(let l of t){let a=r.get(l);if(!a){s.push(l);continue}o.includes(a.id)||(o.push(a.id),a.risk==="read"&&i.size<Math.max(0,n)&&i.add(a.id));}return {tools:e.filter(l=>l.risk!=="read"||i.has(l.id)),reconocidos:o,ignorados:s}}function Yo(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 ts=new WeakSet;function ca(t){typeof t=="object"&&t!==null&&ts.add(t);}function la(t){return typeof t=="object"&&t!==null&&ts.has(t)}function ua(t){switch(t){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";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";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.";case "expired":case "grace":return `BiVelio license is not active (${t}). Renew your subscription at https://savings.bivelio.com`;default:return `BiVelio license is not active${t?` (${t})`:""}. See https://savings.bivelio.com/dashboard/account`}}var $t=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new jt;constructor(e){this.config=e,this.deps=No(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>qt()),this.contratosQueIncumplen=e.constraintMemory??new Set;}async generate(e){this.assertLicensed();let n={llamadas:0,falloDelProveedor:false};try{return await this.generateOptimized(e,n)}catch(r){if(r instanceof Te||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||la(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){let c={marcar:false,huella:"",mensajesDePrefijo:0},l=ma(e.model,this.config.compressionEconomics);if(!l)return i.record("prefix-cache","skipped",{reason:`no cache read discount for model "${e.model}" (unrecognised provider, or a declared tier that does not discount reads): not claiming a cacheable prefix`}),c;if(!r.setIsStable)return i.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(o)return i.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(s<=0)return c;let a=n.slice(0,s),u=this.tokensFor(this.assemblePromptText(a,r.tools),e),d=this.tokensFor(this.assemblePromptText(n,r.tools),e),p=fe(we({model:e.model,tools:(r.tools??[]).map(f=>f.id),prefijo:a.map(f=>`${f.role}:${f.content}`)})),m=this.verjaDeCache.decidir(p,{totalTokens:d,stablePrefixTokens:u,tier:l});return i.record("prefix-cache",m.marcar?"marked":"skipped",{reason:m.razon,stablePrefixTokens:u,breakEvenHitRate:m.umbral,observedHitRate:m.observada}),m.marcar?{marcar:true,huella:p,mensajesDePrefijo:s}:c}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 Te(ua(n),n)}throw e?new Te("licenseGate must implement isActive(). A gate without it cannot prove the licence is live, so the pipeline refuses to run. Pass { licenseKey } for enforced licensing, or { devUnlicensed: true } for local development.","invalid"):new Te("No BiVelio license configured. Pass { licenseKey } from your subscription (or { devUnlicensed: true } for local dev). Get a key at https://savings.bivelio.com")}avisar(e,n){this.config.silenceWarnings||J(e,n);}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 Ke(this.now),o=new Le,s=Yt(e),i=Xt(s),c=e.savings??{};this.avisarDePalancasSinConfigurar(c);let l=this.costModelFor(e.model);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 a=this.tokensFor(this.assembleBaselinePrompt(e),e),u=e.response?.maxOutputTokens??256;if(o.baselineInput=a,o.baselineOutput=u,o.baselineTools=e.tools?.length??0,c.deterministicResolvers!==false){let f=this.deps.resolvers.try(s);if(f)return o.avoidCall(a,this.tokensFor(f.text,e)),r.record("resolver",f.resolver,{avoided:true}),this.finish(e,s,{text:f.text,data:f.data,storedAtMs:this.now()},"deterministic",o,l,r,et(),tt())}let d=ar(s);if(i.allowExactCache&&c.exactCache!==false){let f=await this.deps.exactCache.get(d);if(f)return o.avoidCall(a,this.tokensFor(f.text,e)),r.record("exact-cache","hit",{ageMs:this.now()-f.storedAtMs}),this.finish(e,s,f,"exact",o,l,r,et(),tt(),this.now()-f.storedAtMs);r.record("exact-cache","miss");}let p=cr(s),m=async()=>{try{return await this.expensivePath(n,e,s,i,c,o,l,r,d,a)}catch(f){throw (n.falloDelProveedor||n.llamadas>0)&&ca(f),f}};if(i.allowSingleflight&&c.singleflight!==false){let{value:f,coalesced:b}=await this.deps.singleflight.run(p,m);return b?(r.record("singleflight","coalesced",{key:p}),this.asCoalescedFollower(f,a,this.tokensFor(f.text??"",e),l)):f}return m()}async expensivePath(e,n,r,o,s,i,c,l,a,u){let d=this.entitled("semantic_cache");if(o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&!d&&l.record("semantic-cache","degraded: feature not licensed (free tier)"),o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&d){let w=await this.deps.semanticCache.find(r);if(w)return i.avoidCall(u,this.tokensFor(w.record.answer.text,n)),l.record("semantic-cache","hit",{confidence:w.confidence,similarity:w.similarity}),this.finish(n,r,w.record.answer,"semantic",i,c,l,et(),tt(),w.ageMs,w.confidence);l.record("semantic-cache","miss");}let p=s.router===false,m=p?et():this.deps.router.classify(r);l.record("router",m.executionClass,{confidence:m.confidence,reason:m.reason});let f=p?this.deps.toolSelector.passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,m.executionClass);if(i.actualTools=f.tools.length,f.droppedIds.length){let w=new Set(f.droppedIds),L=(n.tools??[]).filter(U=>w.has(U.id)).reduce((U,te)=>U+this.tokensFor(Zn(te),n),0);i.eliminate(L),l.record("tool-selector",f.reason,{dropped:f.droppedIds,eliminatedTokens:L});}i.baselineRetrieval=m.rounds;let b=await hr({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=b.rounds,b.retrievedCount>0&&l.record("retrieval",`kept ${b.keptCount}/${b.retrievedCount}`,{rounds:b.rounds});let h=tt(),g=[...n.messages],x=Xn(n.messages),y=false,T=b.docs.length>0?{role:"system",content:`Retrieved context \u2014 answer using only this evidence and cite sources by [id]:
|
|
14
|
+
-----END PUBLIC KEY-----`;function ns(t){let e=atob(t),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n}function eo(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4?"=".repeat(4-e.length%4):"";return ns(e+n)}function ba(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=ns(e);return n.subarray(n.length-32)}var xa=new TextEncoder,os=new TextDecoder;function ya(t){return typeof t=="object"&&t!==null&&"keys"in t}function to(t,e){let n=t.split(".");if(n.length!==3)return {ok:false,reason:"malformed token"};let o=n[0],r=n[1],s=n[2],i;try{i=JSON.parse(os.decode(eo(o)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(ya(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 l;try{if(l=ba(a),l.length!==32)return {ok:!1,reason:"invalid public key"}}catch{return {ok:false,reason:"invalid public key"}}let c=false;try{c=es.verify(eo(s),xa.encode(`${o}.${r}`),l);}catch{return {ok:false,reason:"signature verification error"}}return c?{ok:true,header:i,payloadBytes:eo(r)}:{ok:false,reason:"bad signature"}}function Fe(t,e){let n=to(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(os.decode(n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function no(t,e,n){if(n?.has(t.jti))return "revoked";let o=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"active":e<=o?"grace":"expired"}function rd(t,e,n={}){let o=Fe(t,e);if(!o.signatureValid||!o.payload)return {status:"invalid",...o.reason?{reason:o.reason}:{}};let r=o.payload,s=n.nowSeconds??Math.floor(Date.now()/1e3),i=no(r,s,n.revoked);return i==="revoked"?{status:i,payload:r,reason:"license revoked"}:{status:i,payload:r}}var rs="BVSALA-REVOC",va=300,ka=new TextDecoder;function ss(t,e,n={}){let o=c=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:c}),r=to(t,e);if(!r.ok||!r.payloadBytes)return o(r.reason??"bad signature");if(r.header?.typ!==rs)return o(`unexpected token type "${String(r.header?.typ??"")}" (want ${rs})`);let s;try{s=JSON.parse(ka.decode(r.payloadBytes));}catch{return o("payload is not valid JSON")}if(typeof s.seq!="number"||typeof s.asOf!="number"||!Array.isArray(s.revoked))return o("malformed revocation payload");let i=n.minSeq??0;if(s.seq<i)return o(`stale/rolled-back list (seq ${s.seq} < ${i})`);let a=n.nowSeconds??Math.floor(Date.now()/1e3),l=n.maxSkewSeconds??va;return s.asOf>a+l?o(`asOf too far in the future (${s.asOf} > ${a+l})`):{ok:true,seq:s.seq,asOf:s.asOf,revoked:new Set(s.revoked)}}var ze=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 o=this.set.size>n,r=e.seq>this._seq;return e.seq>this._seq&&(this._seq=e.seq),e.asOf>this._asOf&&(this._asOf=e.asOf),o||r}};function zt(t,e,n){let o=()=>Math.floor((n.now?n.now():Date.now())/1e3),r=n.startedAt??o(),s=Fe(t,e),i=s.signatureValid?s.payload:void 0,a=new Set(i?.features??[]),l=()=>{if(!i)return "invalid";let u=no(i,o(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(u==="active"||u==="grace")){let d=i.expires_at+i.grace_days*86400,p=Math.min(r,d),f=Math.max(n.revocation.lastContactAt,p);if(o()-f>n.maxStalenessSeconds)return "stale"}return u},c=()=>{let u=l();return u==="active"||u==="grace"};return {isEntitled:u=>c()&&a.has(u),isActive:()=>c(),status:l,refreshAfter:()=>{if(i)return Math.min(i.expires_at,o()+86400)}}}function is(t,e,n){return zt(t,e,{revocation:new ze,...n?{now:n}:{}})}var Ve={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},as=3,wa=12;function Sa(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>0){let r=Math.pow(2,Math.min(t.consecutiveFailures,4));n=Math.min(t.maxIntervalSeconds,t.floorSeconds*r);}else {let r=t.refreshAfter!=null?t.refreshAfter-t.nowSeconds:t.pollIntervalSeconds,s=r<0?t.pollIntervalSeconds:r;n=Math.min(t.pollIntervalSeconds,Math.max(t.floorSeconds,s));}let o=1+(e()*2-1)*t.jitterRatio;return Math.max(t.floorSeconds,n*o)}var Ta=10,Vt=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 o=this.opts.requestTimeoutMs??Ve.requestTimeoutMs,r=setTimeout(()=>n.abort(),o);r.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>=Ta&&(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"),l=await i.json();if(!l.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let c=ss(l.list,this.opts.publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??Ve.maxSkewSeconds});if(!c.ok){let d=c.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(c);this.opts.onEvent?.(u?{type:"applied",seq:c.seq,size:this.opts.snapshot.snapshot().size}:{type:"unchanged",seq:c.seq});}catch(i){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:i}),this.avisarFalloDeRed(i);}finally{clearTimeout(r),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;let n=this.consecutiveFailures;if(n<as||(n-as)%wa!==0)return;let o=e instanceof Error?e.message:String(e);console.warn(`[bv-sala] no se ha podido contactar con el servidor de revocaciones ${n} veces seguidas (${o}). La licencia SIGUE funcionando y las revocaciones ya conocidas se siguen aplicando, pero las NUEVAS no est\xE1n llegando. Compruebe la salida hacia ${this.opts.url}.`);}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)return;let e=Sa({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??Ve.floorSeconds,pollIntervalSeconds:this.opts.pollIntervalSeconds??Ve.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??Ve.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??Ve.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 st=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;flushing=false;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 flush(){if(this.flushing||this.buffer.length===0)return;let e=this.options.fetchImpl??globalThis.fetch;if(!e)return;this.flushing=true;let n=this.buffer.splice(0,this.maxBatch);try{let o=n.map(s=>this.toWire(s)),r=await e(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.options.serviceAccountKey}`},body:JSON.stringify(o)});r.ok?this.fallosSeguidos=0:r.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(`el servidor respondi\xF3 ${r.status}`)):r.status===401||r.status===403?(G(`metering-auth-${r.status}`,`[bv-sala] el env\xEDo de uso est\xE1 siendo rechazado con HTTP ${r.status} en ${this.options.url}. 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?.(r.status)):(this.fallosSeguidos++,this.avisarDeFallo(r.status===404||r.status===405?`HTTP ${r.status}: la URL de env\xEDo parece equivocada`:`el servidor rechaz\xF3 el lote con HTTP ${r.status}`));}catch(o){this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(o instanceof Error?o.message:"error de red");}finally{this.flushing=false;}}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 Ut(){return globalThis.process}function Ea(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 Ra(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 Ca(){if(Ut()?.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 Oa(t,e=Ca){if(t.KUBERNETES_SERVICE_HOST||Ra(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||Ea(n)))return n}async function Ia(){let t=Ut();if(!t||!t.env)return;let e=t.env,n=await Oa(e),o=[t.platform,t.arch,t.execPath,n,e.USER??e.USERNAME??e.LOGNAME,e.HOME??e.USERPROFILE].filter(r=>typeof r=="string"&&r.length>0);return o.length?o.join("|"):void 0}var _a=["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 oo(){let t=Ut()?.env;if(!t)return false;for(let e of _a){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function Da(t,e){let n=globalThis.crypto,o=new TextEncoder;if(n?.subtle)try{let i=await n.subtle.importKey("raw",o.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",i,o.encode(e));return [...new Uint8Array(a)].map(l=>l.toString(16).padStart(2,"0")).join("")}catch{}let r=2166136261,s=`${t}|${e}`;for(let i=0;i<s.length;i++)r^=s.charCodeAt(i),r=Math.imul(r,16777619);return (r>>>0).toString(16).padStart(8,"0")}async function ro(t){let n=Ut()?.env?.BVSALA_SEAT_ID;if(n&&Aa.test(n))return n;let o=await Ia();if(!o)return;let r=await Da(t,o);if(r)return `m-${r.slice(0,32)}`}var Aa=/^[A-Za-z0-9._:/-]{1,128}$/;var cs={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function ls(t){return {exactCache:t.exactCache??new ft,semanticCache:t.semanticCache,singleflight:t.singleflight??new mt,resolvers:t.resolvers??Po(),router:t.router??new ht,toolSelector:t.toolSelector??new gt,formatSelector:t.formatSelector??new vt({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new kt,constraintBackends:t.constraintBackends??[]}}var La=36e5,Ma=7*86400,Pa=3e4,qt=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??La,this.refreshLeadSeconds=e.refreshLeadSeconds??Ma;let n=Fe(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??Pa);n.unref?.();try{let r=await(this.opts.fetchImpl??globalThis.fetch.bind(globalThis))(this.opts.url,{signal:e.signal,headers:{authorization:`Bearer ${this.opts.serviceAccountKey}`,accept:"application/json"}});if(!r.ok)return (r.status===401||r.status===403||r.status===404)&&!this.avisadoDeCredencial&&(this.avisadoDeCredencial=!0,console.warn(`[bv-sala] la recogida autom\xE1tica de la licencia renovada falla con HTTP ${r.status} en ${this.opts.url}. Revisa 'serviceAccountKey' (\xBFrotada? \xBFde otra organizaci\xF3n?) y 'licenseServerUrl': mientras no funcione, el token NO se renovar\xE1 solo y el SDK dejar\xE1 de operar al terminar el periodo de gracia.`)),!1;let s=await r.json();if(typeof s.token!="string")return !1;let i=Fe(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 so={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},io={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25};var us={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function Ht(t,e,n,o){let r=o.minimumCacheTokens;if(r==null||t<r)return t;let s=Math.min(e,t),i=t-s,a=Math.min(1,Math.max(0,n)),l=a*s*o.cacheReadMultiplier+(1-a)*s*o.cacheWriteMultiplier;return i+l}function ao(t){let e=Ht(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=Ht(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??0),o=e-n,r=t.tier.minimumCacheTokens,i=r!=null&&t.originalTokens>=r&&t.compressedTokens<r,a;if(o<=0){let l=e<t.originalTokens;a=i?`compressing drops the prompt out of the cacheable tier (${t.compressedTokens} < ${r}) and costs more than it saves`:l?`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:o>0,costeComprimido:n,costeSinComprimir:e,ganancia:o,razon:a}}function ds(t){let e=r=>ao({...t,prefixHitRate:r}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,o=1;for(let r=0;r<40;r++){let s=(n+o)/2;e(s)>0?n=s:o=s;}return (n+o)/2}function Ba(t){let e=ds({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(Ht(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.totalTokens?null:1)}var Kt=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 o=Ba(n),r=this.estados.get(e),s=ja(r);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:o,observada:s}:o==null?{marcar:true,razon:"marking cannot lose money at this tier (no write premium)",umbral:o,observada:s}:r?.apagada?{marcar:false,razon:`prefix-cache marking OFF: measured hit rate ${Ue(s)} did not reach the ${Ue(o)} break-even, so marking was costing money`,umbral:o,observada:s}:r==null||r.marcadas<this.exploracion?{marcar:true,razon:`exploring the prefix cache (${r?.marcadas??0}/${this.exploracion}); hit rate is only observable on requests that were marked`,umbral:o,observada:s}:s!=null&&s>o?{marcar:true,razon:`measured hit rate ${Ue(s)} beats the ${Ue(o)} break-even`,umbral:o,observada:s}:(r.apagada=true,{marcar:false,razon:`prefix-cache marking OFF: measured hit rate ${Ue(s)} did not reach the ${Ue(o)} break-even, so marking was costing money`,umbral:o,observada:s})}registrar(e,n){let o=this.estados.get(e)??{marcadas:0,tokensLeidos:0,tokensEscritos:0,apagada:false};o.marcadas+=1,o.tokensLeidos+=Math.max(0,n.cachedInputTokens??0),o.tokensEscritos+=Math.max(0,n.cacheWriteInputTokens??0),this.estados.set(e,o);}};function ja(t){if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function Ue(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var ps=.5;function Na(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function $a(t){return 1-t}function Fa(t,e=ps){return e-t}function fs(t,e,n=ps){if(!t||!e)return null;let o=Na(t,e);if(o==null||!Number.isFinite(o))return null;let r=$a(o),s=Fa(o,n),i=s>0,a=l=>`${(l*100).toFixed(1)}%`;return {r:o,equilibrio:r,escaladoMaximo:s,viable:i,razon:i?`the cheap model costs ${a(o)} of the strong one, so routing pays off while escalations stay under ${a(s)} (it stops saving money at ${a(r)})`:`the cheap model costs ${a(o)} of the strong one: even with zero escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var co={"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 za(t){return Object.keys(t).sort((e,n)=>n.length-e.length||e.localeCompare(n))}function ms(t,e=co){if(!t)return null;let n=t.lastIndexOf("/"),o=n>=0?t.slice(0,n+1):"",r=n>=0?t.slice(n+1):t,s=e[t]??e[r]??Va(r,e);return !s||s===r?null:o+s}function Va(t,e){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 Jt=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 o=this.estados.get(e),r=Ua(o),s=o?.enrutadas??0,i=a=>a==null?"n/a":`${(a*100).toFixed(1)}%`;return o?.apagada?{enrutar:false,razon:`model cascade OFF for this workload: measured escalation rate ${i(r)} is at or above the ${i(n.equilibrio)} break-even, so routing was costing money`,observada:r,muestras:s}:s<this.exploracion?{enrutar:true,razon:`measuring this workload (${s}/${this.exploracion}); the escalation rate is only observable on requests that were actually routed`,observada:r,muestras:s}:r!=null&&r<n.equilibrio?{enrutar:true,razon:`measured escalation rate ${i(r)} stays under the ${i(n.equilibrio)} break-even (this is a MONEY check, not a quality one)`,observada:r,muestras:s}:(o&&(o.apagada=true),{enrutar:false,razon:`model cascade OFF for this workload: measured escalation rate ${i(r)} is at or above the ${i(n.equilibrio)} break-even, so routing was costing money`,observada:r,muestras:s})}registrar(e,n){let o=this.estados.get(e)??{enrutadas:0,escaladas:0,apagada:false};o.enrutadas+=1,n&&(o.escaladas+=1),this.estados.set(e,o);}};function Ua(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var qa=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function Ha(t){return t?lo(t)?"value-constrained":"structural":"none"}function lo(t,e=0){if(e>12)return false;let n=t;for(let o of qa)if(n[o]!==void 0)return true;if(t.properties){for(let o of Object.values(t.properties))if(lo(o,e+1))return true}return !!(t.items&&lo(t.items,e+1))}function hs(t){let e=Ha(t.schema),n=(t.tools??[]).filter(o=>o.risk==="write"||o.risk==="destructive");return n.length>0?{elegible:false,fuerza:e,razon:`the request carries ${n.length} write/destructive tool(s); a cheaper model's choice of ACTION 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 uo(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 o=se(n,t.schema);return o.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 (${o.errors.slice(0,3).map(s=>`${s.path}: ${s.message}`).join("; ")})`,comprobaciones:e}}function gs(t,e){let n,o;try{n=JSON.parse(t),o=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let r=Gt(n),s=Gt(o);return r.length===0&&s.length===0?{divergen:false,motivo:"no comparable facts (free prose only)"}:Ja(r,s)?{divergen:false,motivo:"the hard values agree"}:{divergen:true,motivo:"both answers satisfy the contract but disagree on at least one hard value; this is the signature of a false valid \u2014 it is a reason to look, never a verdict"}}var Ka=40;function Gt(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 o=t.trim();o.length>0&&o.length<=Ka&&n.push(`s:${o.toLowerCase()}`);}else if(Array.isArray(t))for(let o of t)Gt(o,e+1,n);else if(t&&typeof t=="object")for(let o of Object.keys(t).sort())Gt(t[o],e+1,n);return n.sort()}function Ja(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 bs="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 Ga(t){if(t<=0)return "";let e=bs;for(;e.length<t;)e+=bs;return e.slice(0,t)}function Wa(t){let e=t[0],n=-1;for(let o of t){let r=JSON.stringify(o)?.length??0;r>n&&(n=r,e=o);}return e}function po(t){if(t.enum&&t.enum.length>0)return {valor:Wa(t.enum)};switch(t.type??(t.properties?"object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:Ga(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=po(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[o,r]of Object.entries(t.properties)){let s=po(r);if(!s)return;n[o]=s.valor;}return {valor:n}}default:return}}function Za(t){let e=po(t);return e?JSON.stringify(e.valor):null}function xs(t,e){let n=Za(t);return n===null?null:e(n)}var Wt=16,ys=64,Ya=8,Xa="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 vs(t,e,n,o={}){let r=o.minimumSavingsTokens??Ya,s;try{if(ho(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};s=bo(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=>qe(S,i,true),l=S=>qe(S,i,false),c=rc(t),u=Qa(t,s.compact,i,c);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 c){let M=e(JSON.stringify(S))-e(JSON.stringify(a(S)));M<m&&(m=M);}Number.isFinite(m)||(m=0);let h=S=>S/1e3*n.inputPer1k,g=S=>S/1e3*n.outputPer1k,x=h(r),b=n.outputPer1k>0?(r-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=o.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: ${Xa}. 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 I=C.deltaTokens;if(I<0)return {applied:false,reason:`the measured output delta is ${I} 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=h(f)+g(I),D=n.inputPer1k>0?T*1e3/n.inputPer1k:f,R=`+${I} tokens (${I>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 ${r} 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:l,compact:a,renamedKeys:s.renamed,codedEnumValues:s.coded,schemaTokensOriginal:d,schemaTokensCompact:p,modelledShapeSavingTokens:m,measuredOutputDeltaTokens:I,outputDeltaProvenance:C.procedencia,breakEvenOutputDeltaTokens:b,netSavingUsd:T}}}function Qa(t,e,n,o){for(let r of o){if(!se(r,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let s=qe(r,n,true);if(!se(s,e).valid)return {ok:false,reason:"compact witness does not validate against the compact schema"};if(!go(qe(s,n,false),r))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function ks(t){return t.type==="object"||t.type==null&&t.properties!=null}function ws(t){return t.type==="array"||t.type==null&&t.items!=null}function ec(t){let e=t.enum;return !e||e.length===0||e.length>ys||!e.every(n=>typeof n=="string")?null:e}function bo(t,e){if(e>Wt)throw new RangeError("schema too deep");let n=ec(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let o=Ss(n,true);if(!o)return {compact:t,renamed:0,coded:0};let r=[...o].filter(([i,a])=>i!==a).length;if(r===0)return {compact:t,renamed:0,coded:0};let s=new Map;for(let[i,a]of o)s.set(a,i);return {compact:{...t,enum:n.map(i=>o.get(i))},node:{enumFwd:o,enumBack:s},renamed:0,coded:r}}return ks(t)?tc(t,e):ws(t)?nc(t,e):{compact:t,renamed:0,coded:0}}function tc(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};let o=0,r=0,s=new Map,i=new Map;for(let[p,f]of n){let m=bo(f,e+1);i.set(p,m.compact),m.node&&s.set(p,m.node),o+=m.renamed,r+=m.coded;}let a=null;t.additionalProperties===false&&(a=Ss(n.map(([p])=>p),false));let l={};for(let[p]of n)l[a?.get(p)??p]=i.get(p);let c={...t,properties:l};t.required&&(c.required=t.required.map(p=>a?.get(p)??p));let u={};if(a){let p=new Map;for(let[m,h]of a)p.set(h,m);let f=false;for(let[m,h]of a)m!==h&&(f=true);if(f){u.keysFwd=a,u.keysBack=p;for(let[m,h]of a)m!==h&&(o+=1);}}s.size>0&&(u.props=s);let d=!u.keysFwd&&!u.props;return {compact:c,...d?{}:{node:u},renamed:o,coded:r}}function nc(t,e){if(!t.items)return {compact:t,renamed:0,coded:0};let n=bo(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function Ss(t,e){let n=[...t].sort(),o=new Set,r=new Map;n.forEach((i,a)=>{let l=e?i.toUpperCase():i,c=i;for(let u=1;u<i.length;u++){let d=l.slice(0,u);if(!o.has(d)){c=d;break}}if(c===i){let u=a.toString(36);u.length<i.length&&!o.has(u)&&(c=u);}o.add(c),r.set(i,c);});let s=new Set(t);for(let[i,a]of r)if(a!==i&&s.has(a))return null;return r}function qe(t,e,n){let o=n?e.enumFwd:e.enumBack;if(o&&typeof t=="string")return o.get(t)??t;if(e.items&&Array.isArray(t))return t.map(s=>qe(s,e.items,n));let r=n?e.keysFwd:e.keysBack;if((r||e.props)&&oc(t)){let s={};for(let[i,a]of Object.entries(t)){let l=r?.get(i)??i,c=n?i:l,u=e.props?.get(c);s[l]=u?qe(a,u,n):a;}return s}return t}function oc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function rc(t){let e=Math.min(ys,Math.max(1,fo(t,0))),n=[];for(let o=0;o<e;o++)n.push(mo(t,o,0));return n}function fo(t,e){if(e>Wt)return 0;let n=t.enum?.length??0;for(let o of Object.values(t.properties??{}))n=Math.max(n,fo(o,e+1));return t.items&&(n=Math.max(n,fo(t.items,e+1))),n}function mo(t,e,n){if(n>Wt)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(ks(t)){let o={};for(let[r,s]of Object.entries(t.properties??{}))o[r]=mo(s,e,n+1);return o}if(ws(t)){if(t.maxItems===0)return [];let o=Math.max(1,t.minItems??1),r=t.maxItems!=null?Math.min(o,t.maxItems):o,s=t.items;return Array.from({length:r},()=>s?mo(s,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";let o=Math.max(1,t.minLength??1),r=t.maxLength!=null?Math.min(o,t.maxLength):o;return "x".repeat(r)}case "number":case "integer":{let o=t.minimum??1;return t.maximum!=null&&o>t.maximum&&(o=t.maximum),t.type==="integer"?Math.round(o):o}case "boolean":return true;case "null":return null;default:return null}}function ho(t,e){if(e>Wt)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.values(t.properties??{}))if(ho(n,e+1))return true;return !!(t.items&&ho(t.items,e+1))}function go(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.isArray(t),o=Array.isArray(e);if(n||o){if(!n||!o||t.length!==e.length)return false;for(let i=0;i<t.length;i++)if(!go(t[i],e[i]))return false;return true}let r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return false;for(let i of r)if(!Object.prototype.hasOwnProperty.call(e,i)||!go(t[i],e[i]))return false;return true}var sc="2026-08-14",Ts={"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}},ic=an(Ts);function ac(t){return sn(Ts,ic,t)}var Zt=class t{deltas=new Map;static clave(e,n){return `${e}\0${n}`}recordar(e,n,o){this.deltas.set(t.clave(e,n),o);}resolver(e,n,o){if(o!=null&&Number.isFinite(o))return this.recordar(e,n,o),{deltaTokens:o,origen:"caller",procedencia:`measured by the caller for this contract on ${e}`};let r=this.deltas.get(t.clave(e,n));if(r!=null)return {deltaTokens:r,origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let s=ac(e);return s?{deltaTokens:s.deltaTokens,origen:"catalogue",procedencia:`measured by BiVelio on ${e} (${sc}, ${s.pares} paired reps, ${s.contrato}, ${s.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};function xo(t,e){if(e?.cacheTier)return e.cacheTier;let n=t.toLowerCase(),o=n.indexOf("/"),r=o>0?n.slice(0,o):"",s=o>=0?n.slice(o+1):n;return r==="openai"||r==="azure-openai"?so:r==="anthropic"?io:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(s)?so:s.startsWith("claude")?io:us}function Es(t){let e=t.prefix!=null,n=ao({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 o=t.tier.minimumCacheTokens;return o!=null&&t.originalTokens>=o&&t.compressedTokens<o?{...n,comprimir:false,razon:`compressing would drop the prompt out of the cacheable tier (${t.compressedTokens} < ${o}) and nobody has measured the prefix hit rate, so it cannot be claimed to pay for itself. Declare it in \`compressionEconomics.prefix\` to unlock the full decision`}:n}function Cs(t){let e=u=>u/1e3*t.precio.inputPer1k,n=u=>u/1e3*t.precio.outputPer1k,o=e(t.promptTokens+t.descriptoresLigeros)+n(t.salidaDelSondeo),r=e(t.promptTokens+t.esquemasCompletos)+n(t.salidaFinal),s=o+e(t.promptTokens+t.esquemasDeLaSegunda)+n(t.salidaFinal),i=r-s,a=o,l=i>0&&i>=a,c;return i<=0?c=`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`:l?c=`se evitan ${t.esquemasCompletos-t.esquemasDeLaSegunda} tokens de esquema en el peor caso, bastante para pagar el prompt repetido y el sondeo`:c="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:l,costeDeUnaLlamada:r,costeDeDosLlamadas:s,ganancia:i,perdidaSiDegrada:a,razon:c}}function Os(t){let n=(t.description??t.intents.join("; ")).trim().split(/\r?\n/,1)[0]??"",o=n.length>Rs?n.slice(0,Rs-1).trimEnd()+"\u2026":n;return {id:t.id,intents:t.intents,risk:t.risk,...o?{description:o}:{}}}var Rs=200;function Is(t,e,n){let o=new Map(e.map(l=>[l.id,l])),r=[],s=[],i=new Set;for(let l of t){let c=o.get(l);if(!c){s.push(l);continue}r.includes(c.id)||(r.push(c.id),c.risk==="read"&&i.size<Math.max(0,n)&&i.add(c.id));}return {tools:e.filter(l=>l.risk!=="read"||i.has(l.id)),reconocidos:r,ignorados:s}}function _s(t,e){let n=0,o=[];for(let r of t)r.risk==="read"?o.push(r.tokens):n+=r.tokens;o.sort((r,s)=>s-r);for(let r of o.slice(0,Math.max(0,e)))n+=r;return n}var Ms=new WeakSet;function cc(t){typeof t=="object"&&t!==null&&Ms.add(t);}function lc(t){return typeof t=="object"&&t!==null&&Ms.has(t)}function Ls(t){switch(t){case "none":return uc();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 uc(){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 dc(){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 Xt=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new Kt;verjaDeCascada;memoriaDelCodebook=new Zt;constructor(e){this.config=e,this.deps=ls(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>cn()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.verjaDeCascada=new Jt(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(o){if(o instanceof Ie||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||lc(o))throw o;return await this.failOpenDirect(e,o)}}async llamarProveedor(e,n){n.llamadas+=1;try{return await this.config.provider.generate(e)}catch(o){throw n.falloDelProveedor=true,o}}decidirMarcadoDeCache(e,n,o,r,s,i,a){let l={marcar:false,huella:"",mensajesDePrefijo:0},c=bc(n,this.config.compressionEconomics);if(!c)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`}),l;if(!r.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."}),l;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."}),l;if(i<=0)return l;let u=o.slice(0,i),d=this.tokensFor(this.assemblePromptText(u,r.tools),e),p=this.tokensFor(this.assemblePromptText(o,r.tools),e),f=re(ye({model:n,tools:(r.tools??[]).map(h=>h.id),prefijo:u.map(h=>`${h.role}:${h.content}`)})),m=this.verjaDeCache.decidir(f,{totalTokens:p,stablePrefixTokens:d,tier:c});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}:l}decidirCascada(e,n,o,r){let s=o.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=hs({schema:e.response?.schema,tools:e.tools}),l=ms(e.model,this.config.modelCascade?.pairs??co),c=this.precioConocido(e.model),u=l?this.precioConocido(l):void 0,d=fs(u,c),p=re(ye({tenant:n.tenantId,scope:n.authorizationScope,contract:n.contractId,schema:n.schemaVersion,fuerte:e.model,barato:l,tools:n.toolsetHash})),f=this.verjaDeCascada.estado(p),m={modo:s,modeloPedido:e.model,modeloServido:e.model,candidato:l,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},h=b=>(r.record("model-cascade",s==="on"?"not routed":"not eligible",{reason:b}),{...m,razon:b});if(!a.elegible)return h(a.razon);if(!l)return h(`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?[]:[l]];return h(`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 h(d.razon);let g=Math.min(1,Math.max(0,this.config.modelCascade?.shadowSampleRate??0));if(s==="shadow")return r.record("model-cascade","shadow",{candidateModel:l,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:g};let x=this.verjaDeCascada.decidir(p,d);return x.enrutar?(this.avisar(`cascada:${e.model}->${l}`,`[bv-sala] model cascade ON: requests for "${e.model}" may be answered by "${l}" 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".`),r.record("model-cascade","routed",{candidateModel:l,costRatio:d.r,breakEvenEscalationRate:d.equilibrio,observedEscalationRate:x.observada,verifier:a.fuerza,workload:p,reason:x.razon}),{...m,modeloServido:l,enruta:true,elegible:true,razon:x.razon,observada:x.observada,muestras:x.muestras,tasaDeMuestreo:0}):(r.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 Ie(Ls(n),n)}throw e?new Ie(dc(),"invalid"):new Ie(Ls("none"),"none")}avisar(e,n){this.config.silenceWarnings||G(e,n);}avisarDeTruncado(e,n,o,r,s){let i=e.response?.maxOutputTokens,a=lt(e)||"(sin contractId)",l=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.":"",c=r===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 ~${r} 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.`:r>i?` El contrato autoriza respuestas de hasta ~${r} tokens con este modelo (lo que permiten sus \`maxLength\`/\`maxItems\`) y el tope son ${i}: ninguna respuesta que use lo que el propio esquema permite cabe. Un 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 ~${r} 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\`).${l}`;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 ${o} tokens de salida, as\xED que el JSON no valida. NO se reintenta: con el mismo tope volver\xEDa a cortarse y ser\xEDa una llamada pagada para el mismo fallo.${c}`);}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 o=new Xe(this.now),r=new Pe,s=hn(e),i=bn(s),a=e.savings??{};this.avisarDePalancasSinConfigurar(a);let l=this.decidirCascada(e,s,a,o),c=this.costModelFor(l.modeloServido);o.record("canonicalize","done",{tenant:s.tenantId,contract:s.contractId}),o.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(r.baselineInput=u,r.baselineOutput=d,r.baselineTools=e.tools?.length??0,a.deterministicResolvers!==false){let h=this.deps.resolvers.try(s);if(h)return r.avoidCall(u,this.tokensFor(h.text,e)),o.record("resolver",h.resolver,{avoided:true}),this.finish(e,s,{text:h.text,data:h.data,storedAtMs:this.now()},"deterministic",r,c,o,at(),ct(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(l,{servedModel:e.model}))}let p=gn(s,{servedModel:l.modeloServido});if(i.allowExactCache&&a.exactCache!==false){let h=await this.deps.exactCache.get(p);if(h)return r.avoidCall(u,this.tokensFor(h.text,e)),o.record("exact-cache","hit",{ageMs:this.now()-h.storedAtMs}),this.finish(e,s,h,"exact",r,c,o,at(),ct(),this.now()-h.storedAtMs,void 0,void 0,void 0,void 0,this.informeDeCascada(l));o.record("exact-cache","miss");}let f=_o(s,{servedModel:l.modeloServido,deferrable:a.deferrable===true}),m=async()=>{try{return await this.expensivePath(n,e,s,i,a,r,c,o,p,u,l)}catch(h){throw (n.falloDelProveedor||n.llamadas>0)&&cc(h),h}};if(i.allowSingleflight&&a.singleflight!==false){let{value:h,coalesced:g}=await this.deps.singleflight.run(f,m);return g?(o.record("singleflight","coalesced",{key:f}),this.asCoalescedFollower(h,u,this.tokensFor(h.text??"",e),c,e)):h}return m()}async expensivePath(e,n,o,r,s,i,a,l,c,u,d){let p=this.entitled("semantic_cache");if(r.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&!p&&l.record("semantic-cache","degraded: feature not licensed (free tier)"),r.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&p){let k=await this.deps.semanticCache.find(o);if(k)return i.avoidCall(u,this.tokensFor(k.record.answer.text,n)),l.record("semantic-cache","hit",{confidence:k.confidence,similarity:k.similarity}),this.finish(n,o,k.record.answer,"semantic",i,a,l,at(),ct(),k.ageMs,k.confidence,void 0,void 0,void 0,this.informeDeCascada(d,{servedModel:n.model}));l.record("semantic-cache","miss");}let f=s.router===false,m=f?at():this.deps.router.classify(o);l.record("router",m.executionClass,{confidence:m.confidence,reason:m.reason});let h=f?this.deps.toolSelector.passthrough(n.tools):this.deps.toolSelector.select(o.normalizedText,n.tools,m.executionClass);if(i.actualTools=h.tools.length,h.droppedIds.length){let k=new Set(h.droppedIds),L=(n.tools??[]).filter(j=>k.has(j.id)).reduce((j,J)=>j+this.tokensFor(yo(J),n),0);i.eliminate(L),l.record("tool-selector",h.reason,{dropped:h.droppedIds,eliminatedTokens:L});}i.baselineRetrieval=m.rounds;let g=await jo({execution:m.executionClass,query:o.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=g.rounds,g.retrievedCount>0&&l.record("retrieval",`kept ${g.keptCount}/${g.retrievedCount}`,{rounds:g.rounds});let x=ct(),b=[...n.messages],y=ko(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
15
|
|
|
16
|
-
`+
|
|
17
|
-
${
|
|
16
|
+
`+g.docs.map((k,L)=>`[${k.source??k.id??`doc${L+1}`}]
|
|
17
|
+
${k.text}`).join(`
|
|
18
18
|
|
|
19
|
-
`)}:null,
|
|
20
|
-
`:"")+
|
|
21
|
-
`)
|
|
19
|
+
`)}:null,I=lt(n),T=n.response?.maxOutputTokens!=null?Math.floor(n.response.maxOutputTokens*3.2):null,D=this.contratosQueIncumplen.has(I)?vo(n.response?.schema,"",T):"";if(D&&Yt(b,{role:"system",content:`JSON limits (not API-enforced): ${D}`}),n.structuredData!==void 0){let k=JSON.stringify(n.structuredData),L=this.tokensFor(k,n);if(s.serialization!==false){x=this.deps.formatSelector.choose(n.structuredData,{model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let j=this.tokensFor(x.encoded+x.instruction,n);i.compress(L,j),Yt(b,{role:"system",content:(x.instruction?x.instruction+`
|
|
20
|
+
`:"")+x.encoded}),l.record("serialization",x.chosen,{reason:x.reason,jsonTokens:L,chosenTokens:j});}else Yt(b,{role:"system",content:k}),l.record("serialization","json-compact",{reason:"format selector disabled; sent compact JSON"});}if(C&&Yt(b,C),(s.compression===true||s.compression==="auto")&&r.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let k=this.config.compressionEconomics??{},L=xo(n.model,k),j={compressorCostTokens:k.compressorCostTokens??0,...k.minimumContextTokens!=null?{minimumContextTokens:k.minimumContextTokens}:{},...k.minimumNetTokens!=null?{minimumNetTokens:k.minimumNetTokens}:{}},J=0,P=0;for(let le of b)le.role==="system"?J+=1:P+=this.tokensFor(le.content,n);let Q=this.tokensFor(this.assemblePromptText(b,h.tools),n),W=En({...j,contextTokens:P,projectedEliminable:P}),Y=0,Ce=0,nn=false,We=W.reason;if(W.compress){let le=[];for(let xe of b){if(xe.role==="system"){le.push(xe);continue}let Ze=this.tokensFor(xe.content,n),ut=await this.config.compressor.compress({text:xe.content}),So=!ut.skipped&&ut.fidelityPassed,To=So?this.tokensFor(ut.compressed,n):Ze;So&&To<Ze?(le.push({...xe,content:ut.compressed}),Y+=Ze,Ce+=To):le.push(xe);}let js=this.tokensFor(this.assemblePromptText(le,h.tools),n),wo=En({...j,contextTokens:P,projectedEliminable:Y-Ce}),on=Es({originalTokens:Q,compressedTokens:js,tier:L,...k.prefix?{prefix:k.prefix}:{},compressorCostTokens:j.compressorCostTokens});Ce>=Y?We="no fidelity-passed net reduction":wo.compress?on.comprimir?(nn=true,We=on.razon,E=le.slice(0,y).some((xe,Ze)=>xe.content!==b[Ze]?.content),b=le,i.compress(Y,Ce)):We=on.razon:We=wo.reason;}nn||(Y=0,Ce=0),l.record("compression",nn?"applied":"skipped",{reason:We,before:Y,after:Ce,contextTokens:P,promptTokens:Q,cacheTierMinimum:L.minimumCacheTokens,protectedSystemMessages:J,prefixRewritten:E}),i.compressionReport={originalTokens:Y,compressedTokens:Ce,protectedSpans:J,fidelityPassed:true};}let R=n.response?.schema,S=R&&s.outputCodebook===true?vs(R,k=>this.tokensFor(k,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,lt(n),s.outputCodebookMeasuredOutputDeltaTokens)}):null;S&&l.record("output-codebook",S.applied?"applied":"skipped",{reason:S.reason,...S.applied?{renamedKeys:S.plan.renamedKeys,codedEnumValues:S.plan.codedEnumValues,schemaTokensOriginal:S.plan.schemaTokensOriginal,schemaTokensCompact:S.plan.schemaTokensCompact,modelledShapeSavingTokens:S.plan.modelledShapeSavingTokens,measuredOutputDeltaTokens:S.plan.measuredOutputDeltaTokens,outputDeltaProvenance:S.plan.outputDeltaProvenance,breakEvenOutputDeltaTokens:S.plan.breakEvenOutputDeltaTokens,netSavingUsd:S.plan.netSavingUsd,pricedForModel:d.modeloServido}:{}});let M=S?.applied?S.plan.compactSchema:R,v=M?Jo(d.modeloServido,M,this.deps.constraintBackends):{backend:"none",reason:"no output contract"};l.record("constraints",v.backend,{reason:v.reason});let w=this.decidirMarcadoDeCache(n,d.modeloServido,b,h,s.toolDiscovery===true,E?ko(b,true):y,l),_=this.now(),A=await this.descubrirHerramientas(e,n,s,h.tools,b,i,a,l),B=A.tools;i.actualTools=B.length;let F={messages:b,...B.length?{tools:B}:{},...M?{schema:M}:{},...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{},...s.deferrable?{deferrable:true}:{},constraintBackend:v.backend},O=await this.llamarProveedor({model:d.modeloServido,...F,...w.marcar?{stablePrefixMessages:w.mensajesDePrefijo,promptCacheKey:w.huella}:{}},e);i.actualLlm+=1;let X=k=>{if(!S?.applied)return k;let L=He(k);return L.ok?JSON.stringify(S.plan.expand(L.value)):k},U=X(O.text),ne=O.usage,K=false;if(d.enruta){let k=uo({texto:U,schema:R,finishReason:O.finishReason,pidioHerramientas:(O.toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!k.acepta),l.record("model-cascade",k.acepta?"accepted":"escalating",{servedModel:d.modeloServido,reason:k.motivo,checks:k.comprobaciones}),k.acepta||(K=true,i.cascadeAttempt(O.usage,d.precioBarato??a),i.actualLlm+=1,O=await this.llamarProveedor({model:n.model,...F},e),U=X(O.text));}let ce=K?n.model:d.modeloServido,Ke=K?this.costModelFor(n.model):a;i.actualInput+=O.usage.inputTokens,i.actualOutput+=O.usage.outputTokens,S?.applied&&l.record("output-codebook",He(O.text).ok?"expanded":"not-expanded (response was not JSON)",He(O.text).ok?{localOutputTokensCompact:this.tokensFor(O.text,n),localOutputTokensExpanded:this.tokensFor(U,n),creditedLedger:"none",note:"local count of the served answer in both shapes; not credited to any ledger"}:{}),R&&v.backend==="provider-native"&&O.structuredNatively===false&&(v={backend:"none",reason:"provider did not enforce the contract natively; the schema travelled in the prompt and the layer is the only validator"},l.record("constraints","none",{downgradedFrom:"provider-native",reason:v.reason})),i.sentInputLocal=this.tokensFor(this.assemblePromptText(b,B),n),i.removedInputLocal=Math.max(0,u-i.sentInputLocal),i.sentInputLocal+=A.tokensLocalesDelSondeo,i.estimatorExact=this.estimatorEsExacto(n),O.usage.cachedInputTokens&&i.providerCached(O.usage.cachedInputTokens),w.marcar&&(this.verjaDeCache.registrar(w.huella,ne),l.record("prefix-cache","measured",{cacheRead:ne.cachedInputTokens??0,cacheWritePremiumTokens:ne.cacheWriteInputTokens??0}));let ge=null;if(d.modo==="shadow"&&d.elegible&&d.candidato&&d.precioBarato&&hc(c,d.tasaDeMuestreo))try{let k=await this.llamarProveedor({model:d.candidato,...F},e);i.actualLlm+=1;let L=i.extraCostUsd;i.cascadeAttempt(k.usage,d.precioBarato);let j=X(k.text),J=uo({texto:j,schema:R,finishReason:k.finishReason,pidioHerramientas:(k.toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!J.acepta);let P=J.acepta?gs(j,U):null;ge={coste:i.extraCostUsd-L,divergio:P?P.divergen:null},l.record("model-cascade",J.acepta?"sample accepted":"sample escalated",{candidateModel:d.candidato,reason:J.motivo,sampleCost:ge.coste,...P?{diverged:P.divergen,divergence:P.motivo}:{},note:"measurement only: this answer was NEVER served. The escalation rate it feeds is a money figure, not a quality one"});}catch(k){l.record("model-cascade","sample failed (measurement only; the answer is unaffected)",{error:k instanceof Error?k.message:String(k)});}let Je=U,Re=true,Ge=(O.toolCalls?.length??0)>0;if(Ge&&(Re=null,R&&l.record("validation","n/a: model requested tool calls (the output contract applies to the final answer)")),R&&!Ge){let k=He(U),L=k.ok?se(k.value,R):{valid:false,errors:[{path:"$",message:"not valid JSON"}]};!L.valid&&gc(L.errors)&&this.contratosQueIncumplen.add(lt(n));let j=O.finishReason==="length",J=!L.valid&&L.errors.some(P=>/not a valid regular expression/.test(P.message));if(!L.valid&&J)l.record("validation","repair-skipped",{reason:"schema defect (uncompilable pattern); no output can satisfy it, a retry is a wasted call",errors:L.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 (seria una llamada pagada para el mismo fallo). Corrige el `pattern` del esquema.");else if(!L.valid&&j){let P=xs(R,Y=>this.tokensFor(Y,n)),Q=n.response?.maxOutputTokens??null,W=P!==null&&Q!=null&&P<=Q;W&&this.contratosQueIncumplen.add(lt(n)),l.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same cap would truncate again",maxOutputTokens:n.response?.maxOutputTokens??null,outputTokens:O.usage.outputTokens,model:ce,...P!==null?{schemaAllowsTokens:P}:{},learnedValueLimits:W}),this.avisarDeTruncado(n,ce,O.usage.outputTokens,P,W);}else if(!L.valid&&v.backend==="none"){i.retries=1,l.record("validation","repair-attempt",{errors:L.errors});let P=L.errors.slice(0,5).map(Y=>`- ${Y.path}: ${Y.message}`).join(`
|
|
21
|
+
`),Q=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
|
|
22
22
|
|
|
23
23
|
Previous reply:
|
|
24
|
-
${
|
|
24
|
+
${U}
|
|
25
25
|
|
|
26
26
|
Problems found:
|
|
27
|
-
${
|
|
27
|
+
${P}
|
|
28
28
|
|
|
29
|
-
Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}];C=await this.llamarProveedor({model:n.model,messages:$e,schema:R,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),i.actualLlm+=1,i.actualInput+=C.usage.inputTokens,i.actualOutput+=C.usage.outputTokens,i.repairOutput+=C.usage.outputTokens,i.repairInput+=C.usage.inputTokens,i.sentInputLocal+=this.tokensFor(this.assemblePromptText($e),n),B=C.text;let ve=Ft(B);L=ve.ok?pe(ve.value,R):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},ve.ok&&(V=ve.value);}else w.ok&&(V=w.value);H=L.valid,l.record("validation",H?"valid":"invalid");}let ue=this.now()-k,ee=da(V),Oe={text:B,data:V,rendered:ee,storedAtMs:this.now()};try{let w=I.aplicado,L=H!==!1&&!K&&!w;if(L||l.record("cache-write",K?"skipped: tool-call turn (an action request must not be replayed from cache)":H===!1?"skipped: response fails its output contract":"skipped: answered with a reduced tool view (tool discovery), so it must not be replayed"),L&&o.allowExactCache&&s.exactCache!==!1){let U=this.config.exactCacheTtlMs??864e5,te=o.maxCacheAgeMs==null?U:Math.min(U,o.maxCacheAgeMs);await this.deps.exactCache.set(a,Oe,te);}L&&o.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&await this.deps.semanticCache.store(r,Oe);}catch(w){l.record("cache-write","failed (non-fatal; answer already served)",{error:w instanceof Error?w.message:String(w)});}let _e=this.finish(n,r,Oe,"miss",i,c,l,m,h,void 0,void 0,H,D.backend,ue);return K&&(_e.toolCalls=C.toolCalls),C.finishReason!==void 0&&(_e.finishReason=C.finishReason),_e}async descubrirHerramientas(e,n,r,o,s,i,c,l){let a={tools:o,tokensLocalesDelSondeo:0,aplicado:false};if(r.toolDiscovery!==true)return a;if(o.length<2)return l.record("tool-discovery","skipped (nothing to discover)",{candidates:o.length}),a;let u=h=>this.tokensFor(Zn(h),n),d=o.map(Wo),p=Go({promptTokens:this.tokensFor(this.assemblePromptText(s),n),esquemasCompletos:o.reduce((h,g)=>h+u(g),0),descriptoresLigeros:d.reduce((h,g)=>h+u(g),0),esquemasDeLaSegunda:Yo(o.map(h=>({risk:h.risk,tokens:u(h)})),3),salidaFinal:n.response?.maxOutputTokens??256,salidaDelSondeo:96,precio:c});if(!p.aplicar)return l.record("tool-discovery","skipped (not worth a second call)",{reason:p.razon,oneCall:p.costeDeUnaLlamada,twoCalls:p.costeDeDosLlamadas}),a;let m,f=this.tokensFor(this.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}:{}},e);}catch(h){return l.record("tool-discovery","failed (falling back to a single call with every schema)",{error:h instanceof Error?h.message:String(h)}),a}i.actualLlm+=1,i.actualInput+=m.usage.inputTokens,i.actualOutput+=m.usage.outputTokens,i.discoveryInput+=m.usage.inputTokens,i.discoveryOutput+=m.usage.outputTokens;let b=Zo((m.toolCalls??[]).map(h=>h.name),o,3);return b.reconocidos.length===0?(l.record("tool-discovery","degraded: probe named no known tool",{finishReason:m.finishReason??null,...b.ignorados.length?{unknownNames:b.ignorados}:{}}),{tools:o,tokensLocalesDelSondeo:f,aplicado:false}):(l.record("tool-discovery","applied (two provider calls)",{chosen:b.reconocidos,sent:b.tools.map(h=>h.id),candidates:o.length,...b.ignorados.length?{unknownNames:b.ignorados}:{}}),{tools:b.tools,tokensLocalesDelSondeo:f,aplicado:true})}finish(e,n,r,o,s,i,c,l,a,u,d,p,m="none",f=0){let b=e.response?.schema,h=p===null?null:p??(b?pe(r.data,b).valid:true),g=this.buildReport(e,n,o,s,i,c,l,a,u,d,h,m,f);return {requestId:g.requestId,data:r.data,text:r.text,...r.rendered!==void 0?{rendered:r.rendered}:{},report:g}}buildReport(e,n,r,o,s,i,c,l,a,u,d,p,m){let f=o.estimateCost(s),b=i.elapsed();return {requestId:this.generateId(),model: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}:{},...a!==void 0?{ageMs:a}:{}},routing:{executionClass:c.executionClass,confidence:c.confidence,rounds:o.actualRetrieval,reason:c.reason},serialization:{chosen:l.chosen,candidateTokens:l.candidateTokens,instructionOverheadTokens:l.instructionOverheadTokens},...o.compressionReport?{compression:o.compressionReport}:{},constraints:{backend:p,schemaVersion:n.schemaVersion,...d===null?{}:{structurallyValid:d}},qualityStatus:fa(r,d),quality:{...r!=="miss"?{freshnessPassed:!Xt(n).requiresFreshData}:{}},cost:f,latencyMs:{total:b,preprocessing:Math.max(0,b-m),provider:m},traces:i.all()}}async failOpenDirect(e,n){let r=new Ke(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 Le,s=this.costModelFor(e.model),i;try{i=Yt(e);}catch{i={schemaVersion:e.response?.version??e.response?.contractId??"none"};}let c=e.response?.schema,l=this.now(),a=await this.config.provider.generate({model:e.model,messages:e.messages,...e.tools?.length?{tools:e.tools}:{},...c?{schema:c}:{},...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),u=this.now()-l;o.baselineLlm=1,o.actualLlm=1,o.actualInput=a.usage.inputTokens,o.actualOutput=a.usage.outputTokens,o.baselineInput=a.usage.inputTokens,o.baselineOutput=a.usage.outputTokens,a.usage.cachedInputTokens&&o.providerCached(a.usage.cachedInputTokens);let d=a.text,p=true,m=(a.toolCalls?.length??0)>0;if(m&&(p=null),c&&!m){let b=Ft(a.text);p=b.ok?pe(b.value,c).valid:false,b.ok&&(d=b.value);}let f=this.buildReport(e,i,"miss",o,s,r,et(),tt(),void 0,void 0,p,"none",u);return {requestId:f.requestId,data:d,text:a.text,...m?{toolCalls:a.toolCalls}:{},...a.finishReason!==void 0?{finishReason:a.finishReason}:{},report:f}}asCoalescedFollower(e,n,r,o){let s=new Le;s.avoidCall(n,r);let i=s.estimateCost(o),c=this.generateId();return {...e,requestId:c,report:{...e.report,requestId:c,calls:{...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:s.baselineInput,actualInput:s.actualInput,eliminatedInput:s.eliminatedInput,compressedInput:s.compressedInput,baselineOutput:s.publishedBaselineOutput,actualOutput:s.actualOutput,eliminatedOutput:s.eliminatedOutput,...s.providerCachedInput?{providerCachedInput:s.providerCachedInput}:{}},cache:{result:"singleflight"},cost:i}}}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(Zn(s));return o.join(`
|
|
30
|
-
`)}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;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(e)}
|
|
29
|
+
Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}];O=await this.llamarProveedor({model:ce,messages:Q,schema:R,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),i.actualLlm+=1,i.actualInput+=O.usage.inputTokens,i.actualOutput+=O.usage.outputTokens,i.repairOutput+=O.usage.outputTokens,i.repairInput+=O.usage.inputTokens,i.sentInputLocal+=this.tokensFor(this.assemblePromptText(Q),n),U=O.text;let W=He(U);L=W.ok?se(W.value,R):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},W.ok&&(Je=W.value);}else k.ok&&(Je=k.value);Re=L.valid,l.record("validation",Re?"valid":"invalid");}let Ps=this.now()-_,Bs=pc(Je),en={text:U,data:Je,rendered:Bs,storedAtMs:this.now()},be=this.informeDeDiferido(s,O,Ke);be&&l.record("deferred-tier",be.credited?"credited":"not-credited",{...be.requestedTier?{requestedTier:be.requestedTier}:{},...be.servedTier?{servedTier:be.servedTier}:{},creditedLedger:"none",reason:be.reason});try{let k=A.aplicado,L=O.finishReason==="length",j=Re!==!1&&!Ge&&!k&&!L;j||l.record("cache-write",Ge?"skipped: tool-call turn (an action request must not be replayed from cache)":Re===!1?"skipped: response fails its output contract":L?'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 J=K?gn(o,{servedModel:ce}):c;if(j&&r.allowExactCache&&s.exactCache!==!1){let Q=this.config.exactCacheTtlMs??864e5,W=r.maxCacheAgeMs==null?Q:Math.min(Q,r.maxCacheAgeMs);await this.deps.exactCache.set(J,en,W);}let P=ce!==n.model;j&&!P&&r.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache?await this.deps.semanticCache.store(o,en):j&&P&&s.semanticCache&&l.record("cache-write","semantic write skipped: a cheaper model answered, and this cache keys on the model the caller asked for");}catch(k){l.record("cache-write","failed (non-fatal; answer already served)",{error:k instanceof Error?k.message:String(k)});}let tn=this.finish(n,o,en,"miss",i,Ke,l,m,x,void 0,void 0,Re,v.backend,Ps,this.informeDeCascada(d,{servedModel:ce,...d.enruta?{escalated:K}:{},...d.elegible&&d.precioBarato?{estimatedSwapSaving:mc(i,K,d.precioBarato,this.costModelFor(n.model))}:{},...ge?{sampled:true,sampleCost:Qt(ge.coste),...ge.divergio!==null?{divergedOnSample:ge.divergio}:{}}:{},...i.cascadeInput>0||i.cascadeOutput>0?{cascadeInputTokens:i.cascadeInput,cascadeOutputTokens:i.cascadeOutput}:{}}),be);return Ge&&(tn.toolCalls=O.toolCalls),O.finishReason!==void 0&&(tn.finishReason=O.finishReason),tn}async descubrirHerramientas(e,n,o,r,s,i,a,l){let c={tools:r,tokensLocalesDelSondeo:0,aplicado:false};if(o.toolDiscovery!==true)return c;if(r.length<2)return l.record("tool-discovery","skipped (nothing to discover)",{candidates:r.length}),c;let u=g=>this.tokensFor(yo(g),n),d=r.map(Os),p=Cs({promptTokens:this.tokensFor(this.assemblePromptText(s),n),esquemasCompletos:r.reduce((g,x)=>g+u(x),0),descriptoresLigeros:d.reduce((g,x)=>g+u(x),0),esquemasDeLaSegunda:_s(r.map(g=>({risk:g.risk,tokens:u(g)})),3),salidaFinal:n.response?.maxOutputTokens??256,salidaDelSondeo:96,precio:a});if(!p.aplicar)return l.record("tool-discovery","skipped (not worth a second call)",{reason:p.razon,oneCall:p.costeDeUnaLlamada,twoCalls:p.costeDeDosLlamadas}),c;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(g){return l.record("tool-discovery","failed (falling back to a single call with every schema)",{error:g instanceof Error?g.message:String(g)}),c}i.actualLlm+=1,i.actualInput+=f.usage.inputTokens,i.actualOutput+=f.usage.outputTokens,i.discoveryInput+=f.usage.inputTokens,i.discoveryOutput+=f.usage.outputTokens;let h=Is((f.toolCalls??[]).map(g=>g.name),r,3);return h.reconocidos.length===0?(l.record("tool-discovery","degraded: probe named no known tool",{finishReason:f.finishReason??null,...h.ignorados.length?{unknownNames:h.ignorados}:{}}),{tools:r,tokensLocalesDelSondeo:m,aplicado:false}):(l.record("tool-discovery","applied (two provider calls)",{chosen:h.reconocidos,sent:h.tools.map(g=>g.id),candidates:r.length,...h.ignorados.length?{unknownNames:h.ignorados}:{}}),{tools:h.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:it(e.economia.r),breakEvenEscalationRate:it(e.economia.equilibrio),targetEscalationRate:it(e.economia.escaladoMaximo)}:{},...e.bucket?{workload:e.bucket}:{},...e.observada!=null?{escalationRate:it(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,o){if(e.deferrable!==true)return;let r=n.requestedServiceTier,s=Yo(n.servedServiceTier),i={...r?{requestedTier:r}:{},...s?{servedTier:s.servido}:{},credited:false,creditedLedger:"none",latency:er(r),reason:""};if(!r)return {...i,reason:Qo};if(!s)return {...i,reason:`asked the provider for the "${r}" tier, and it reported none back: the rate this request was billed at cannot be known, so nothing is credited`};if(s.factor==null)return {...i,reason:`asked for "${r}" and the provider reports serving "${s.servido}", a tier this layer has no published rate for: nothing is credited`};if(!s.conDescuento)return {...i,reason:`asked for "${r}" and the provider reports serving "${s.servido}", which bills at the standard rate: this request was billed as if it had never been deferred`};let a=n.usage,l=Math.min(Math.max(0,a.cachedInputTokens??0),Math.max(0,a.inputTokens)),c=o.cachedInputPer1k??o.inputPer1k,u=(Math.max(0,a.inputTokens)-l)/1e3*o.inputPer1k+l/1e3*c+Math.max(0,a.outputTokens)/1e3*o.outputPer1k,d=Xo(s,u);return {...i,credited:true,discountRate:it(s.factor),...d!=null?{estimatedTierSaving:Qt(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,o,r,s,i,a,l,c,u,d,p,f="none",m=0,h,g){let x=e.response?.schema,b=p===null?null:p??(x?se(o.data,x).valid:true),y=this.buildReport(e,n,r,s,i,a,l,c,u,d,b,f,m,h,g??this.diferidoSinLlamada(e));return {requestId:y.requestId,data:o.data,text:o.text,...o.rendered!==void 0?{rendered:o.rendered}:{},report:y}}buildReport(e,n,o,r,s,i,a,l,c,u,d,p,f,m,h){let g=r.estimateCost(s),x=i.elapsed(),b=m!=null&&m.servedModel!==m.requestedModel;return {requestId:this.generateId(),model:m?.servedModel??e.model,calls:{baselineLlm:r.baselineLlm,actualLlm:r.actualLlm,avoidedLlm:r.avoidedLlm,baselineRetrieval:r.baselineRetrieval,actualRetrieval:r.actualRetrieval,baselineTools:r.baselineTools,actualTools:r.actualTools,retries:r.retries},tokens:{baselineInput:r.baselineInput,actualInput:r.actualInput,eliminatedInput:r.eliminatedInput,compressedInput:r.compressedInput,baselineOutput:r.publishedBaselineOutput,actualOutput:r.actualOutput,eliminatedOutput:r.eliminatedOutput,...r.providerCachedInput?{providerCachedInput:r.providerCachedInput}:{}},cache:{result:o,...u!==void 0?{confidence:u}:{},...c!==void 0?{ageMs:c}:{}},routing:{executionClass:a.executionClass,confidence:a.confidence,rounds:r.actualRetrieval,reason:a.reason},serialization:{chosen:l.chosen,candidateTokens:l.candidateTokens,instructionOverheadTokens:l.instructionOverheadTokens},...r.compressionReport?{compression:r.compressionReport}:{},constraints:{backend:p,schemaVersion:n.schemaVersion,...d===null?{}:{structurallyValid:d}},qualityStatus:fc(o,d,b),...m?{modelCascade:m}:{},...h?{deferred:h}:{},quality:{...o!=="miss"?{freshnessPassed:!bn(n).requiresFreshData}:{}},cost:g,latencyMs:{total:x,preprocessing:Math.max(0,x-f),provider:f},traces:i.all()}}async failOpenDirect(e,n){let o=new Xe(this.now);o.record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",{error:n instanceof Error?n.message:String(n)});let r=new Pe,s=this.costModelFor(e.model),i;try{i=hn(e);}catch{i={schemaVersion:e.response?.version??e.response?.contractId??"none"};}let a=e.response?.schema,l=this.now(),c=await this.config.provider.generate({model:e.model,messages:e.messages,...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}:{}}),u=this.now()-l;r.baselineLlm=1,r.actualLlm=1,r.actualInput=c.usage.inputTokens,r.actualOutput=c.usage.outputTokens,r.baselineInput=c.usage.inputTokens,r.baselineOutput=c.usage.outputTokens,c.usage.cachedInputTokens&&r.providerCached(c.usage.cachedInputTokens);let d=c.text,p=true,f=(c.toolCalls?.length??0)>0;if(f&&(p=null),a&&!f){let h=He(c.text);p=h.ok?se(h.value,a).valid:false,h.ok&&(d=h.value);}let m=this.buildReport(e,i,"miss",r,s,o,at(),ct(),void 0,void 0,p,"none",u,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:m.requestId,data:d,text:c.text,...f?{toolCalls:c.toolCalls}:{},...c.finishReason!==void 0?{finishReason:c.finishReason}:{},report:m}}asCoalescedFollower(e,n,o,r,s){let i=new Pe;i.avoidCall(n,o);let a=i.estimateCost(r),l=this.generateId(),c=this.diferidoSinLlamada(s),u=c?{deferred:c}:{},{deferred:d,...p}=e.report;return {...e,requestId:l,report:{...p,requestId:l,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,o){let r=e.map(s=>s.content);o!==void 0&&r.push(JSON.stringify(o));for(let s of n??[])r.push(yo(s));return r.join(`
|
|
30
|
+
`)}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;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(e)}precioConocido(e){let n=this.config.costModels;if(n){let o=n[e];if(o)return o;let r=e.indexOf("/");if(r>=0){let s=n[e.slice(r+1)];if(s)return s}}return dt(e)}costModelFor(e){let n=this.precioConocido(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 price. Dollar figures will not match your bill. Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),cs))}};function He(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}function pc(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function fc(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 "not_verified"}}function it(t){return Math.round(t*1e6)/1e6}function Qt(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function mc(t,e,n,o){if(e)return Qt(-t.extraCostUsd);let r=s=>t.actualInput/1e3*s.inputPer1k+t.actualOutput/1e3*s.outputPer1k;return Qt(r(o)-r(n))}function hc(t,e){if(!(e>0))return false;if(e>=1)return true;let n=re(`${t}:cascade-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function at(){return {executionClass:"NO_RETRIEVAL",confidence:1,reason:"n/a (short-circuited)",rounds:0}}function ct(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,reason:"no structured payload"}}function vo(t,e="",n=null){if(t==null||typeof t!="object")return "";let o=t,r=[],s=e||"the value",i=m=>typeof o[m]=="number"?o[m]:null,a=i("maxLength"),l=i("minLength"),c=i("maxItems"),u=i("minItems"),d=i("maximum"),p=i("minimum");if(a!=null){let m=n!=null?Math.min(a,n):a;r.push(`${s}<=${m}ch`);}l!=null&&r.push(`${s}>=${l}ch`),c!=null&&r.push(`${s}<=${c} items`),u!=null&&r.push(`${s}>=${u} items`),d!=null&&r.push(`${s}<=${d}`),p!=null&&r.push(`${s}>=${p}`),typeof o.pattern=="string"&&r.push(`${s} matches /${o.pattern}/`);let f=o.properties;if(f&&typeof f=="object")for(let[m,h]of Object.entries(f)){let g=vo(h,e?`${e}.${m}`:m,n);g&&r.push(g);}if(o.items!==void 0){let m=vo(o.items,`${s} entries`,n);m&&r.push(m);}return r.join("; ")}function lt(t){let e=t.response;return e?e.contractId??e.version??JSON.stringify(e.schema??{}).slice(0,200):""}function gc(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.test(e.message))}function yo(t){return JSON.stringify({type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function Yt(t,e){for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}function ko(t,e=false){if(e){let n=0;for(;n<t.length&&t[n].role==="system";)n+=1;return n}for(let n=t.length-1;n>=0;n--)if(t[n].role==="user")return n;return ko(t,true)}function bc(t,e){let n=xo(t,e);return n.cacheReadMultiplier<1?n:null}var xc=6*3600;function Np(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's embedded public key. Get yours at https://savings.bivelio.com/dashboard/install"),t={...t,licenseGate:void 0});let n={...t,tokenizer:t.tokenizer??Eo},o,r;if(t.licenseKey&&!t.licenseGate){let a=ts;if(t.licenseServerUrl){let l=new ze,c=p=>zt(p,a,{revocation:l,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??xc}),u=c(t.licenseKey);n.licenseGate={isEntitled:p=>u.isEntitled(p),isActive:()=>u.isActive(),status:()=>u.status()};let d=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;o=new Vt({url:d,publicKeyPem:a,snapshot:l,getRefreshAfter:()=>u.refreshAfter?.(),...t.now?{nowSeconds:()=>Math.floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.licensePollIntervalSeconds}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{},...t.licenseRevocation??{}}),o.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(r=new qt({url:`${t.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,serviceAccountKey:t.serviceAccountKey,publicKey:a,initialToken:t.licenseKey,revocados:l,onNewToken:p=>{u=c(p);},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),r.start());}else n.licenseGate=is(t.licenseKey,a,t.now);}let s=new Xt(n),i;if(t.serviceAccountKey&&t.metering?.enabled!==false){let a=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/usage`:void 0);if(a){i=new st({url:a,serviceAccountKey:t.serviceAccountKey,...t.metering?.orgId?{orgId:t.metering.orgId}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...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.licenseFetch}:{},...t.now?{now:t.now}:{},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let l=t.metering?.ci??oo();if(t.metering?.seatId)i.setSeat(t.metering.seatId,l);else {let c=i;ro(t.serviceAccountKey).then(u=>c.setSeat(u,l)).catch(()=>{});}i.start();}}return {generate:async a=>{let l=await s.generate(a);if(i)try{i.record(l.report);}catch{}return l},close:()=>{o?.stop(),r?.stop(),i?.stop();}}}var qp="0.3.1";/*! Bundled license information:
|
|
31
31
|
|
|
32
32
|
@noble/curves/utils.js:
|
|
33
33
|
@noble/curves/abstract/modular.js:
|
|
@@ -35,4 +35,4 @@ Return ONLY the corrected JSON object. Keep the same content; fix only what is l
|
|
|
35
35
|
@noble/curves/abstract/edwards.js:
|
|
36
36
|
@noble/curves/ed25519.js:
|
|
37
37
|
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
38
|
-
*/export{
|
|
38
|
+
*/export{ir as AnthropicProvider,qp as BV_SALA_VERSION,rn as CATALOGO,Si as COMPACT_ROWS_INSTRUCTION,cs as DEFAULT_COST_MODEL,ts as EMBEDDED_PUBLIC_KEY,dn as ExactTokenizer,ht as ExecutionRouter,vt as FormatSelector,ln as HeuristicEstimator,ft as InMemoryExactCache,Mo as InMemorySemanticCache,Ie as LicenseError,Lc as MODELOS_POR_CODIFICACION,Ro as MODELS_BY_ENCODING,Rn as MockProvider,nr as OpenAICompatibleProvider,Ns as PRECIOS_AL_DIA,Sc as QUALITY_STATUSES,xn as ResolverRegistry,Vt as RevocationPoller,ze as RevocationSnapshot,Pe as SavingsLedger,kt as SchemaRegistry,mt as Singleflight,un as TokenizerRegistry,gt as ToolSelector,Xe as TraceCollector,st as UsageEmitter,pi as adaptiveK,oi as arithmeticResolver,gn as buildExactKey,_o as buildInflightKey,hn as canonicalize,Uo as compactRowsSerializer,Sa as computeNextDelay,Xs as cosine,Ti as createCompactRowsSerializer,Po as createDefaultResolvers,Ec as createHandoff,ou as createMockProvider,Np as createSavingsLayer,Ho as csvSerializer,$o as decodeCompactRows,di as dedupe,Eo as defaultTokenizerRegistry,ro as deriveSeatId,no as deriveStatus,oo as detectCi,xl as emptyState,vi as encodeCompactRows,ii as evalArithmetic,bn as evaluatePolicy,jo as executeRetrievalPlan,is as gateFromKey,Me as heuristicEstimator,ya as isKeyset,Oe as isStrictCompatible,No as jsonCompactSerializer,ni as keyTokensMatch,zt as liveGateFromKey,yl as mergeDelta,mn as modelFamilyOf,Zl as noopCompressor,pt as normalizeText,dt as precioDeLista,vl as projectContext,Ul as providerNativeBackend,cn as randomId,zs as registerExactTokenizer,Mc as registrarTokenizadorExacto,mi as renderState,Jo as resolveConstraintBackend,ls as resolveDependencies,rd as resolveLicense,re as sha256,En as shouldCompress,ye as stableStringify,yt as uniformColumns,se as validateAgainstSchema,to as verifyCompactSignature,Fe as verifyLicenseToken,ss as verifyRevocationList,Wl as withProtectedSpans};
|