@bivelio/savings-layer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,36 @@
1
+ var Hr=0;function dt(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++Hr,o=Date.now?Date.now():0;for(let s=0;s<16;s++)e[s]=(s<6?r>>>s*8:o>>>(s-6)*8)&255;}e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=[];for(let r=0;r<16;r++)n.push(e[r].toString(16).padStart(2,"0"));return `${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}-${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}function Bs(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 pt=class{id;exact=false;constructor(e="heuristic"){this.id=e;}count(e){if(e.length===0)return 0;let n=e.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],r=0;for(let o of n){let s=o[0];if(/\s/.test(s)){let i=(o.match(/\n/g)??[]).length;r+=i+Math.floor(Math.max(0,o.length-1)/2);}else /[A-Za-z]/.test(s)?r+=Math.max(1,Math.ceil(o.length/4)):/\d/.test(s)?r+=Math.max(1,Math.ceil(o.length/2)):r+=1;}return Math.max(r,Math.ceil(e.length/4))}},pe=new pt;var mt=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=pe){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){return this.modelToTokenizer.set(e,n),this}resolve(e){let n=e.tokenizer?this.estimators.get(e.tokenizer):void 0;if(n)return n;if(e.model){let r=this.modelToTokenizer.get(e.model);if(r){let o=this.estimators.get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},dn=new mt;var ht=class{constructor(e,n){this.codificador=n;this.id=e;}codificador;id;exact=true;count(e){return e.length===0?0:this.codificador.encode(e).length}},qr={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 Ns(t,e={}){let n=e.codificaciones??["o200k_base","cl100k_base"],r=false;for(let o of n){let s;try{s=await import(`gpt-tokenizer/encoding/${o}`);}catch{continue}if(typeof s.encode=="function"){t.register(new ht(o,s)),r=true;for(let i of qr[o]??[])t.mapModel(i,o),t.mapModel(`openai/${i}`,o);}}return r}var me=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;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.baselineOutput}estimateCost(e){let n=this.avoidedLlm===0,r="estimated";if(n)if(this.actualInput>0&&this.sentInputLocal>0){let f=this.actualInput/this.sentInputLocal;this.baselineInput=this.actualInput+Math.round(f*this.removedInputLocal),r=this.removedInputLocal===0?"measured":"estimated";}else this.actualInput>0?(this.baselineInput=this.actualInput,r="measured"):(this.baselineInput=0,r="unmeasured");let o=n?Math.max(0,this.actualOutput-this.repairOutput):this.baselineOutput,s=e.cachedInputPer1k??e.inputPer1k,i=Math.min(this.providerCachedInput,this.actualInput),a=f=>Math.max(0,f-i)/1e3*e.inputPer1k+i/1e3*s,l=a(this.baselineInput)+o/1e3*e.outputPer1k,c=a(this.actualInput)+this.actualOutput/1e3*e.outputPer1k,u=l===0?0:1-c/l;return {baselineEstimate:pn(l),actual:pn(c),netSavings:Kr(u),basis:r}}};function pn(t){return Math.round(t*1e10)/1e10}function Kr(t){return Math.round(t*1e6)/1e6}var Zr=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]),Gr=new TextEncoder;function H(t,e){return t>>>e|t<<32-e}function mn(t){let e=Gr.encode(t),n=e.length*8,r=(e.length+8>>6)+1,o=new Uint8Array(r*64);o.set(e),o[e.length]=128;let s=new DataView(o.buffer);s.setUint32(o.length-8,Math.floor(n/4294967296)),s.setUint32(o.length-4,n>>>0);let i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let c=0;c<o.length;c+=64){for(let x=0;x<16;x++)a[x]=s.getUint32(c+x*4);for(let x=16;x<64;x++){let w=a[x-15],E=a[x-2],R=H(w,7)^H(w,18)^w>>>3,k=H(E,17)^H(E,19)^E>>>10;a[x]=a[x-16]+R+a[x-7]+k|0;}let u=i[0],f=i[1],p=i[2],d=i[3],m=i[4],v=i[5],h=i[6],b=i[7];for(let x=0;x<64;x++){let w=H(m,6)^H(m,11)^H(m,25),E=m&v^~m&h,R=b+w+E+Zr[x]+a[x]|0,k=H(u,2)^H(u,13)^H(u,22),T=u&f^u&p^f&p,O=k+T|0;b=h,h=v,v=m,m=d+R|0,d=p,p=f,f=u,u=R+O|0;}i[0]=i[0]+u|0,i[1]=i[1]+f|0,i[2]=i[2]+p|0,i[3]=i[3]+d|0,i[4]=i[4]+m|0,i[5]=i[5]+v|0,i[6]=i[6]+h|0,i[7]=i[7]+b|0;}let l="";for(let c=0;c<8;c++)l+=(i[c]>>>0).toString(16).padStart(8,"0");return l}var Yr=/\s+/g;function Jr(t){return t.trim().replace(Yr," ").toLowerCase()}function he(t){return mn(t)}function we(t){return JSON.stringify(gt(t))}function gt(t){if(Array.isArray(t))return t.map(gt);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=gt(t[n]);return e}return t}function Wr(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function xt(t){let e=t.context??{},n=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(`
2
+ `),r=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${Jr(s.content)}`).join(`
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:Wr(t.model),messages:t.messages,normalizedText:r,systemPromptHash:he(n),toolsetHash:he(we(o)),structuredDataHash:t.structuredData!==void 0?he(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}}function hn(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:${he(e)}`}function gn(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,tools:t.toolsetHash,data:t.structuredDataHash,temperature:t.temperature,seed:t.seed});return `bvsala:inflight:${he(e)}`}var Xr=/\b(now|today|current|currently|latest|live|price|prices|stock|availability|weather|score|breaking|ahora|hoy|actual|precio|precios|disponibilidad)\b/i,Qr=/\b(my|mine|our|account|balance|subscription|invoice|order|profile|mi|mis|cuenta|factura|pedido|saldo)\b/i;function bt(t){let e=[],n=t.normalizedText,r=(t.original.tools??[]).some(f=>f.risk==="write"||f.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||Xr.test(n),s=Qr.test(n),i=(t.temperature??0)>.3&&t.seed==null;r&&e.push("write/destructive tools present"),o&&e.push("freshness-sensitive request"),s&&e.push("personalized/account-scoped request"),i&&e.push("stochastic sampling (temp>0.3, no seed)");let a=o&&(t.freshnessBucket==null||t.freshnessBucket==="any"),l=s&&t.principal==null,c=!i&&!a&&!l;a&&e.push("freshness-sensitive without a freshness bucket \u2192 exact cache off"),l&&e.push("personalized request with no principal (context.sessionId) \u2192 exact cache off");let u=!r&&!o&&!s&&!i&&t.freshnessBucket!=="day";return {allowExactCache:c,allowSemanticCache:u,allowSingleflight:!r&&!l,allowCompression:true,requiresFreshData:o,hasSideEffects:r,isPersonalized:s,reasons:e}}var je=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 Pe=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 eo(t,e){let n=Math.min(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i++){let a=t[i],l=e[i];r+=a*l,o+=a*a,s+=l*l;}return o===0||s===0?0:r/(Math.sqrt(o)*Math.sqrt(s))}var to=new Set(["no","not","never","none","cannot","cant","without","nor","nt","isnt","arent","wasnt","werent","dont","doesnt","didnt","wont","cant","shouldnt"]),no=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 xn(t){return (t.match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function ro(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 bn(t){return t.split(/\s+/).filter(Boolean)}function yn(t){return t.filter(e=>to.has(e.replace(/'/g,""))||e.endsWith("n't")).length}function oo(t,e){if(!ro(xn(t),xn(e)))return false;let n=bn(t),r=bn(e);if(yn(n)!==yn(r))return false;let o=c=>c.length>1&&!no.has(c)&&!/^\d/.test(c),s=new Set(n.filter(o)),i=new Set(r.filter(o));if(s.size===0&&i.size===0)return true;let a=0;for(let c of s)i.has(c)&&a++;let l=s.size+i.size-a;return l===0?true:a/l>=.75}var vn=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=eo(n,o.embedding);if(s<this.similarityThreshold||!oo(e.normalizedText,o.query))continue;let i=this.verify?await this.verify(e.normalizedText,o.query):s,a=Math.min(s,i);a<this.acceptThreshold||(!r||a>r.confidence)&&(r={record:o,similarity:s,verifierScore:i,confidence:a,ageMs:this.now()-o.storedAtMs});}return r}async store(e,n){let r=await this.embed(e.normalizedText);this.records.length>=this.maxRecords&&this.records.shift(),this.records.push({embedding:r,query:e.normalizedText,answer:n,tenantId:e.tenantId,authorizationScope:e.authorizationScope,principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.structuredDataHash,locale:e.locale,schemaVersion:e.schemaVersion,safetyPolicyVersion:e.safetyPolicyVersion,storedAtMs:this.now()});}invalidateEpoch(e){let n=0;for(let r=this.records.length-1;r>=0;r--)this.records[r].knowledgeEpoch===e&&(this.records.splice(r,1),n++);return n}get size(){return this.records.length}};var yt=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}},so={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]??io(t.normalizedText))?.trim();if(!n)return null;let r=co(n);return r===null||!Number.isFinite(r)?null:{text:ao(r),data:{value:r},resolver:"arithmetic"}}};function io(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function ao(t){return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function co(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],r=[],o={"+":1,"-":1,"*":2,"/":2,"%":2},s=a=>{let 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==="(")r.push(a),i=true;else if(a===")"){for(;r.length&&r[r.length-1]!=="(";)if(!s(r.pop()))return null;if(r.pop()!=="(")return null;i=false;}else {if(i)return null;for(;r.length&&r[r.length-1]!=="("&&o[r[r.length-1]]>=o[a];)if(!s(r.pop()))return null;r.push(a),i=true;}for(;r.length;){let a=r.pop();if(a==="("||!s(a))return null}return n.length===1?n[0]:null}function wn(){return new yt().register(so)}var lo=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,Sn=/\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,uo=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,Fe=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(n==="off")return Z("NO_RETRIEVAL",1,"retrieval disabled by caller",0);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 Z("TOOL_ACTION",.9,"imperative + write tool available",0);if(uo.test(r)&&!Sn.test(r))return Z("NO_RETRIEVAL",.8,"self-contained transformation",0);let s=this.classifier?.classify(r);return s&&s.confidence>=.75?Z(s.executionClass,s.confidence,"local classifier",fo(s.executionClass,this.maxRounds)):n==="single"?Z("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?Z("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):lo.test(r)?Z("MULTI_HOP_RETRIEVAL",.7,"comparison/compound question",Math.min(this.maxRounds,2)):Sn.test(r)?Z("SINGLE_RETRIEVAL",.65,"single factual lookup",1):Z("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function fo(t,e){return t==="SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function Z(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var ze=class{maxTools;scoreIntentMatch;constructor(e={}){this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??po;}select(e,n,r){if(!n||n.length===0)return {tools:[],droppedIds:[],reason:"no tools provided"};let o=r==="TOOL_ACTION",a=n.filter(u=>o||u.risk==="read").map(u=>({tool:u,score:this.scoreIntentMatch(e,u)})).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,this.maxTools).map(u=>u.tool),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 ${o?"allowed":"blocked"})`}}};function po(t,e){let n=t.toLowerCase(),r=0;for(let o of e.intents){let s=o.toLowerCase();n.includes(s)?r+=2:s.split(/\s+/).some(i=>i.length>3&&n.includes(i))&&(r+=1);}return r}function mo(t){let e=new Set,n=[];for(let r of t){let o=r.hash??go(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function ho(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((i,a)=>(a.score??0)-(i.score??0));if(r.length<=n)return r;let o=r[0]?.score??0;if(o<=0)return r.slice(0,e.maxDocuments);let s=[];for(let i of r){let a=(i.score??0)/o;if(s.length<n||a>=.4&&s.length<e.maxDocuments)s.push(i);else break}return s}async function kn(t,e){if(t.execution==="NO_RETRIEVAL"||t.execution==="TOOL_ACTION"||t.execution==="NON_CACHEABLE"||!e.retriever)return {docs:[],rounds:0,retrievedCount:0,keptCount:0};let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,r=[];for(let i=0;i<n;i++){let a=await e.retriever.retrieve(t.query,t.maxDocuments*2);r.push(...a);}let o=r.length;r=mo(r),e.reranker&&(r=await e.reranker.rerank(t.query,r));let s=ho(r,{maxDocuments:t.maxDocuments});return {docs:s,rounds:n,retrievedCount:o,keptCount:s.length}}function go(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function ki(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function Ei(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"&&vo(o)?Object.assign(n.userPreferences,o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let s=bo(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],yo(n,r);return n}function Ti(t){let e=t.rawTurns??3,n=[],r=xo(t.state);r&&n.push({role:"system",content:`Conversation state:
4
+ ${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function xo(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 bo(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 yo(t,e){for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function vo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var En={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function Tn(t,e={}){let n=e.delimiter??",",r=e.indent??" ",s=t.split(`
6
+ `).filter(l=>l.trim().length>0).map(l=>({indent:wo(l,r),content:l.slice(Rn(l,r))}));if(s.length===0)return {};let i=s[0];if(i.indent===0){let l=i.content.match(/^\[(\d+)\]\{(.*)\}:\s*$/);if(l){let u=ge(l[2],n),f=Number(l[1]),p=[];for(let d=0,m=1;d<f&&m<s.length;d++,m++){let v=s[m];if(v.indent!==1)break;let h=ge(v.content,n),b={};u.forEach((x,w)=>{b[x]=Se(h[w]??"null");}),p.push(b);}return p}let c=i.content.match(/^\[(\d+)\]:\s*(.*)$/);if(c){let u=c[2];return Number(c[1])===0||u.trim()===""?[]:ge(u,n).map(Se)}}let[a]=In(s,0,0,n);return a}function Rn(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}function wo(t,e){return Rn(t,e)/e.length}function In(t,e,n,r){let o={},s=e;for(;s<t.length;){let i=t[s];if(i.indent<n)break;if(i.indent>n){s++;continue}let a=So(i.content,r);if(!a){s++;continue}let{key:l,kind:c}=a;if(c.type==="scalar")o[l]=c.value,s++;else if(c.type==="inlineArray")o[l]=c.values,s++;else if(c.type==="emptyArray")o[l]=[],s++;else if(c.type==="table"){let u=[];s++;for(let f=0;f<c.count&&s<t.length;f++,s++){let p=t[s];if(p.indent!==n+1)break;let d=ge(p.content,r),m={};c.columns.forEach((v,h)=>{m[v]=Se(d[h]??"null");}),u.push(m);}o[l]=u;}else {let[u,f]=In(t,s+1,n+1,r);o[l]=u,s=f;}}return [o,s]}function So(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:Ne(n[1]),kind:{type:"table",count:Number(n[2]),columns:ge(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){let s=Number(r[2]),i=r[3];return s===0||i.trim()===""?{key:Ne(r[1]),kind:{type:"emptyArray"}}:{key:Ne(r[1]),kind:{type:"inlineArray",values:ge(i,e).map(Se)}}}let o=t.match(/^([^:]+):\s*(.*)$/);if(o){let s=Ne(o[1]),i=o[2];return i===""?{key:s,kind:{type:"object"}}:{key:s,kind:{type:"scalar",value:Se(i)}}}return null}function ge(t,e){let n=[],r="",o=false;for(let s=0;s<t.length;s++){let i=t[s];o?i==='"'?t[s+1]==='"'?(r+='"',s++):o=false:r+=i:i==='"'?o=true:i===e?(n.push(r),r=""):r+=i;}return n.push(r),n.map(s=>s.trim())}function Se(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 Ne(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,'"'):e}function ko(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return St(null,t,0,o,n,r),o.join(`
7
+ `)}function St(t,e,n,r,o,s){let i=s.repeat(n),a=t===null?"":`${To(t)}`;if(Array.isArray(e)){Eo(a,e,n,r,o,s);return}if(wt(e)){t!==null&&r.push(`${i}${a}:`);let l=t===null?n:n+1;for(let[c,u]of Object.entries(e))St(c,u,l,r,o,s);return}r.push(`${i}${a}: ${$e(e,o)}`);}function Eo(t,e,n,r,o,s){let i=s.repeat(n),a=t===""?"":t;if(e.length===0){r.push(`${i}${a}[0]:`);return}if(e.every(vt)){let f=e.map(p=>$e(p,o)).join(o);r.push(`${i}${a}[${e.length}]: ${f}`);return}let l=Ve(e);if(l){r.push(`${i}${a}[${e.length}]{${l.join(o)}}:`);let f=s.repeat(n+1);for(let p of e){let d=l.map(m=>$e(p[m],o)).join(o);r.push(`${f}${d}`);}return}r.push(`${i}${a}[${e.length}]:`);let c=n+1,u=s.repeat(c);for(let f of e)if(vt(f))r.push(`${u}- ${$e(f,o)}`);else {let p=[];St(null,f,0,p,o,s);let[d,...m]=p;r.push(`${u}- ${d??""}`);for(let v of m)r.push(`${u}${s}${v}`);}}function Ve(t){if(t.length===0)return null;let e=t[0];if(!wt(e))return null;let n=Object.keys(e);if(n.length===0)return null;let r=n.slice().sort().join("\0");for(let o of t){if(!wt(o))return null;let s=Object.keys(o);if(s.slice().sort().join("\0")!==r)return null;for(let i of s)if(!vt(o[i]))return null}return n}function To(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:On(t)}function $e(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)?On(n):n}function On(t){return `"${t.replace(/"/g,'""')}"`}function vt(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function wt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ro="Data is TOON: `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 Io(t={}){return {format:"toon",supports(){return true},encode(e){return ko(e,t)},instruction(){return Ro},decode(e){return Tn(e,t)}}}var _n=Io();var An={format:"csv",supports(t){return Array.isArray(t)&&Ve(t)!==null},encode(t){let e=t,n=Ve(e),r=n.map(Cn).join(","),o=e.map(s=>n.map(i=>Cn(s[i])).join(","));return [r,...o].join(`
9
+ `)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function Cn(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}var Ue=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[En,_n,An],this.minSavingsTokens=e.minimumSavingsTokens??64,this.minSavingsRatio=e.minimumSavingsRatio??.08,this.qualityPenalty=e.qualityPenalty??(()=>0);}choose(e,n){let r={model:n.model,tokenizer:n.tokenizer},o=[];for(let c of this.serializers){if(!c.supports(e))continue;let u=c.encode(e);if(c.format!=="json-compact"&&!Oo(c,u,e))continue;let f=c.instruction(e),p=this.tokenizer.count(u,r),d=f?this.tokenizer.count(f,r):0,m=this.qualityPenalty(n.model??"",c.format);o.push({format:c.format,encoded:u,instruction:f,payloadTokens:p,instructionTokens:d,penalty:m,total:p+d+m});}let s=o.find(c=>c.format==="json-compact"),i={};for(let c of o)i[c.format]=c.total;if(!s){let c=o[0];return c?Bn(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 o){if(c.format==="json-compact")continue;let u=s.total-c.total,f=s.total===0?0:u/s.total;u>=this.minSavingsTokens&&f>=this.minSavingsRatio&&c.total<a.total&&(a=c,l=`${c.format} saved ${u} tokens (${(f*100).toFixed(1)}%) vs json`);}return Bn(a,i,l)}};function Oo(t,e,n){if(!t.decode)return false;try{return kt(t.decode(e),n)}catch{return false}}function kt(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(!kt(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)||!kt(t[i],e[i]))return false;return true}function Bn(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function ke(t,e,n="$"){let r=[];return Et(t,e,n,r),{valid:r.length===0,errors:r}}function Et(t,e,n,r){switch(e.enum&&!e.enum.some(o=>Lo(o,t))&&r.push({path:n,message:"value not in enum"}),e.type){case "object":_o(t,e,n,r);break;case "array":Co(t,e,n,r);break;case "string":Ao(t,e,n,r);break;case "number":case "integer":Bo(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function _o(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,message:"expected object"});return}let o=t;for(let s of e.required??[])s in o||r.push({path:`${n}.${s}`,message:"missing required property"});if(e.additionalProperties===false&&e.properties){let s=new Set(Object.keys(e.properties));for(let i of Object.keys(o))s.has(i)||r.push({path:`${n}.${i}`,message:"additional property not allowed"});}if(e.properties)for(let[s,i]of Object.entries(e.properties))s in o&&Et(o[s],i,`${n}.${s}`,r);}function Co(t,e,n,r){if(!Array.isArray(t)){r.push({path:n,message:"expected array"});return}e.maxItems!=null&&t.length>e.maxItems&&r.push({path:n,message:`array exceeds maxItems ${e.maxItems}`}),e.minItems!=null&&t.length<e.minItems&&r.push({path:n,message:`array below minItems ${e.minItems}`}),e.items&&t.forEach((o,s)=>Et(o,e.items,`${n}[${s}]`,r));}function Ao(t,e,n,r){if(typeof t!="string"){r.push({path:n,message:"expected string"});return}if(e.maxLength!=null&&t.length>e.maxLength&&r.push({path:n,message:`string exceeds maxLength ${e.maxLength}`}),e.minLength!=null&&t.length<e.minLength&&r.push({path:n,message:`string below minLength ${e.minLength}`}),e.pattern){let o=null;try{o=new RegExp(e.pattern);}catch{r.push({path:n,message:`schema pattern is not a valid regular expression: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function Bo(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}e.type==="integer"&&!Number.isInteger(t)&&r.push({path:n,message:"expected integer"}),e.maximum!=null&&t>e.maximum&&r.push({path:n,message:`number exceeds maximum ${e.maximum}`}),e.minimum!=null&&t<e.minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function Lo(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var He=class{contracts=new Map;register(e){return this.contracts.set(e.contractId,e),this}resolve(e){return this.contracts.get(e)}has(e){return this.contracts.has(e)}static lint(e,n="$"){let r=[];return Tt(e,n,r),r}};function Tt(t,e,n){if(t.type==="object"){t.additionalProperties!==false&&n.push(`${e}: object should set additionalProperties:false`);for(let[r,o]of Object.entries(t.properties??{}))Tt(o,`${e}.${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&Tt(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: string should set maxLength or use an enum`);}function Ln(t,e,n){for(let r of n)if(r.supports(t,e))return {backend:r.id,reason:`first supporting backend: ${r.id}`};return {backend:"none",reason:"no constrained-decoding backend available; will validate + repair"}}function Gi(t=()=>true){return {id:"provider-native",supports:t}}function ea(t){let e=t.minimumContextTokens??2e3,n=t.minimumNetTokens??200;if(t.contextTokens<e)return {compress:false,reason:`context ${t.contextTokens} < ${e} min`};let r=t.projectedEliminable-t.compressorCostTokens;return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function ta(t){return {async compress(e){let n=e.protectedSpans??[],r=e.text,o=[];n.forEach((l,c)=>{let u=`\0PROTECT_${c}\0`;o.push({token:u,span:l}),r=r.split(l.text).join(u);});let s=await t.compress({text:r,...e.targetRatio!=null?{targetRatio:e.targetRatio}:{}}),i=s.compressed,a=true;for(let{token:l,span:c}of o){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 na={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 Mn=new WeakSet;function Dn(t){Mn.add(t);}var Rt=class{id="mock";options;constructor(e={}){this.options=e,Dn(this);}async generate(e){let n=e.messages.map(a=>a.content).join(`
10
+ `),r=pe.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??{}})));r+=pe.count(a);}let o,s=false;if(e.schema){let a=this.options.data??qe(e.schema);o=JSON.stringify(a),s=true;}else o=this.options.answer??`mock-response(${e.model})`;let i=Math.min(e.maxOutputTokens??Number.MAX_SAFE_INTEGER,pe.count(o));return {text:o,usage:{inputTokens:r,outputTokens:i,...this.options.cachedInputTokens!=null?{cachedInputTokens:this.options.cachedInputTokens}:{}},structuredNatively:s}}};function qe(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 r=t.properties?.[n];e[n]=r?qe(r):null;}for(let[n,r]of Object.entries(t.properties??{}))n in e||(e[n]=qe(r));return e}case "array":return t.items?[qe(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 la(t){return new Rt(t)}var Pn=new Set;function Ee(t,e){Pn.has(t)||(Pn.add(t),console.warn(e));}function Te(t){if(t==null||typeof t!="object")return true;let e=t,n=e.properties;if(n&&typeof n=="object"){if(e.additionalProperties!==false)return false;let o=Object.keys(n),s=Array.isArray(e.required)?e.required.map(String):[];if(o.some(i=>!s.includes(i)))return false;for(let i of Object.values(n))if(!Te(i))return false}if(e.items!==void 0&&!Te(e.items))return false;for(let o of ["anyOf","oneOf","allOf"]){let s=e[o];if(Array.isArray(s)&&s.some(i=>!Te(i)))return false}let r=e.$defs??e.definitions;return !(r&&typeof r=="object"&&Object.values(r).some(o=>!Te(o)))}var Fn=class{id;opts;fetchImpl;constructor(e){this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch;}async generate(e){let r={model:this.opts.stripProviderPrefix?e.model.replace(/^[^/]+\//,""):e.model,messages:e.messages.map(d=>({role:d.role,content:d.content}))};if(e.maxOutputTokens!=null&&(r.max_tokens=e.maxOutputTokens),e.temperature!=null&&(r.temperature=e.temperature),e.seed!=null&&(r.seed=e.seed),e.schema){let d=Te(e.schema);d||Ee("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."),r.response_format={type:"json_schema",json_schema:{name:"bvsala_contract",schema:e.schema,strict:d}};}e.tools&&e.tools.length>0&&(r.tools=e.tools.map(d=>({type:"function",function:{name:d.id,...d.description?{description:d.description}:{},parameters:d.parameters??{type:"object",properties:{}}}})));let o=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(r)});if(!o.ok){let d=await Mo(o);throw new Error(`provider ${o.status}: ${d}`)}let s=await o.json(),i=s.choices?.[0]?.message?.content??"",a=s.usage??{},l=a.prompt_tokens??0,c=a.completion_tokens??0,u=typeof a.prompt_tokens!="number",f=typeof a.completion_tokens!="number";if(this.opts.requireUsage&&(u||f))throw new Error(`provider returned incomplete usage (prompt=${a.prompt_tokens??"absent"}, completion=${a.completion_tokens??"absent"}); cannot measure cost. For gateways/streaming, ensure usage reporting is enabled.`);let p=s.choices?.[0]?.finish_reason;return {text:i,...p?{finishReason:p}:{},usage:{inputTokens:l,outputTokens:c,...a.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:a.prompt_tokens_details.cached_tokens}:{}},structuredNatively:e.schema!=null,raw:s}}};async function Mo(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}var Re=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 ie=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function It(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Ke(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 V(t,e,n=""){let r=It(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){let i=n&&`"${n}" `,a=s?` of length ${e}`:"",l=r?`length=${o}`:`type=${typeof t}`,c=i+"expected Uint8Array"+a+", got "+l;throw r?new RangeError(c):new TypeError(c)}return t}function Ot(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 Nn(t,e){V(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 Ie(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function Ze(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var $n=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Do=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ge(t){if(V(t),$n)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Do[t[n]];return e}var G={_0:48,_9:57,A:65,F:70,a:97,f:102};function zn(t){if(t>=G._0&&t<=G._9)return t-G._0;if(t>=G.A&&t<=G.F)return t-(G.A-10);if(t>=G.a&&t<=G.f)return t-(G.a-10)}function Oe(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if($n)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=zn(t.charCodeAt(s)),a=zn(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)}r[o]=i*16+a;}return r}function _t(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];V(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 Vn(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 Un(t=32){Ke(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 Hn=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var Ye=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=Ze(this.buffer);}update(e){Ot(this),V(e);let{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let l=Ze(e);for(;o<=s-i;i+=o)this.process(l,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ot(this),Nn(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;n[i++]=128,Ie(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let f=i;f<o;f++)n[f]=0;r.setBigUint64(o-8,BigInt(this.length*8),s),this.process(r,0);let a=Ze(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 f=0;f<c;f++)a.setUint32(4*f,u[f],s);}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};var z=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Je=BigInt(4294967295),qn=BigInt(32);function jo(t,e=false){return e?{h:Number(t&Je),l:Number(t>>qn&Je)}:{h:Number(t>>qn&Je)|0,l:Number(t&Je)|0}}function Kn(t,e=false){let n=t.length,r=new Uint32Array(n),o=new Uint32Array(n);for(let s=0;s<n;s++){let{h:i,l:a}=jo(t[s],e);[r[s],o[s]]=[i,a];}return [r,o]}var Ct=(t,e,n)=>t>>>n,At=(t,e,n)=>t<<32-n|e>>>n,ae=(t,e,n)=>t>>>n|e<<32-n,ce=(t,e,n)=>t<<32-n|e>>>n,_e=(t,e,n)=>t<<64-n|e>>>n-32,Ce=(t,e,n)=>t>>>n-32|e<<64-n;function q(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var Zn=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Gn=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Yn=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Jn=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,Wn=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Xn=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0;var Qn=Kn(["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))),Fo=Qn[0],zo=Qn[1],Q=new Uint32Array(80),ee=new Uint32Array(80),Bt=class extends Ye{constructor(e){super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:a,Dl:l,Eh:c,El:u,Fh:f,Fl:p,Gh:d,Gl:m,Hh:v,Hl:h}=this;return [e,n,r,o,s,i,a,l,c,u,f,p,d,m,v,h]}set(e,n,r,o,s,i,a,l,c,u,f,p,d,m,v,h){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=l|0,this.Eh=c|0,this.El=u|0,this.Fh=f|0,this.Fl=p|0,this.Gh=d|0,this.Gl=m|0,this.Hh=v|0,this.Hl=h|0;}process(e,n){for(let w=0;w<16;w++,n+=4)Q[w]=e.getUint32(n),ee[w]=e.getUint32(n+=4);for(let w=16;w<80;w++){let E=Q[w-15]|0,R=ee[w-15]|0,k=ae(E,R,1)^ae(E,R,8)^Ct(E,R,7),T=ce(E,R,1)^ce(E,R,8)^At(E,R,7),O=Q[w-2]|0,_=ee[w-2]|0,B=ae(O,_,19)^_e(O,_,61)^Ct(O,_,6),L=ce(O,_,19)^Ce(O,_,61)^At(O,_,6),g=Yn(T,L,ee[w-7],ee[w-16]),y=Jn(g,k,B,Q[w-7],Q[w-16]);Q[w]=y|0,ee[w]=g|0;}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:a,Cl:l,Dh:c,Dl:u,Eh:f,El:p,Fh:d,Fl:m,Gh:v,Gl:h,Hh:b,Hl:x}=this;for(let w=0;w<80;w++){let E=ae(f,p,14)^ae(f,p,18)^_e(f,p,41),R=ce(f,p,14)^ce(f,p,18)^Ce(f,p,41),k=f&d^~f&v,T=p&m^~p&h,O=Wn(x,R,T,zo[w],ee[w]),_=Xn(O,b,E,k,Fo[w],Q[w]),B=O|0,L=ae(r,o,28)^_e(r,o,34)^_e(r,o,39),g=ce(r,o,28)^Ce(r,o,34)^Ce(r,o,39),y=r&s^r&a^s&a,S=o&i^o&l^i&l;b=v|0,x=h|0,v=d|0,h=m|0,d=f|0,m=p|0,{h:f,l:p}=q(c|0,u|0,_|0,B|0),c=a|0,u=l|0,a=s|0,l=i|0,s=r|0,i=o|0;let I=Zn(B,g,S);r=Gn(I,_,L,y),o=I|0;}(({h:r,l:o}=q(this.Ah|0,this.Al|0,r|0,o|0))),{h:s,l:i}=q(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l}=q(this.Ch|0,this.Cl|0,a|0,l|0),{h:c,l:u}=q(this.Dh|0,this.Dl|0,c|0,u|0),{h:f,l:p}=q(this.Eh|0,this.El|0,f|0,p|0),{h:d,l:m}=q(this.Fh|0,this.Fl|0,d|0,m|0),{h:v,l:h}=q(this.Gh|0,this.Gl|0,v|0,h|0),{h:b,l:x}=q(this.Hh|0,this.Hl|0,b|0,x|0),this.set(r,o,s,i,a,l,c,u,f,p,d,m,v,h,b,x);}roundClean(){Ie(Q,ee);}destroy(){this.destroyed=true,Ie(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},Lt=class extends Bt{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 We=Vn(()=>new Lt,Hn(3));var D=(t,e,n)=>V(t,e,n),Dt=Ke,jt=Ge,K=(...t)=>_t(...t),er=t=>Oe(t),et=It,tr=t=>Un(t),Qe=BigInt(0),Mt=BigInt(1);function xe(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"expected boolean, got type="+typeof t)}return t}function No(t){if(typeof t=="bigint"){if(!Xe(t))throw new RangeError("positive bigint expected, got "+t)}else Dt(t);return t}function Y(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 nr(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Qe:BigInt("0x"+t)}function Pt(t){return nr(Ge(t))}function J(t){return nr(Ge(Ae(V(t)).reverse()))}function Ft(t,e){if(Ke(e),e===0)throw new RangeError("zero length");t=No(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return Oe(n.padStart(e*2,"0"))}function rr(t,e){return Ft(t,e).reverse()}function or(t,e){if(t=D(t),e=D(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 Ae(t){return Uint8Array.from(D(t))}var Xe=t=>typeof t=="bigint"&&Qe<=t;function $o(t,e,n){return Xe(t)&&Xe(e)&&Xe(n)&&e<=t&&t<n}function zt(t,e,n,r){if(!$o(e,n,r))throw new RangeError("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Nt(t){if(t<Qe)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>Qe;t>>=Mt,e+=1);return e}var sr=t=>(Mt<<BigInt(t))-Mt;function le(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function r(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let 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 o=(s,i)=>Object.entries(s).forEach(([a,l])=>r(a,l,i));o(e,false),o(n,true);}var $t=()=>{throw new Error("not implemented")};var N=BigInt(0),j=BigInt(1),ue=BigInt(2),lr=BigInt(3),ur=BigInt(4),fr=BigInt(5),Vo=BigInt(7),dr=BigInt(8),Uo=BigInt(9),pr=BigInt(16);function M(t,e){if(e<=N)throw new Error("mod: expected positive modulus, got "+e);let n=t%e;return n>=N?n:e+n}function U(t,e,n){if(e<N)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >N;)r*=r,r%=n;return r}function ir(t,e){if(t===N)throw new Error("invert: expected non-zero number");if(e<=N)throw new Error("invert: expected positive modulus, got "+e);let n=M(t,e),r=e,o=N,i=j;for(;n!==N;){let c=r/n,u=r-n*c,f=o-i*c;r=n,n=u,o=i,i=f;}if(r!==j)throw new Error("invert: does not exist");return M(o,e)}function Vt(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function mr(t,e){let n=t,r=(n.ORDER+j)/ur,o=n.pow(e,r);return Vt(n,o,e),o}function Ho(t,e){let n=t,r=(n.ORDER-fr)/dr,o=n.mul(e,ue),s=n.pow(o,r),i=n.mul(e,s),a=n.mul(n.mul(i,ue),s),l=n.mul(i,n.sub(a,n.ONE));return Vt(n,l,e),l}function qo(t){let e=ot(t),n=hr(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+Vo)/pr;return((a,l)=>{let c=a,u=c.pow(l,i),f=c.mul(u,r),p=c.mul(u,o),d=c.mul(u,s),m=c.eql(c.sqr(f),l),v=c.eql(c.sqr(p),l);u=c.cmov(u,f,m),f=c.cmov(d,p,v);let h=c.eql(c.sqr(f),l),b=c.cmov(u,f,h);return Vt(c,b,l),b})}function hr(t){if(t<lr)throw new Error("sqrt is not defined for small field");let e=t-j,n=0;for(;e%ue===N;)e/=ue,n++;let r=ue,o=ot(t);for(;ar(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return mr;let s=o.pow(r,e),i=(e+j)/ue;return function(l,c){let u=l;if(u.is0(c))return c;if(ar(u,c)!==1)throw new Error("Cannot find square root");let f=n,p=u.mul(u.ONE,s),d=u.pow(c,e),m=u.pow(c,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))return u.ZERO;let v=1,h=u.sqr(d);for(;!u.eql(h,u.ONE);)if(v++,h=u.sqr(h),v===f)throw new Error("Cannot find square root");let b=j<<BigInt(f-v-1),x=u.pow(p,b);f=v,p=u.sqr(x),d=u.mul(d,p),m=u.mul(m,x);}return m}}function Ko(t){return t%ur===lr?mr:t%dr===fr?Ho:t%pr===Uo?qo(t):hr(t)}var W=(t,e)=>(M(t,e)&j)===j,Zo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function gr(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=Zo.reduce((r,o)=>(r[o]="function",r),e);if(le(t,n),Y(t.BYTES,"BYTES"),Y(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=j)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Go(t,e,n){let r=t;if(n<N)throw new Error("invalid exponent, negatives unsupported");if(n===N)return r.ONE;if(n===j)return e;let o=r.ONE,s=e;for(;n>N;)n&j&&(o=r.mul(o,s)),s=r.sqr(s),n>>=j;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((a,l,c)=>r.is0(l)?a:(o[c]=a,r.mul(a,l)),r.ONE),i=r.inv(s);return e.reduceRight((a,l,c)=>r.is0(l)?a:(o[c]=r.mul(a,o[c]),r.mul(a,l)),i),o}function ar(t,e){let n=t,r=(n.ORDER-j)/ue,o=n.pow(e,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Yo(t,e){if(e!==void 0&&Dt(e),t<=N)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=Nt(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 cr=new WeakMap,nt=class{ORDER;BITS;BYTES;isLE;ZERO=N;ONE=j;_lengths;_mod;constructor(e,n={}){if(e<=j)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}=Yo(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 N<=e&&e<this.ORDER}is0(e){return e===N}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&j)===j}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 Go(this,e,n)}div(e,n){return M(e*ir(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 ir(e,this.ORDER)}sqrt(e){let n=cr.get(this);return n||cr.set(this,n=Ko(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?rr(e,this.BYTES):Ft(e,this.BYTES)}fromBytes(e,n=false){D(e);let{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(o);c.set(e,s?0:c.length-e.length),e=c;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let l=s?J(e):Pt(e);if(a&&(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 xe(r,"condition"),r?n:e}};Object.freeze(nt.prototype);function ot(t,e={}){return new nt(t,e)}var st=BigInt(0),Kt=BigInt(1);function xr(t,e){let n=e.negate();return t?n:e}function at(t,e){let n=rt(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function wr(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ut(t,e){wr(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=sr(t),i=BigInt(t);return {windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function br(t,e,n){let{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n,a=Number(t&o),l=t>>i;a>r&&(a-=s,l+=Kt);let c=e*r,u=c+Math.abs(a)-1,f=a===0,p=a<0,d=e%2!==0;return {nextN:l,offset:u,isZero:f,isNeg:p,isNegF:d,offsetF:c}}var Ht=new WeakMap,Sr=new WeakMap;function qt(t){return Sr.get(t)||1}function yr(t){if(t!==st)throw new Error("invalid wNAF")}var it=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>st;)n&Kt&&(r=r.add(o)),o=o.double(),n>>=Kt;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Ut(n,this.bits),s=[],i=e,a=i;for(let l=0;l<r;l++){a=i,s.push(a);for(let c=1;c<o;c++)a=a.add(i),s.push(a);i=a.double();}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Ut(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:l,offset:c,isZero:u,isNeg:f,isNegF:p,offsetF:d}=br(r,a,i);r=l,u?s=s.add(xr(p,n[d])):o=o.add(xr(f,n[c]));}return yr(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.ZERO){let s=Ut(e,this.bits);for(let i=0;i<s.windows&&r!==st;i++){let{nextN:a,offset:l,isZero:c,isNeg:u}=br(r,i,s);if(r=a,!c){let f=n[l];o=o.add(u?f.negate():f);}}return yr(r),o}getPrecomputes(e,n,r){let o=Ht.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Ht.set(n,o))),o}cached(e,n,r){let o=qt(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let s=qt(e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){wr(n,this.bits),Sr.set(e,n),Ht.delete(e);}hasCache(e){return qt(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 gr(e),e}else return ot(t,{isLE:n})}function kr(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 c=e[l];if(!(typeof c=="bigint"&&c>st))throw new Error(`CURVE.${l} must be positive bigint`)}let o=vr(e.p,n.Fp,r),s=vr(e.n,n.Fn,r),a=["Gx","Gy","a","d"];for(let l of a)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 Er(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var te=BigInt(0),P=BigInt(1),Zt=BigInt(2),Jo=BigInt(8);function Wo(t,e,n,r){let o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function Tr(t,e={}){let n=e,r=kr("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r,i=r.CURVE,{h:a}=i;le(n,{},{uvRatio:"function"});let l=Zt<<BigInt(s.BYTES*8)-P,c=v=>o.create(v),u=n.uvRatio===void 0?(v,h)=>{try{return {isValid:!0,value:o.sqrt(o.div(v,h))}}catch{return {isValid:false,value:te}}}:n.uvRatio;if(!Wo(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(v,h,b=false){let x=b?P:te;return zt("coordinate "+v,h,x,l),h}function p(v){if(!(v instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,P,c(i.Gx*i.Gy));static ZERO=new d(te,P,P,te);static Fp=o;static Fn=s;X;Y;Z;T;constructor(h,b,x,w){this.X=f("x",h),this.Y=f("y",b),this.Z=f("z",x,true),this.T=f("t",w),Object.freeze(this);}static CURVE(){return i}static fromAffine(h){if(h instanceof d)throw new Error("extended point not allowed");let{x:b,y:x}=h||{};return f("x",b),f("y",x),new d(b,x,P,c(b*x))}static fromBytes(h,b=false){let x=o.BYTES,{a:w,d:E}=i;h=Ae(D(h,x,"point")),xe(b,"zip215");let R=Ae(h),k=h[x-1];R[x-1]=k&-129;let T=J(R),O=b?l:o.ORDER;zt("point.y",T,te,O);let _=c(T*T),B=c(_-P),L=c(E*_-w),{isValid:g,value:y}=u(B,L);if(!g)throw new Error("bad point: invalid y coordinate");let S=(y&P)===P,I=(k&128)!==0;if(!b&&y===te&&I)throw new Error("bad point: x=0 and x_0=1");return I!==S&&(y=c(-y)),d.fromAffine({x:y,y:T})}static fromHex(h,b=false){return d.fromBytes(er(h),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,b=true){return m.createCache(this,h),b||this.multiply(Zt),this}assertValidity(){let h=this,{a:b,d:x}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:w,Y:E,Z:R,T:k}=h,T=c(w*w),O=c(E*E),_=c(R*R),B=c(_*_),L=c(T*b),g=c(_*c(L+O)),y=c(B+c(x*c(T*O)));if(g!==y)throw new Error("bad point: equation left != right (1)");let S=c(w*E),I=c(R*k);if(S!==I)throw new Error("bad point: equation left != right (2)")}equals(h){p(h);let{X:b,Y:x,Z:w}=this,{X:E,Y:R,Z:k}=h,T=c(b*k),O=c(E*w),_=c(x*k),B=c(R*w);return T===O&&_===B}is0(){return this.equals(d.ZERO)}negate(){return new d(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:h}=i,{X:b,Y:x,Z:w}=this,E=c(b*b),R=c(x*x),k=c(Zt*c(w*w)),T=c(h*E),O=b+x,_=c(c(O*O)-E-R),B=T+R,L=B-k,g=T-R,y=c(_*L),S=c(B*g),I=c(_*g),C=c(L*B);return new d(y,S,C,I)}add(h){p(h);let{a:b,d:x}=i,{X:w,Y:E,Z:R,T:k}=this,{X:T,Y:O,Z:_,T:B}=h,L=c(w*T),g=c(E*O),y=c(k*x*B),S=c(R*_),I=c((w+E)*(T+O)-L-g),C=S-y,A=S+y,F=c(g-b*L),$=c(I*C),fe=c(A*F),de=c(I*F),se=c(C*A);return new d($,fe,se,de)}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:b,f:x}=m.cached(this,h,w=>at(d,w));return at(d,[b,x])[0]}multiplyUnsafe(h){if(!s.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===te?d.ZERO:this.is0()||h===P?this:m.unsafe(this,h,b=>at(d,b))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return m.unsafe(this,i.n).is0()}toAffine(h){let b=this,x=h,{X:w,Y:E,Z:R}=b,k=b.is0();x==null&&(x=k?Jo:o.inv(R));let T=c(w*x),O=c(E*x),_=o.mul(R,x);if(k)return {x:te,y:P};if(_!==P)throw new Error("invZ was invalid");return {x:T,y:O}}clearCofactor(){return a===P?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y:b}=this.toAffine(),x=o.toBytes(b);return x[x.length-1]|=h&P?128:0,x}toHex(){return jt(this.toBytes())}toString(){return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=new it(d,s.BITS);return s.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var ct=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e;}static fromBytes(e){$t();}static fromHex(e){$t();}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 jt(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 Rr(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');let r=e,o=n;le(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:l}=t,c=r.outputLen,u=2*a.BYTES;if(c!==void 0&&(Y(c,"hash.outputLen"),c!==u))throw new Error(`hash.outputLen must be ${u}, got ${c}`);let f=o.randomBytes===void 0?tr:o.randomBytes,p=o.adjustScalarBytes===void 0?g=>g:o.adjustScalarBytes,d=o.domain===void 0?(g,y,S)=>{if(xe(S,"phflag"),y.length||S)throw new Error("Contexts/pre-hash are not supported");return g}:o.domain;function m(g){return l.create(J(g))}function v(g){let y=T.secretKey;D(g,T.secretKey,"secretKey");let S=D(r(g),2*y,"hashedSecretKey"),I=p(S.slice(0,y)),C=S.slice(y,2*y),A=m(I);return {head:I,prefix:C,scalar:A}}function h(g){let{head:y,prefix:S,scalar:I}=v(g),C=i.multiply(I),A=C.toBytes();return {head:y,prefix:S,scalar:I,point:C,pointBytes:A}}function b(g){return h(g).pointBytes}function x(g=Uint8Array.of(),...y){let S=K(...y);return m(r(d(S,D(g,void 0,"context"),!!s)))}function w(g,y,S={}){g=D(g,void 0,"message"),s&&(g=s(g));let{prefix:I,scalar:C,pointBytes:A}=h(y),F=x(S.context,I,g),$=i.multiply(F).toBytes(),fe=x(S.context,$,A,g),de=l.create(F+fe*C);if(!l.isValid(de))throw new Error("sign failed: invalid s");let se=K($,l.toBytes(de));return D(se,T.signature,"result")}let E={zip215:o.zip215};function R(g,y,S,I=E){let{context:C}=I,A=I.zip215===void 0?!!E.zip215:I.zip215,F=T.signature;g=D(g,F,"signature"),y=D(y,void 0,"message"),S=D(S,T.publicKey,"publicKey"),A!==void 0&&xe(A,"zip215"),s&&(y=s(y));let $=F/2,fe=g.subarray(0,$),de=J(g.subarray($,F)),se,un,fn;try{se=t.fromBytes(S,A),un=t.fromBytes(fe,A),fn=i.multiplyUnsafe(de);}catch{return false}if(!A&&se.isSmallOrder())return false;let Ur=x(C,fe,S,y);return un.add(se.multiplyUnsafe(Ur)).subtract(fn).clearCofactor().is0()}let k=a.BYTES,T={secretKey:k,publicKey:k,signature:2*k,seed:k};function O(g){return g=g===void 0?f(T.seed):g,D(g,T.seed,"seed")}function _(g){return et(g)&&g.length===T.secretKey}function B(g,y){try{return !!t.fromBytes(g,y===void 0?E.zip215:y)}catch{return false}}let L={getExtendedPublicKey:h,randomSecretKey:O,isValidSecretKey:_,isValidPublicKey:B,toMontgomery(g){let{y}=t.fromBytes(g),S=T.publicKey,I=S===32;if(!I&&S!==57)throw new Error("only defined for 25519 and 448");let C=I?a.div(P+y,P-y):a.div(y-P,y+P);return a.toBytes(C)},toMontgomerySecret(g){let y=T.secretKey;D(g,y);let S=r(g.subarray(0,y));return p(S).subarray(0,y)}};return Object.freeze(T),Object.freeze(L),Object.freeze({keygen:Er(O,b),getPublicKey:b,sign:w,verify:R,utils:L,Point:t,lengths:T})}var es=BigInt(0),X=BigInt(1),Or=BigInt(2);var ts=BigInt(5),ns=BigInt(8),be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Xt={p:be,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ns,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function rs(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=be,a=t*t%s*t%s,l=U(a,Or,s)*a%s,c=U(l,X,s)*t%s,u=U(c,ts,s)*c%s,f=U(u,e,s)*u%s,p=U(f,n,s)*f%s,d=U(p,r,s)*p%s,m=U(d,o,s)*d%s,v=U(m,o,s)*d%s,h=U(v,e,s)*u%s;return {pow_p_5_8:U(h,Or,s)*t%s,b2:a}}function os(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var Yt=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Qt(t,e){let n=be,r=M(e*e*e,n),o=M(r*r*e,n),s=rs(t*o).pow_p_5_8,i=M(t*r*s,n),a=M(e*i*i,n),l=i,c=M(i*Yt,n),u=a===t,f=a===M(-t,n),p=a===M(-t*Yt,n);return u&&(i=l),(f||p)&&(i=c),W(i,n)&&(i=M(-i,n)),{isValid:u||f,value:i}}var re=Tr(Xt,{uvRatio:Qt}),ne=re.Fp,Ar=re.Fn;function ss(t){return Rr(re,We,Object.assign({adjustScalarBytes:os,zip215:true},t))}var Br=ss({});var Jt=Yt;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var as=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var _r=t=>Qt(X,t),us=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Wt=t=>ne.create(J(t)&us);var oe=class t extends ct{static BASE=new t(re.BASE);static ZERO=new t(re.ZERO);static Fp=ne;static Fn=Ar;constructor(e){super(e);}static fromAffine(e){return new t(re.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoPoint expected")}init(e){return new t(e)}static fromBytes(e){V(e,32);let{a:n,d:r}=Xt,o=be,s=E=>ne.create(E),i=Wt(e);if(!or(ne.toBytes(i),e)||W(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),l=s(X+n*a),c=s(X-n*a),u=s(l*l),f=s(c*c),p=s(n*r*u-f),{isValid:d,value:m}=_r(s(p*f)),v=s(m*c),h=s(m*v*p),b=s((i+i)*v);W(b,o)&&(b=s(-b));let x=s(l*h),w=s(b*x);if(!d||W(w,o)||x===es)throw new Error("invalid ristretto255 encoding 2");return new t(new re(b,x,X,w))}static fromHex(e){return t.fromBytes(Oe(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,s=be,i=h=>ne.create(h),a=i(i(r+n)*i(r-n)),l=i(e*n),c=i(l*l),{value:u}=_r(i(a*c)),f=i(u*a),p=i(u*l),d=i(f*p*o),m;if(W(o*d,s)){let h=i(n*Jt),b=i(e*Jt);e=h,n=b,m=i(f*as);}else m=p;W(e*d,s)&&(n=i(-n));let v=i((r-n)*m);return W(v,s)&&(v=i(-v)),ne.toBytes(v)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:s}=e.ep,i=c=>ne.create(c),a=i(n*s)===i(r*o),l=i(r*s)===i(n*o);return a||l}is0(){return this.equals(t.ZERO)}};Object.freeze(oe.BASE);Object.freeze(oe.ZERO);Object.freeze(oe.prototype);Object.freeze(oe);var Lr=`-----BEGIN PUBLIC KEY-----
11
+ MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
12
+ -----END PUBLIC KEY-----`;function Mr(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 en(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4?"=".repeat(4-e.length%4):"";return Mr(e+n)}function ds(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=Mr(e);return n.subarray(n.length-32)}var ps=new TextEncoder,Dr=new TextDecoder;function ms(t){return typeof t=="object"&&t!==null&&"keys"in t}function tn(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(Dr.decode(en(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(ms(e)){let u=typeof i.kid=="string"?i.kid:e.defaultKid,f=e.keys[u];if(!f)return {ok:false,reason:`unknown key id "${u}"`};a=f;}else {if(!e)return {ok:false,reason:"no verification key"};a=e;}let l;try{if(l=ds(a),l.length!==32)return {ok:!1,reason:"invalid public key"}}catch{return {ok:false,reason:"invalid public key"}}let c=false;try{c=Br.verify(en(s),ps.encode(`${r}.${o}`),l);}catch{return {ok:false,reason:"signature verification error"}}return c?{ok:true,header:i,payloadBytes:en(o)}:{ok:false,reason:"bad signature"}}function nn(t,e){let n=tn(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(Dr.decode(n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function rn(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 nc(t,e,n={}){let r=nn(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=rn(o,s,n.revoked);return i==="revoked"?{status:i,payload:o,reason:"license revoked"}:{status:i,payload:o}}var jr="BVSALA-REVOC",hs=300,gs=new TextDecoder;function Pr(t,e,n={}){let r=c=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:c}),o=tn(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");if(o.header?.typ!==jr)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${jr})`);let s;try{s=JSON.parse(gs.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof s.seq!="number"||typeof s.asOf!="number"||!Array.isArray(s.revoked))return r("malformed revocation payload");let i=n.minSeq??0;if(s.seq<i)return r(`stale/rolled-back list (seq ${s.seq} < ${i})`);let a=n.nowSeconds??Math.floor(Date.now()/1e3),l=n.maxSkewSeconds??hs;return s.asOf>a+l?r(`asOf too far in the future (${s.asOf} > ${a+l})`):{ok:true,seq:s.seq,asOf:s.asOf,revoked:new Set(s.revoked)}}var ye=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=nn(t,e),i=s.signatureValid?s.payload:void 0,a=new Set(i?.features??[]),l=()=>{if(!i)return "invalid";let u=rn(i,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(u==="active"||u==="grace")){let f=i.expires_at+i.grace_days*86400,p=Math.min(o,f),d=Math.max(n.revocation.lastContactAt,p);if(r()-d>n.maxStalenessSeconds)return "expired"}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,r()+86400)}}}function Fr(t,e,n){return lt(t,e,{revocation:new ye,...n?{now:n}:{}})}var ve={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4};function xs(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 bs=10,ut=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??ve.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>=bs&&(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");a&&(this.lastEtag=a);let l=await i.json();if(!l.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let c=Pr(l.list,this.opts.publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??ve.maxSkewSeconds});if(!c.ok){this.opts.onEvent?.({type:"rejected",reason:c.reason??"rejected"});return}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});}finally{clearTimeout(o),this.controller=null;}}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)return;let e=xs({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 Le=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;flushing=false;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&&o.status>=500&&this.requeue(n);}catch{this.requeue(n);}finally{this.flushing=false;}}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 on(){return globalThis.process}function ys(t){if(t.KUBERNETES_SERVICE_HOST)return true;let e=t.HOSTNAME;return e?/^[0-9a-f]{12}$/.test(e)?true:/-[0-9a-z]{5,10}-[0-9a-z]{5}$/.test(e):false}function vs(){let t=on();if(!t||!t.env)return;let e=t.env,n=ys(e)?void 0:e.HOSTNAME??e.COMPUTERNAME,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 ws=["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 sn(){let t=on()?.env;if(!t)return false;for(let e of ws){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function Ss(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let i=await n.subtle.importKey("raw",r.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",i,r.encode(e));return [...new Uint8Array(a)].map(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 an(t){let n=on()?.env?.BVSALA_SEAT_ID;if(n&&ks.test(n))return n;let r=vs();if(!r)return;let o=await Ss(t,r);if(o)return `m-${o.slice(0,32)}`}var ks=/^[A-Za-z0-9._:/-]{1,128}$/;var zr={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function Nr(t){return {exactCache:t.exactCache??new je,semanticCache:t.semanticCache,singleflight:t.singleflight??new Pe,resolvers:t.resolvers??wn(),router:t.router??new Fe,toolSelector:t.toolSelector??new ze,formatSelector:t.formatSelector??new Ue({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new He,constraintBackends:t.constraintBackends??[]}}var ft=class{deps;config;now;generateId;illustrativePriceWarned=false;contratosQueIncumplen;constructor(e){this.config=e,this.deps=Nr(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>dt()),this.contratosQueIncumplen=e.constraintMemory??new Set;}async generate(e){this.assertLicensed();try{return await this.generateOptimized(e)}catch(n){if(n instanceof ie||this.config.failOpen===false)throw n;return await this.failOpenDirect(e,n)}}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(`BiVelio license is not active${n?` (${n})`:""}. Renew your subscription at https://savings.bivelio.com`,n)}throw e?new ie("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 ie("No BiVelio license configured. Pass { licenseKey } from your subscription (or { devUnlicensed: true } for local dev). Get a key at https://savings.bivelio.com")}async generateOptimized(e){this.assertLicensed();let n=new Re(this.now),r=new me,o=xt(e),s=bt(o),i=e.savings??{},a=this.costModelFor(e.model);n.record("canonicalize","done",{tenant:o.tenantId,contract:o.contractId}),n.record("policy",s.reasons.join("; ")||"no restrictions",{allowExactCache:s.allowExactCache,allowSemanticCache:s.allowSemanticCache});let l=this.tokensFor(this.assembleBaselinePrompt(e),e),c=e.response?.maxOutputTokens??256;if(r.baselineInput=l,r.baselineOutput=c,r.baselineTools=e.tools?.length??0,i.deterministicResolvers!==false){let d=this.deps.resolvers.try(o);if(d)return r.avoidCall(l,this.tokensFor(d.text,e)),n.record("resolver",d.resolver,{avoided:true}),this.finish(e,o,{text:d.text,data:d.data,storedAtMs:this.now()},"deterministic",r,a,n,Me(),De())}let u=hn(o);if(s.allowExactCache&&i.exactCache!==false){let d=await this.deps.exactCache.get(u);if(d)return r.avoidCall(l,this.tokensFor(d.text,e)),n.record("exact-cache","hit",{ageMs:this.now()-d.storedAtMs}),this.finish(e,o,d,"exact",r,a,n,Me(),De(),this.now()-d.storedAtMs);n.record("exact-cache","miss");}let f=gn(o),p=()=>this.expensivePath(e,o,s,i,r,a,n,u,l);if(s.allowSingleflight&&i.singleflight!==false){let{value:d,coalesced:m}=await this.deps.singleflight.run(f,p);return m?(n.record("singleflight","coalesced",{key:f}),this.asCoalescedFollower(d,l,this.tokensFor(d.text??"",e),a)):d}return p()}async expensivePath(e,n,r,o,s,i,a,l,c){let u=this.entitled("semantic_cache");if(r.allowSemanticCache&&o.semanticCache&&this.deps.semanticCache&&!u&&a.record("semantic-cache","degraded: feature not licensed (free tier)"),r.allowSemanticCache&&o.semanticCache&&this.deps.semanticCache&&u){let g=await this.deps.semanticCache.find(n);if(g)return s.avoidCall(c,this.tokensFor(g.record.answer.text,e)),a.record("semantic-cache","hit",{confidence:g.confidence,similarity:g.similarity}),this.finish(e,n,g.record.answer,"semantic",s,i,a,Me(),De(),g.ageMs,g.confidence);a.record("semantic-cache","miss");}let f=o.router===false?Me():this.deps.router.classify(n);a.record("router",f.executionClass,{confidence:f.confidence,reason:f.reason});let p=this.deps.toolSelector.select(n.normalizedText,e.tools,f.executionClass);s.actualTools=p.tools.length,p.droppedIds.length&&a.record("tool-selector",p.reason,{dropped:p.droppedIds}),s.baselineRetrieval=f.rounds;let d=await kn({execution:f.executionClass,query:n.normalizedText,maxRounds:e.retrieval?.maxRounds??f.rounds,maxDocuments:e.retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});s.actualRetrieval=d.rounds,d.retrievedCount>0&&a.record("retrieval",`kept ${d.keptCount}/${d.retrievedCount}`,{rounds:d.rounds});let m=De(),v=[...e.messages];if(d.docs.length>0){let g=d.docs.map((y,S)=>`[${y.source??y.id??`doc${S+1}`}]
13
+ ${y.text}`).join(`
14
+
15
+ `);v.push({role:"system",content:`Retrieved context \u2014 answer using only this evidence and cite sources by [id]:
16
+
17
+ ${g}`});}let h=$r(e),b=e.response?.maxOutputTokens!=null?Math.floor(e.response.maxOutputTokens*3.2):null,x=this.contratosQueIncumplen.has(h)?ln(e.response?.schema,"",b):"";if(x&&v.push({role:"system",content:`JSON limits (not API-enforced): ${x}`}),e.structuredData!==void 0){let g=JSON.stringify(e.structuredData),y=this.tokensFor(g,e);if(o.serialization!==false){m=this.deps.formatSelector.choose(e.structuredData,{model:e.model,...e.tokenizer?{tokenizer:e.tokenizer}:{}});let S=this.tokensFor(m.encoded+m.instruction,e);s.compress(y,S),Vr(v,{role:"system",content:(m.instruction?m.instruction+`
18
+ `:"")+m.encoded}),a.record("serialization",m.chosen,{reason:m.reason,jsonTokens:y,chosenTokens:S});}else Vr(v,{role:"system",content:g}),a.record("serialization","json-compact",{reason:"format selector disabled; sent compact JSON"});}if((o.compression===true||o.compression==="auto")&&r.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let g=0,y=0,S=[];for(let I of v){let C=this.tokensFor(I.content,e),A=await this.config.compressor.compress({text:I.content}),F=!A.skipped&&A.fidelityPassed,$=F?this.tokensFor(A.compressed,e):C;F&&$<C?(S.push({...I,content:A.compressed}),g+=C,y+=$):S.push(I);}y<g?(v=S,s.compress(g,y),a.record("compression","applied",{before:g,after:y})):a.record("compression","skipped (no fidelity-passed net reduction)");}let w=e.response?.schema,E=w?Ln(e.model,w,this.deps.constraintBackends):{backend:"none",reason:"no output contract"};a.record("constraints",E.backend,{reason:E.reason});let R=this.now(),k=await this.config.provider.generate({model:e.model,messages:v,...p.tools.length?{tools:p.tools}:{},...w?{schema:w}:{},...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{},constraintBackend:E.backend});s.actualLlm=1,s.actualInput=k.usage.inputTokens,s.actualOutput=k.usage.outputTokens,s.sentInputLocal=this.tokensFor(this.assemblePromptText(v,p.tools),e),s.removedInputLocal=Math.max(0,c-s.sentInputLocal),s.estimatorExact=this.estimatorEsExacto(e),k.usage.cachedInputTokens&&s.providerCached(k.usage.cachedInputTokens);let T=k.text,O=true;if(w){let g=cn(k.text),y=g.ok?ke(g.value,w):{valid:false,errors:[{path:"$",message:"not valid JSON"}]};!y.valid&&Ts(y.errors)&&this.contratosQueIncumplen.add($r(e));let S=k.finishReason==="length",I=!y.valid&&y.errors.some(C=>/not a valid regular expression/.test(C.message));if(!y.valid&&I)a.record("validation","repair-skipped",{reason:"schema defect (uncompilable pattern); no output can satisfy it, a retry is a wasted call",errors:y.errors}),Ee("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(!y.valid&&S)a.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same cap would truncate again",maxOutputTokens:e.response?.maxOutputTokens??null,outputTokens:k.usage.outputTokens}),Ee("salida-truncada","[bvsala] La respuesta se cort\xF3 al agotar `maxOutputTokens`"+(e.response?.maxOutputTokens!=null?` (${e.response.maxOutputTokens})`:"")+", as\xED que no valida contra el contrato. NO se reintenta: con el mismo tope volver\xEDa a cortarse y ser\xEDa una llamada pagada para el mismo fallo. Sube `maxOutputTokens` o reduce lo que pide el contrato.");else if(!y.valid&&E.backend==="none"){s.retries=1,a.record("validation","repair-attempt",{errors:y.errors});let C=y.errors.slice(0,5).map($=>`- ${$.path}: ${$.message}`).join(`
19
+ `),A=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
20
+
21
+ Previous reply:
22
+ ${k.text}
23
+
24
+ Problems found:
25
+ ${C}
26
+
27
+ Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}];k=await this.config.provider.generate({model:e.model,messages:A,schema:w,...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{}}),s.actualLlm=2,s.actualInput+=k.usage.inputTokens,s.actualOutput+=k.usage.outputTokens,s.repairOutput+=k.usage.outputTokens,s.sentInputLocal+=this.tokensFor(this.assemblePromptText(A),e);let F=cn(k.text);y=F.ok?ke(F.value,w):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},F.ok&&(T=F.value);}else g.ok&&(T=g.value);O=y.valid,a.record("validation",O?"valid":"invalid");}let _=this.now()-R,B=Es(T),L={text:k.text,data:T,rendered:B,storedAtMs:this.now()};try{r.allowExactCache&&o.exactCache!==!1&&await this.deps.exactCache.set(l,L,this.config.exactCacheTtlMs??1440*60*1e3),r.allowSemanticCache&&o.semanticCache&&this.deps.semanticCache&&await this.deps.semanticCache.store(n,L);}catch(g){a.record("cache-write","failed (non-fatal; answer already served)",{error:g instanceof Error?g.message:String(g)});}return this.finish(e,n,L,"miss",s,i,a,f,m,void 0,void 0,O,E.backend,_)}finish(e,n,r,o,s,i,a,l,c,u,f,p,d="none",m=0){let v=e.response?.schema,h=p??(v?ke(r.data,v).valid:true),b=this.buildReport(e,n,o,s,i,a,l,c,u,f,h,d,m);return {requestId:b.requestId,data:r.data,text:r.text,...r.rendered!==void 0?{rendered:r.rendered}:{},report:b}}buildReport(e,n,r,o,s,i,a,l,c,u,f,p,d){let m=o.estimateCost(s),v=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}:{},...c!==void 0?{ageMs:c}:{}},routing:{executionClass:a.executionClass,confidence:a.confidence,rounds:o.actualRetrieval,reason:a.reason},serialization:{chosen:l.chosen,candidateTokens:l.candidateTokens,instructionOverheadTokens:l.instructionOverheadTokens},constraints:{backend:p,schemaVersion:n.schemaVersion,structurallyValid:f},quality:{...r!=="miss"?{freshnessPassed:!bt(n).requiresFreshData}:{}},cost:m,latencyMs:{total:v,preprocessing:Math.max(0,v-d),provider:d},traces:i.all()}}async failOpenDirect(e,n){let r=new Re(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 me,s=this.costModelFor(e.model),i;try{i=xt(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;o.baselineLlm=1,o.actualLlm=1,o.actualInput=c.usage.inputTokens,o.actualOutput=c.usage.outputTokens,o.baselineInput=c.usage.inputTokens,o.baselineOutput=c.usage.outputTokens,c.usage.cachedInputTokens&&o.providerCached(c.usage.cachedInputTokens);let f=c.text,p=true;if(a){let m=cn(c.text);p=m.ok?ke(m.value,a).valid:false,m.ok&&(f=m.value);}let d=this.buildReport(e,i,"miss",o,s,r,Me(),De(),void 0,void 0,p,"none",u);return {requestId:d.requestId,data:f,text:c.text,report:d}}asCoalescedFollower(e,n,r,o){let s=new me;s.avoidCall(n,r);let i=s.estimateCost(o),a=this.generateId();return {...e,requestId:a,report:{...e.report,requestId:a,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(JSON.stringify({type:"function",function:{name:s.id,...s.description?{description:s.description}:{},parameters:s.parameters??{type:"object",properties:{}}}}));return o.join(`
28
+ `)}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)}costModelFor(e){let n=this.config.costModels;if(n){let r=n[e];if(r)return r;let o=e.indexOf("/");if(o>=0){let s=n[e.slice(o+1)];if(s)return s}}return this.config.defaultCostModel?this.config.defaultCostModel:(this.illustrativePriceWarned||(this.illustrativePriceWarned=true,console.warn(`[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 } } }.`)),zr)}};function cn(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}function Es(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function Me(){return {executionClass:"NO_RETRIEVAL",confidence:1,reason:"n/a (short-circuited)",rounds:0}}function De(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,reason:"no structured payload"}}function ln(t,e="",n=null){if(t==null||typeof t!="object")return "";let r=t,o=[],s=e||"the value",i=m=>typeof r[m]=="number"?r[m]:null,a=i("maxLength"),l=i("minLength"),c=i("maxItems"),u=i("minItems"),f=i("maximum"),p=i("minimum");if(a!=null){let m=n!=null?Math.min(a,n):a;o.push(`${s}<=${m}ch`);}l!=null&&o.push(`${s}>=${l}ch`),c!=null&&o.push(`${s}<=${c} items`),u!=null&&o.push(`${s}>=${u} items`),f!=null&&o.push(`${s}<=${f}`),p!=null&&o.push(`${s}>=${p}`),typeof r.pattern=="string"&&o.push(`${s} matches /${r.pattern}/`);let d=r.properties;if(d&&typeof d=="object")for(let[m,v]of Object.entries(d)){let h=ln(v,e?`${e}.${m}`:m,n);h&&o.push(h);}if(r.items!==void 0){let m=ln(r.items,`${s} entries`,n);m&&o.push(m);}return o.join("; ")}function $r(t){let e=t.response;return e?e.contractId??e.version??JSON.stringify(e.schema??{}).slice(0,200):""}function Ts(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.test(e.message))}function Vr(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);}var Rs=6*3600;function sl(t){t.licenseGate&&(console.warn("[bvsala] Se ignora el `licenseGate` inyectado: en el paquete publicado la licencia solo se acepta v\xEDa `licenseKey` verificado contra la clave de BiVelio."),t={...t,licenseGate:void 0});let n={...t,tokenizer:t.tokenizer??dn},r;if(t.licenseKey&&!t.licenseGate){let i=Lr;if(t.licenseServerUrl){let a=new ye,l=lt(t.licenseKey,i,{revocation:a,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??Rs});n.licenseGate=l;let c=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;r=new ut({url:c,publicKeyPem:i,snapshot:a,getRefreshAfter:()=>l.refreshAfter?.(),...t.now?{nowSeconds:()=>Math.floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.licensePollIntervalSeconds}:{},...t.licenseRevocation??{}}),r.start();}else n.licenseGate=Fr(t.licenseKey,i,t.now);}let o=new ft(n),s;if(t.serviceAccountKey&&t.metering?.enabled!==false){let i=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/usage`:void 0);if(i){s=new Le({url:i,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}:{}});let a=t.metering?.ci??sn();if(t.metering?.seatId)s.setSeat(t.metering.seatId,a);else {let l=s;an(t.serviceAccountKey).then(c=>l.setSeat(c,a)).catch(()=>{});}s.start();}}return {generate:async i=>{let a=await o.generate(i);if(s)try{s.record(a.report);}catch{}return a},close:()=>{r?.stop(),s?.stop();}}}var fl="0.1.0";/*! Bundled license information:
29
+
30
+ @noble/curves/utils.js:
31
+ @noble/curves/abstract/modular.js:
32
+ @noble/curves/abstract/curve.js:
33
+ @noble/curves/abstract/edwards.js:
34
+ @noble/curves/ed25519.js:
35
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
36
+ */export{fl as BV_SALA_VERSION,zr as DEFAULT_COST_MODEL,Lr as EMBEDDED_PUBLIC_KEY,ht as ExactTokenizer,Fe as ExecutionRouter,Ue as FormatSelector,pt as HeuristicEstimator,je as InMemoryExactCache,vn as InMemorySemanticCache,ie as LicenseError,qr as MODELOS_POR_CODIFICACION,Rt as MockProvider,Fn as OpenAICompatibleProvider,yt as ResolverRegistry,ut as RevocationPoller,ye as RevocationSnapshot,me as SavingsLedger,He as SchemaRegistry,Pe as Singleflight,Ro as TOON_INSTRUCTION,mt as TokenizerRegistry,ze as ToolSelector,Re as TraceCollector,Le as UsageEmitter,ho as adaptiveK,so as arithmeticResolver,hn as buildExactKey,gn as buildInflightKey,xt as canonicalize,xs as computeNextDelay,eo as cosine,wn as createDefaultResolvers,Bs as createHandoff,la as createMockProvider,sl as createSavingsLayer,Io as createToonSerializer,An as csvSerializer,Tn as decodeToon,mo as dedupe,dn as defaultTokenizerRegistry,an as deriveSeatId,rn as deriveStatus,sn as detectCi,ki as emptyState,ko as encodeToon,co as evalArithmetic,bt as evaluatePolicy,kn as executeRetrievalPlan,Fr as gateFromKey,pe as heuristicEstimator,ms as isKeyset,Te as isStrictCompatible,En as jsonCompactSerializer,oo as keyTokensMatch,lt as liveGateFromKey,Ei as mergeDelta,na as noopCompressor,Jr as normalizeText,Ti as projectContext,Gi as providerNativeBackend,dt as randomId,Ns as registrarTokenizadorExacto,xo as renderState,Ln as resolveConstraintBackend,Nr as resolveDependencies,nc as resolveLicense,he as sha256,ea as shouldCompress,we as stableStringify,_n as toonSerializer,Ve as uniformColumns,ke as validateAgainstSchema,tn as verifyCompactSignature,nn as verifyLicenseToken,Pr as verifyRevocationList,ta as withProtectedSpans};
package/package.json ADDED
@@ -0,0 +1,96 @@
1
+ {
2
+ "name": "@bivelio/savings-layer",
3
+ "version": "0.1.0",
4
+ "description": "BV-SALA — a provider-neutral LLM execution optimizer. A decision layer in front of any LLM provider that, for every request, picks the cheapest execution that preserves required quality. Avoid the call, avoid retrieval, eliminate context, compress, constrain — with four separate ledgers of savings. Proprietary and confidential — property of BiVelio Inc.",
5
+ "type": "module",
6
+ "license": "SEE LICENSE IN LICENSE",
7
+ "author": "BiVelio Inc.",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "homepage": "https://github.com/BiVelio/bivelio-savings-layer",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/BiVelio/bivelio-savings-layer.git"
15
+ },
16
+ "bugs": {
17
+ "url": "https://github.com/BiVelio/bivelio-savings-layer/issues"
18
+ },
19
+ "keywords": [
20
+ "llm",
21
+ "gateway",
22
+ "cost-optimization",
23
+ "prompt-compression",
24
+ "semantic-cache",
25
+ "singleflight",
26
+ "adaptive-rag",
27
+ "toon",
28
+ "constrained-decoding",
29
+ "structured-output",
30
+ "token-accounting",
31
+ "bivelio"
32
+ ],
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "import": "./dist/index.js"
37
+ },
38
+ "./package.json": "./package.json"
39
+ },
40
+ "main": "./dist/index.js",
41
+ "module": "./dist/index.js",
42
+ "types": "./dist/index.d.ts",
43
+ "files": [
44
+ "dist",
45
+ "README.md",
46
+ "LICENSE"
47
+ ],
48
+ "engines": {
49
+ "node": ">=20.0.0"
50
+ },
51
+ "scripts": {
52
+ "build": "tsup",
53
+ "build:packages": "pnpm -r --filter=./packages/* build",
54
+ "build:services": "pnpm -r --filter=./services/* build",
55
+ "build:all": "pnpm run build:packages && pnpm run build:services && pnpm run build",
56
+ "typecheck": "tsc --noEmit",
57
+ "typecheck:packages": "pnpm -r --filter=./packages/* --filter=./services/* typecheck",
58
+ "typecheck:all": "pnpm run typecheck && pnpm run typecheck:packages",
59
+ "test": "vitest run",
60
+ "test:watch": "vitest",
61
+ "lint": "tsc --noEmit",
62
+ "example:basic": "BVSALA_DEV_OPEN=1 tsx examples/basic/index.ts",
63
+ "example:handoff": "BVSALA_DEV_OPEN=1 tsx examples/multi-agent/handoff.ts",
64
+ "example:serialization": "BVSALA_DEV_OPEN=1 tsx examples/serialization/format-selector.ts",
65
+ "example:licensed": "tsx examples/licensing/licensed.ts",
66
+ "license:demo": "tsx examples/licensing/demo.ts",
67
+ "example:revocation": "tsx examples/licensing/revocation.ts",
68
+ "demo:e2e": "tsx examples/licensing/e2e.ts",
69
+ "demo:install": "bash examples/licensing/install-demo.sh",
70
+ "demo": "BVSALA_DEV_OPEN=1 tsx --env-file-if-exists=.env.bench benchmarks/run.ts",
71
+ "ablation": "BVSALA_DEV_OPEN=1 tsx --env-file-if-exists=.env.bench benchmarks/ablation.ts",
72
+ "ab": "BVSALA_DEV_OPEN=1 tsx --env-file-if-exists=.env.bench benchmarks/ab-live.ts",
73
+ "web:build": "tsup",
74
+ "web:dev": "node apps/web/serve.mjs",
75
+ "prepublishOnly": "pnpm run build",
76
+ "ab:publish": "tsx benchmarks/publish.ts"
77
+ },
78
+ "devDependencies": {
79
+ "@noble/curves": "^2.2.0",
80
+ "@types/node": "^22.10.2",
81
+ "gpt-tokenizer": "^3.4.0",
82
+ "tsup": "^8.3.5",
83
+ "tsx": "^4.19.2",
84
+ "typescript": "^5.7.2",
85
+ "vitest": "^2.1.8"
86
+ },
87
+ "packageManager": "pnpm@10.17.1",
88
+ "peerDependencies": {
89
+ "gpt-tokenizer": "^3"
90
+ },
91
+ "peerDependenciesMeta": {
92
+ "gpt-tokenizer": {
93
+ "optional": true
94
+ }
95
+ }
96
+ }