@bivelio/savings-layer 0.4.13 → 0.4.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -9
- package/dist/gateway/bin.js +22 -20
- package/dist/index.d.ts +59 -2
- package/dist/index.js +621 -611
- package/package.json +4 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Ys="2026-09-06",un={"gpt-4.1":{inputPer1k:.002,outputPer1k:.008,cachedInputPer1k:5e-4},"gpt-4.1-mini":{inputPer1k:4e-4,outputPer1k:.0016,cachedInputPer1k:1e-4},"gpt-4.1-nano":{inputPer1k:1e-4,outputPer1k:4e-4,
|
|
2
2
|
cachedInputPer1k:25e-6},"gpt-4o":{inputPer1k:.0025,outputPer1k:.01,cachedInputPer1k:.00125},"gpt-4o-mini":{inputPer1k:15e-5,outputPer1k:6e-4,cachedInputPer1k:75e-6},"gpt-4-turbo":{inputPer1k:.01,outputPer1k:.03},
|
|
3
3
|
"gpt-4":{inputPer1k:.03,outputPer1k:.06},"gpt-3.5-turbo":{inputPer1k:5e-4,outputPer1k:.0015},"gpt-5":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gpt-5-codex":{inputPer1k:.00125,outputPer1k:.01,
|
|
4
4
|
cachedInputPer1k:125e-6},"gpt-5-mini":{inputPer1k:25e-5,outputPer1k:.002,cachedInputPer1k:25e-6},"gpt-5-nano":{inputPer1k:5e-5,outputPer1k:4e-4,cachedInputPer1k:5e-6},"gpt-5.1-codex":{inputPer1k:.00125,
|
|
@@ -10,276 +10,277 @@ outputPer1k:.0012,cachedInputPer1k:2e-5},"gpt-5.6-sol":{inputPer1k:.004,outputPe
|
|
|
10
10
|
inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4-6":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4-7":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},
|
|
11
11
|
"claude-opus-4-8":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-5":{inputPer1k:.005,outputPer1k:.025,cachedInputPer1k:5e-4},"claude-opus-4":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},
|
|
12
12
|
"claude-sonnet-4-5":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-4-6":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-sonnet-5":{inputPer1k:.002,outputPer1k:.01,
|
|
13
|
-
cachedInputPer1k:2e-4},"claude-fable-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-
|
|
14
|
-
outputPer1k:.
|
|
15
|
-
-
|
|
13
|
+
cachedInputPer1k:2e-4},"claude-fable-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-fable-5-1":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5-1":{inputPer1k:.01,
|
|
14
|
+
outputPer1k:.05,cachedInputPer1k:25e-5},"claude-mythos-5":{inputPer1k:.01,outputPer1k:.05,cachedInputPer1k:.001},"claude-sonnet-4":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-haik\
|
|
15
|
+
u-4-5":{inputPer1k:.001,outputPer1k:.005,cachedInputPer1k:1e-4},"claude-3-5-sonnet":{inputPer1k:.003,outputPer1k:.015,cachedInputPer1k:3e-4},"claude-3-5-haiku":{inputPer1k:8e-4,outputPer1k:.004,cachedInputPer1k:8e-5},
|
|
16
|
+
"claude-3-opus":{inputPer1k:.015,outputPer1k:.075,cachedInputPer1k:.0015},"claude-3-haiku":{inputPer1k:25e-5,outputPer1k:.00125,cachedInputPer1k:3e-5},"gemini-3.7-flash":{inputPer1k:75e-5,outputPer1k:.00375,
|
|
16
17
|
cachedInputPer1k:75e-6},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5},"gemini-3.1-pro-\
|
|
17
18
|
preview":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}};
|
|
18
|
-
function
|
|
19
|
-
""&&c!=="-"&&c!=="."&&c!=="_")continue;let l=s.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return t[a]}}function
|
|
20
|
-
return un
|
|
21
|
-
16;s++)e[s]=(s<6?
|
|
22
|
-
-${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var
|
|
23
|
-
match(/\n/g)??[]).length;
|
|
24
|
-
Math.ceil(e.length/4))}},
|
|
25
|
-
return this.modelToTokenizer.set(e,n),this}resolve(e){let n=e.tokenizer?this.estimators.get(e.tokenizer):void 0;if(n)return n;if(e.model){let
|
|
26
|
-
get(
|
|
27
|
-
"gpt-4.1-nano","o1","o1-mini","o3","o3-mini","o4-mini"],cl100k_base:["gpt-4","gpt-4-turbo","gpt-3.5-turbo","text-embedding-3-small","text-embedding-3-large"]};async function
|
|
28
|
-
["o200k_base","cl100k_base"],
|
|
29
|
-
[])t.mapModel(i,
|
|
30
|
-
this.cascadeInput+=Math.max(0,e.inputTokens),this.cascadeOutput+=Math.max(0,e.outputTokens),this.extraCostUsd+=Math.max(0,e.inputTokens)/1e3*n.inputPer1k+Math.max(0,e.outputTokens)/1e3*n.outputPer1k;}cacheWritePremium(e,n,
|
|
31
|
-
let
|
|
19
|
+
function dn(t,e,n){if(!n)return;let o=t[n];if(o)return o;let r=n.lastIndexOf("/"),s=r>=0?n.slice(r+1):n,i=t[s];if(i)return i;for(let a of e){if(!s.startsWith(a))continue;let c=s.charAt(a.length);if(c!==
|
|
20
|
+
""&&c!=="-"&&c!=="."&&c!=="_")continue;let l=s.slice(a.length+1);if(!(/^\d/.test(l)&&!/^\d{4}/.test(l)))return t[a]}}function pn(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var Zs=pn(un);function bt(t){
|
|
21
|
+
return dn(un,Zs,t)}var Xs=0;function fn(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let o=++Xs,r=Date.now?Date.now():0;for(let s=0;s<
|
|
22
|
+
16;s++)e[s]=(s<6?o>>>s*8:r>>>(s-6)*8)&255;}e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=[];for(let o=0;o<16;o++)n.push(e[o].toString(16).padStart(2,"0"));return `${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}\
|
|
23
|
+
-${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var Hc=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function Jc(t){return {v:1,task:t.task,goal:t.goal,rules:t.rules??[],facts:t.facts??[],refs:t.refs??[],...t.delta?{delta:t.delta}:{},outputContract:t.outputContract}}var mn=class{id;exact=false;constructor(e="heuristic"){this.id=e;}count(e){if(e.length===0)return 0;let n=e.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],o=0;for(let r of n){let s=r[0];if(/\s/.test(s)){let i=(r.
|
|
24
|
+
match(/\n/g)??[]).length;o+=i+Math.floor(Math.max(0,r.length-1)/2);}else /[A-Za-z]/.test(s)?o+=Math.max(1,Math.ceil(r.length/4)):/\d/.test(s)?o+=Math.max(1,Math.ceil(r.length/2)):o+=1;}return Math.max(o,
|
|
25
|
+
Math.ceil(e.length/4))}},Ne=new mn;var hn=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=Ne){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){
|
|
26
|
+
return this.modelToTokenizer.set(e,n),this}resolve(e){let n=e.tokenizer?this.estimators.get(e.tokenizer):void 0;if(n)return n;if(e.model){let o=this.modelToTokenizer.get(e.model);if(o){let r=this.estimators.
|
|
27
|
+
get(o);if(r)return r}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},Mo=new hn;var gn=class{constructor(e,n){this.encoder=n;this.id=e;}encoder;id;exact=true;count(e){return e.length===0?0:this.encoder.encode(e).length}},Bo={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini",
|
|
28
|
+
"gpt-4.1-nano","o1","o1-mini","o3","o3-mini","o4-mini"],cl100k_base:["gpt-4","gpt-4-turbo","gpt-3.5-turbo","text-embedding-3-small","text-embedding-3-large"]};async function Qs(t,e={}){let n=e.codificaciones??
|
|
29
|
+
["o200k_base","cl100k_base"],o=false;for(let r of n){let s;try{s=await import(`gpt-tokenizer/encoding/${r}`);}catch{continue}if(typeof s.encode=="function"){t.register(new gn(r,s)),o=true;for(let i of Bo[r]??
|
|
30
|
+
[])t.mapModel(i,r),t.mapModel(`openai/${i}`,r);}}return o}var tl=Bo,nl=Qs;var je=class{avoidedLlm=0;baselineLlm=1;actualLlm=0;baselineRetrieval=0;actualRetrieval=0;baselineTools=0;actualTools=0;retries=0;baselineInput=0;actualInput=0;eliminatedInput=0;compressedInput=0;baselineOutput=0;actualOutput=0;eliminatedOutput=0;providerCachedInput=0;cacheWriteInputTokens=0;cacheWritePremiumUsd=0;sentInputLocal=0;removedInputLocal=0;elididoLocal=0;estimatorExact=false;repairOutput=0;repairInput=0;discoveryInput=0;discoveryOutput=0;extraCostUsd=0;cascadeInput=0;cascadeOutput=0;cascadeAttempt(e,n){
|
|
31
|
+
this.cascadeInput+=Math.max(0,e.inputTokens),this.cascadeOutput+=Math.max(0,e.outputTokens),this.extraCostUsd+=Math.max(0,e.inputTokens)/1e3*n.inputPer1k+Math.max(0,e.outputTokens)/1e3*n.outputPer1k;}cacheWritePremium(e,n,o){
|
|
32
|
+
let r=Math.max(0,e);this.cacheWriteInputTokens+=r,this.cacheWritePremiumUsd+=r/1e3*o.inputPer1k*Math.max(0,n-1);}compressionReport=void 0;eliminate(e){this.eliminatedInput+=Math.max(0,e);}compress(e,n){
|
|
32
33
|
this.compressedInput+=Math.max(0,e-n);}providerCached(e){this.providerCachedInput+=Math.max(0,e);}avoidCall(e,n){this.avoidedLlm+=1,this.actualLlm=0,this.baselineInput=e,this.baselineOutput=n;}get publishedBaselineOutput(){
|
|
33
|
-
return this.avoidedLlm===0?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):this.baselineOutput}estimateCost(e){let n=this.avoidedLlm===0,
|
|
34
|
-
this.sentInputLocal>0){let d=this.actualInput/this.sentInputLocal,f=Math.max(0,this.actualInput-this.repairInput-this.discoveryInput);this.baselineInput=f+Math.round(d*this.removedInputLocal),
|
|
35
|
-
0?"measured":"estimated";}else this.actualInput>0?(this.baselineInput=this.actualInput,
|
|
36
|
-
this.baselineOutput,s=e.cachedInputPer1k??e.inputPer1k,i=Math.min(this.providerCachedInput,this.actualInput),a=d=>Math.max(0,d-i)/1e3*e.inputPer1k+i/1e3*s,c=a(this.baselineInput)+
|
|
37
|
-
this.actualInput)+this.actualOutput/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd,u=c===0?0:1-l/c;return {baselineEstimate:
|
|
38
|
-
return Math.round(t*1e10)/1e10}function
|
|
34
|
+
return this.avoidedLlm===0?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):this.baselineOutput}estimateCost(e){let n=this.avoidedLlm===0,o="estimated";if(n)if(this.actualInput>0&&
|
|
35
|
+
this.sentInputLocal>0){let d=this.actualInput/this.sentInputLocal,f=Math.max(0,this.actualInput-this.repairInput-this.discoveryInput);this.baselineInput=f+Math.round(d*this.removedInputLocal),o=this.removedInputLocal===
|
|
36
|
+
0?"measured":"estimated";}else this.actualInput>0?(this.baselineInput=this.actualInput,o="measured"):(this.baselineInput=0,o="unmeasured");let r=n?Math.max(0,this.actualOutput-this.repairOutput-this.discoveryOutput):
|
|
37
|
+
this.baselineOutput,s=e.cachedInputPer1k??e.inputPer1k,i=Math.min(this.providerCachedInput,this.actualInput),a=d=>Math.max(0,d-i)/1e3*e.inputPer1k+i/1e3*s,c=a(this.baselineInput)+r/1e3*e.outputPer1k,l=a(
|
|
38
|
+
this.actualInput)+this.actualOutput/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd,u=c===0?0:1-l/c;return {baselineEstimate:No(c),actual:No(l),netSavings:ei(u),basis:o}}};function No(t){
|
|
39
|
+
return Math.round(t*1e10)/1e10}function ei(t){return Math.round(t*1e6)/1e6}var ti=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
|
|
39
40
|
4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
|
|
40
41
|
1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,
|
|
41
|
-
1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),
|
|
42
|
-
8,
|
|
43
|
-
[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let l=0;l<
|
|
44
|
-
64;b++){let y=a[b-15],
|
|
45
|
-
h,6)^se(h,11)^se(h,25),
|
|
46
|
-
i[4]=i[4]+h|0,i[5]=i[5]+p|0,i[6]=i[6]+g|0,i[7]=i[7]+x|0;}let c="";for(let l=0;l<8;l++)c+=(i[l]>>>0).toString(16).padStart(8,"0");return c}var
|
|
47
|
-
|
|
48
|
-
normalize("NFC"),e=e.replace(
|
|
49
|
-
Y(i)&&!Y(s)&&!
|
|
50
|
-
t)}function Se(t){return JSON.stringify(
|
|
51
|
-
function
|
|
42
|
+
1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ni=new TextEncoder;function se(t,e){return t>>>e|t<<32-e}function jo(t){let e=ni.encode(t),n=e.length*
|
|
43
|
+
8,o=(e.length+8>>6)+1,r=new Uint8Array(o*64);r.set(e),r[e.length]=128;let s=new DataView(r.buffer);s.setUint32(r.length-8,Math.floor(n/4294967296)),s.setUint32(r.length-4,n>>>0);let i=new Uint32Array(
|
|
44
|
+
[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let l=0;l<r.length;l+=64){for(let b=0;b<16;b++)a[b]=s.getUint32(l+b*4);for(let b=16;b<
|
|
45
|
+
64;b++){let y=a[b-15],T=a[b-2],C=se(y,7)^se(y,18)^y>>>3,O=se(T,17)^se(T,19)^T>>>10;a[b]=a[b-16]+C+a[b-7]+O|0;}let u=i[0],d=i[1],f=i[2],m=i[3],h=i[4],p=i[5],g=i[6],x=i[7];for(let b=0;b<64;b++){let y=se(
|
|
46
|
+
h,6)^se(h,11)^se(h,25),T=h&p^~h&g,C=x+y+T+ti[b]+a[b]|0,O=se(u,2)^se(u,13)^se(u,22),E=u&d^u&f^d&f,A=O+E|0;x=g,g=p,p=h,h=m+C|0,m=f,f=d,d=u,u=C+A|0;}i[0]=i[0]+u|0,i[1]=i[1]+d|0,i[2]=i[2]+f|0,i[3]=i[3]+m|0,
|
|
47
|
+
i[4]=i[4]+h|0,i[5]=i[5]+p|0,i[6]=i[6]+g|0,i[7]=i[7]+x|0;}let c="";for(let l=0;l<8;l++)c+=(i[l]>>>0).toString(16).padStart(8,"0");return c}var oi=/\s+/g,ri=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],si=/[¿?¡!;.,:'"·•]/g,ii=/([a-z])\p{M}+/gu,ai=/(^|\s)\p{M}+/gu,
|
|
48
|
+
bn=/\p{L}/u;function Y(t){return t>="0"&&t<="9"}function xt(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,o]of ri)e=e.replace(n,o);return e=e.normalize("NFD").replace(ii,"$1").replace(ai,"$1").
|
|
49
|
+
normalize("NFC"),e=e.replace(si,(n,o,r)=>{let s=r[o-1]??"",i=r[o+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return Y(s)&&Y(i)?n:"";case "!":return Y(s)?n:"";case ".":case ",":return Y(s)&&Y(i)||
|
|
50
|
+
Y(i)&&!Y(s)&&!bn.test(s)?n:"";case ":":return Y(s)&&Y(i)?n:"";case "'":case '"':return bn.test(s)&&bn.test(i)||Y(s)||Y(i)?n:"";default:return Y(s)||Y(i)?n:""}}),e.replace(oi," ").trim()}function ie(t){return jo(
|
|
51
|
+
t)}function Se(t){return JSON.stringify(xn(t))}function xn(t){if(Array.isArray(t))return t.map(xn);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=xn(t[n]);return e}return t}
|
|
52
|
+
function yn(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function vn(t){let e=t.context??{},n=t.messages.filter(s=>s.role==="system").map(s=>s.content).join(
|
|
52
53
|
`
|
|
53
|
-
`),
|
|
54
|
-
`),
|
|
55
|
-
systemPromptHash:ie(n),toolsetHash:ie(Se(
|
|
54
|
+
`),o=t.messages.filter(s=>s.role!=="system").map(s=>`${s.role}:${xt(s.content)}`).join(`
|
|
55
|
+
`),r=(t.tools??[]).map(s=>({id:s.id,risk:s.risk,parameters:s.parameters??null})).sort((s,i)=>s.id.localeCompare(i.id));return {model:t.model,modelFamily:yn(t.model),messages:t.messages,normalizedText:o,
|
|
56
|
+
systemPromptHash:ie(n),toolsetHash:ie(Se(r)),structuredDataHash:t.structuredData!==void 0?ie(Se(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.contractId??"none",contractId:t.
|
|
56
57
|
response?.contractId??null,temperature:t.temperature??null,seed:t.seed??null,tenantId:e.tenantId??"anonymous",authorizationScope:e.authorizationScope??"default",principal:e.sessionId??null,locale:e.locale??
|
|
57
|
-
"und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var
|
|
58
|
+
"und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var $o="n2";function kn(t,e={}){let n=e.servedModel??t.model,o=Se({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily:yn(n),
|
|
58
59
|
model:n,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,data:t.structuredDataHash,locale:t.locale,temperature:t.temperature,seed:t.seed,knowledgeEpoch:t.knowledgeEpoch,
|
|
59
|
-
freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${
|
|
60
|
+
freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${$o}:${ie(o)}`}function Fo(t,e={}){let n=Se({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,
|
|
60
61
|
model:e.servedModel??t.model,system:t.systemPromptHash,contract:t.contractId,schema:t.schemaVersion,tools:t.toolsetHash,data:t.structuredDataHash,temperature:t.temperature,seed:t.seed,deferrable:e.deferrable===
|
|
61
|
-
true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:inflight:${
|
|
62
|
+
true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:inflight:${$o}:${ie(n)}`}var ci=new RegExp("\\b("+["now|today|current|currently|latest|live|price|prices|stock|availability|weather|score|breaking","ahora|hoy|actual|actualmente|ultimo|\xFAltimo|precio|precios|disponibilidad|cot\
|
|
62
63
|
izacion|cotizaci\xF3n","ara|avui|preu|preus|disponibilitat|darrer","maintenant|aujourd'hui|actuel|actuelle|dernier|prix|disponibilite|disponibilit\xE9|meteo|m\xE9t\xE9o","jetzt|heute|aktuell|aktuelle|\
|
|
63
64
|
neueste|preis|preise|verfugbarkeit|verf\xFCgbarkeit|wetter|kurs","adesso|oggi|attuale|ultimo|prezzo|prezzi|disponibilita|disponibilit\xE0|meteo","agora|hoje|atual|ultimo|\xFAltimo|preco|pre\xE7o|precos|pre\xE7\
|
|
64
65
|
os|disponibilidade|cotacao|cota\xE7\xE3o","nu|vandaag|huidige|laatste|prijs|prijzen|beschikbaarheid|weer|koers","teraz|dzisiaj|dzis|dzi\u015B|aktualny|aktualna|najnowszy|cena|ceny|dostepnosc|dost\u0119pno\u015B\u0107|pog\
|
|
65
66
|
oda","simdi|\u015Fimdi|bugun|bug\xFCn|guncel|g\xFCncel|son|fiyat|fiyatlar|stok|hava","sekarang|hari ini|terkini|terbaru|harga|ketersediaan|cuaca","bay gio|b\xE2y gi\u1EDD|hom nay|h\xF4m nay|hien tai|hi\u1EC7n t\u1EA1i|moi\
|
|
66
|
-
nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),
|
|
67
|
+
nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),li=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nu\
|
|
67
68
|
estro|nuestra|cuenta|factura|pedido|saldo|suscripcion|suscripci\xF3n|perfil","meu|meva|nostre|compte|factura|comanda|saldo|subscripcio|subscripci\xF3|perfil","mon|ma|mes|notre|nos|compte|solde|facture\
|
|
68
69
|
|commande|abonnement|profil","mein|meine|meinem|unser|unsere|konto|kontostand|saldo|rechnung|bestellung|abo|abonnement|profil","mio|mia|miei|nostro|nostra|conto|saldo|fattura|ordine|abbonamento|profil\
|
|
69
70
|
o","meu|minha|meus|nosso|nossa|conta|saldo|fatura|pedido|assinatura|perfil","mijn|onze|ons|rekening|saldo|factuur|bestelling|abonnement|profiel","moj|m\xF3j|moja|moje|nasz|nasza|konto|saldo|faktura|zamow\
|
|
70
71
|
ienie|zam\xF3wienie|subskrypcja|profil","benim|bizim|hesap|hesabim|hesab\u0131m|bakiye|fatura|siparis|sipari\u015F|abonelik|profil","saya|kami|akun|saldo|tagihan|pesanan|langganan|profil","cua toi|c\u1EE7a\
|
|
71
|
-
t\xF4i|tai khoan|t\xE0i kho\u1EA3n|so du|s\u1ED1 d\u01B0|hoa don|h\xF3a \u0111\u01A1n|don hang|\u0111\u01A1n h\xE0ng|thue bao|thu\xEA bao"].join("|")+")\\b","i");function
|
|
72
|
-
|
|
73
|
-
push("write/destructive tools present"),
|
|
74
|
-
null||t.freshnessBucket==="any"),c=t.freshnessBucket==="live",l=s&&t.principal==null,u=!i&&!a&&!c&&!l&&!
|
|
72
|
+
t\xF4i|tai khoan|t\xE0i kho\u1EA3n|so du|s\u1ED1 d\u01B0|hoa don|h\xF3a \u0111\u01A1n|don hang|\u0111\u01A1n h\xE0ng|thue bao|thu\xEA bao"].join("|")+")\\b","i");function wn(t){let e=[],n=t.normalizedText,
|
|
73
|
+
o=(t.original.tools??[]).some(m=>m.risk==="write"||m.risk==="destructive"),r=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||ci.test(n),s=li.test(n),i=(t.temperature??0)>.3&&t.seed==null;o&&e.
|
|
74
|
+
push("write/destructive tools present"),r&&e.push("freshness-sensitive request"),s&&e.push("personalized/account-scoped request"),i&&e.push("stochastic sampling (temp>0.3, no seed)");let a=r&&(t.freshnessBucket==
|
|
75
|
+
null||t.freshnessBucket==="any"),c=t.freshnessBucket==="live",l=s&&t.principal==null,u=!i&&!a&&!c&&!l&&!o;o&&e.push("write/destructive tools \u2192 exact cache off (side effects must execute)"),c&&e.push(
|
|
75
76
|
"freshnessBucket=live \u2192 exact cache off (answer must be current)"),a&&e.push("freshness-sensitive without a freshness bucket \u2192 exact cache off"),l&&e.push("personalized request with no princ\
|
|
76
|
-
ipal (context.sessionId) \u2192 exact cache off");let d=!r&&!o&&!s&&!i&&t.freshnessBucket!=="day";return {allowExactCache:u,allowSemanticCache:d,
|
|
77
|
-
|
|
78
|
-
now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),n.value):null}async set(e,n,
|
|
79
|
-
next().value;
|
|
80
|
-
inflight.set(e,
|
|
81
|
-
Boolean)}function
|
|
82
|
-
1]}`;
|
|
83
|
-
e[s]/=
|
|
77
|
+
ipal (context.sessionId) \u2192 exact cache off");let d=!o&&!r&&!s&&!i&&t.freshnessBucket!=="day",f=!o&&!r&&!s&&!i&&t.freshnessBucket!=="day";return {allowExactCache:u,allowSemanticCache:d,allowElision:f,
|
|
78
|
+
allowSingleflight:!o&&!l,allowCompression:true,requiresFreshData:r,hasSideEffects:o,isPersonalized:s,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var yt=class{store=new Map;maxEntries;now;constructor(e={}){this.maxEntries=e.maxEntries??1e4,this.now=e.now??(()=>Date.now());}async get(e){let n=this.store.get(e);return n?n.expiresAtMs!==null&&this.
|
|
79
|
+
now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),n.value):null}async set(e,n,o){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let r=this.store.keys().
|
|
80
|
+
next().value;r!==void 0&&this.store.delete(r);}this.store.set(e,{value:n,expiresAtMs:o!=null?this.now()+o:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};var vt=class{inflight=new Map;waiters=new Map;async run(e,n){let o=this.inflight.get(e);if(o)return this.waiters.set(e,(this.waiters.get(e)??1)+1),{value:await o,coalesced:true};let r=(async()=>n())();this.
|
|
81
|
+
inflight.set(e,r),this.waiters.set(e,1);try{return {value:await r,coalesced:!1}}finally{this.inflight.delete(e),this.waiters.delete(e);}}get activeKeys(){return this.inflight.size}};function ui(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e}function di(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(
|
|
82
|
+
Boolean)}function pi(t){let e=new Array(256).fill(0),n=di(t);if(n.length===0)return e;let o=new Map;for(let s=0;s<n.length;s++){let i=n[s];if(o.set(i,(o.get(i)??0)+1),s+1<n.length){let a=`${i}\0${n[s+
|
|
83
|
+
1]}`;o.set(a,(o.get(a)??0)+1);}}for(let[s,i]of o){let a=ui(s),c=a%256,l=a>>>31===1?-1:1;e[c]+=l*(1+Math.log(i));}let r=0;for(let s of e)r+=s*s;if(r=Math.sqrt(r),r===0)return e;for(let s=0;s<e.length;s++)
|
|
84
|
+
e[s]/=r;return e}function zo(t){return pi(t)}var Vo=.72;function fi(t,e){let n=Math.min(t.length,e.length),o=0,r=0,s=0;for(let i=0;i<n;i++){let a=t[i],c=e[i];o+=a*c,r+=a*a,s+=c*c;}return r===0||s===0?0:o/(Math.sqrt(r)*Math.sqrt(s))}var mi=new Set(["no","not",
|
|
84
85
|
"never","none","cannot","cant","without","nor","nt","isnt","arent","wasnt","werent","dont","doesnt","didnt","wont","shouldnt","sin","nunca","jamas","jam\xE1s","tampoco","ni","ningun","ning\xFAn","ning\
|
|
85
|
-
una","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),
|
|
86
|
+
una","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),hi=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what","whats","whi\
|
|
86
87
|
ch","who","whom","how","when","where","me","my","i","you","please","tell","give","show","find","do","does","did","be","that","this","it","with","as","at","by","from","about","into","over","than","then",
|
|
87
88
|
"s","el","la","los","las","un","una","unos","unas","de","del","al","en","por","para","con","sin","sobre","y","o","u","es","son","era","eran","ser","estar","esta","este","esto","estos","estas","ese","e\
|
|
88
89
|
sa","eso","que","cual","cuales","quien","quienes","como","cuando","donde","dame","dime","quiero","necesito","puedes","podrias","favor","porfavor","gracias","me","mi","mis","tu","tus","su","sus","lo","\
|
|
89
90
|
le","se","hay","el","la","els","les","un","una","uns","unes","de","del","dels","al","als","en","per","amb","sense","sobre","i","o","es","son","era","eren","ser","estar","aquest","aquesta","aquests","a\
|
|
90
91
|
questes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function et(t){return (t.match(/\d[\d.,:/-]*/g)??
|
|
91
|
-
[]).map(e=>e.replace(/[.,:/-]+$/,""))}function
|
|
92
|
-
return true}function tt(t){return t.split(/\s+/).filter(Boolean)}function nt(t){return t.filter(e=>
|
|
92
|
+
[]).map(e=>e.replace(/[.,:/-]+$/,""))}function Sn(t,e){if(t.length!==e.length)return false;let n=new Map;for(let o of t)n.set(o,(n.get(o)??0)+1);for(let o of e){let r=n.get(o);if(!r)return false;n.set(o,r-1);}
|
|
93
|
+
return true}function tt(t){return t.split(/\s+/).filter(Boolean)}function nt(t){return t.filter(e=>mi.has(e.replace(/'/g,""))||e.endsWith("n't")).length}var gi=/^(system|user|assistant|tool):/;function Uo(t){
|
|
93
94
|
return t.split(`
|
|
94
|
-
`).map(e=>{let n=
|
|
95
|
-
r
|
|
96
|
-
n.filter(
|
|
97
|
-
let n=e.embed==null;this.embed=e.embed??
|
|
98
|
-
e.maxRecords??5e3,this.now=e.now??(()=>Date.now());}async find(e){if(this.records.length===0)return null;let n=await this.embed(e.normalizedText),
|
|
99
|
-
|
|
100
|
-
structuredDataHash!==e.structuredDataHash||
|
|
101
|
-
let s=
|
|
102
|
-
a>
|
|
103
|
-
this.records.shift(),this.records.push({embedding:
|
|
95
|
+
`).map(e=>{let n=gi.exec(e);return n?{rol:n[1],texto:e.slice(n[0].length)}:{rol:"",texto:e}})}function bi(t,e){let n=Uo(t),o=Uo(e);if(n.length!==o.length)return false;for(let r=0;r<n.length;r++)if(n[r].rol!==
|
|
96
|
+
o[r].rol||!xi(n[r].texto,o[r].texto))return false;return true}function xi(t,e){if(!Sn(et(t),et(e)))return false;let n=tt(t),o=tt(e);if(nt(n)!==nt(o))return false;let r=l=>l.length>1&&!hi.has(l)&&!/^\d/.test(l),s=new Set(
|
|
97
|
+
n.filter(r)),i=new Set(o.filter(r));if(s.size===0&&i.size===0)return true;let a=0;for(let l of s)i.has(l)&&a++;let c=s.size+i.size-a;return c===0?true:a/c>=.75}var qo=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;constructor(e={}){
|
|
98
|
+
let n=e.embed==null;this.embed=e.embed??zo,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??(n?Vo:.9),this.acceptThreshold=e.acceptThreshold??.85,this.ttlMs=e.ttlMs,this.maxRecords=
|
|
99
|
+
e.maxRecords??5e3,this.now=e.now??(()=>Date.now());}async find(e){if(this.records.length===0)return null;let n=await this.embed(e.normalizedText),o=null;for(let r of this.records){if(r.tenantId!==e.tenantId||
|
|
100
|
+
r.authorizationScope!==e.authorizationScope||r.principal!==e.principal||r.knowledgeEpoch!==e.knowledgeEpoch||r.contractId!==e.contractId||r.model!==e.model||r.systemPromptHash!==e.systemPromptHash||r.
|
|
101
|
+
structuredDataHash!==e.structuredDataHash||r.locale!==e.locale||r.schemaVersion!==e.schemaVersion||r.safetyPolicyVersion!==e.safetyPolicyVersion||this.ttlMs!=null&&this.now()-r.storedAtMs>this.ttlMs)continue;
|
|
102
|
+
let s=fi(n,r.embedding);if(s<this.similarityThreshold||!bi(e.normalizedText,r.query))continue;let i=this.verify?await this.verify(e.normalizedText,r.query):s,a=Math.min(s,i);a<this.acceptThreshold||(!o||
|
|
103
|
+
a>o.confidence)&&(o={record:r,similarity:s,verifierScore:i,confidence:a,ageMs:this.now()-r.storedAtMs});}return o}async store(e,n){let o=await this.embed(e.normalizedText);this.records.length>=this.maxRecords&&
|
|
104
|
+
this.records.shift(),this.records.push({embedding:o,query:e.normalizedText,answer:n,tenantId:e.tenantId,authorizationScope:e.authorizationScope,principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.
|
|
104
105
|
contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.structuredDataHash,locale:e.locale,schemaVersion:e.schemaVersion,safetyPolicyVersion:e.safetyPolicyVersion,storedAtMs:this.
|
|
105
|
-
now()});}invalidateEpoch(e){let n=0;for(let
|
|
106
|
-
|
|
107
|
-
let
|
|
108
|
-
return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function
|
|
106
|
+
now()});}invalidateEpoch(e){let n=0;for(let o=this.records.length-1;o>=0;o--)this.records[o].knowledgeEpoch===e&&(this.records.splice(o,1),n++);return n}get size(){return this.records.length}};var Tn=class{resolvers=[];register(e){return this.resolvers.push(e),this}try(e){for(let n of this.resolvers)try{let o=n.try(e);if(o)return o}catch{}return null}get size(){return this.resolvers.length}},
|
|
107
|
+
yi={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]??vi(t.normalizedText))?.trim();if(!n)return null;
|
|
108
|
+
let o=wi(n);return o===null||!Number.isFinite(o)?null:{text:ki(o),data:{value:o},resolver:"arithmetic"}}};function vi(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function ki(t){
|
|
109
|
+
return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function wi(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],o=[],r={"+":1,"-":1,
|
|
109
110
|
"*":2,"/":2,"%":2},s=a=>{let c=n.pop(),l=n.pop();if(l===void 0||c===void 0)return false;switch(a){case "+":return n.push(l+c),true;case "-":return n.push(l-c),true;case "*":return n.push(l*c),true;case "/":return c===
|
|
110
|
-
0?false:(n.push(l/c),true);case "%":return c===0?false:(n.push(l%c),true);default:return false}},i=true;for(let a of e)if(/^\d/.test(a))n.push(Number(a)),i=false;else if(a==="(")
|
|
111
|
-
|
|
112
|
-
i=true;}for(;
|
|
113
|
-
|
|
114
|
-
classifier=e.classifier,this.maxRounds=e.maxRounds??2;}classify(e){let n=e.original.retrieval?.mode,
|
|
115
|
-
test(
|
|
116
|
-
.8,"self-contained transformation",0);let s=this.classifier?.classify(
|
|
117
|
-
e"?me("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?me("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):
|
|
118
|
-
d question",Math.min(this.maxRounds,2)):
|
|
119
|
-
"SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function me(t,e,n,
|
|
120
|
-
no tools provided",setIsStable:true};let n=e.slice(0,this.maxTools),
|
|
121
|
-
/${e.length}, capped at maxTools=${this.maxTools}; risk gating is the caller's responsibility while routing is off)`,setIsStable:true}}select(e,n,
|
|
122
|
-
no tools provided",setIsStable:true};let o
|
|
111
|
+
0?false:(n.push(l/c),true);case "%":return c===0?false:(n.push(l%c),true);default:return false}},i=true;for(let a of e)if(/^\d/.test(a))n.push(Number(a)),i=false;else if(a==="(")o.push(a),i=true;else if(a===")"){for(;o.length&&
|
|
112
|
+
o[o.length-1]!=="(";)if(!s(o.pop()))return null;if(o.pop()!=="(")return null;i=false;}else {if(i)return null;for(;o.length&&o[o.length-1]!=="("&&r[o[o.length-1]]>=r[a];)if(!s(o.pop()))return null;o.push(a),
|
|
113
|
+
i=true;}for(;o.length;){let a=o.pop();if(a==="("||!s(a))return null}return n.length===1?n[0]:null}function Ho(){return new Tn().register(yi)}var Si=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,Ko=/\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,
|
|
114
|
+
Ti=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,kt=class{classifier;maxRounds;constructor(e={}){this.
|
|
115
|
+
classifier=e.classifier,this.maxRounds=e.maxRounds??2;}classify(e){let n=e.original.retrieval?.mode,o=e.normalizedText;if((e.original.tools??[]).some(i=>i.risk==="write"||i.risk==="destructive")&&/\b(create|update|delete|send|pay|book|cancel|crea|actualiza|elimina|env[ií]a|paga)\b/i.
|
|
116
|
+
test(o))return me("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return me("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(Ti.test(o)&&!Ko.test(o))return me("NO_RETRIEVAL",
|
|
117
|
+
.8,"self-contained transformation",0);let s=this.classifier?.classify(o);return s&&s.confidence>=.75?me(s.executionClass,s.confidence,"local classifier",Ei(s.executionClass,this.maxRounds)):n==="singl\
|
|
118
|
+
e"?me("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?me("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):Si.test(o)?me("MULTI_HOP_RETRIEVAL",.7,"comparison/compoun\
|
|
119
|
+
d question",Math.min(this.maxRounds,2)):Ko.test(o)?me("SINGLE_RETRIEVAL",.65,"single factual lookup",1):me("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function Ei(t,e){return t===
|
|
120
|
+
"SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function me(t,e,n,o){return {executionClass:t,confidence:e,reason:n,rounds:o}}var wt=class{maxTools;scoreIntentMatch;constructor(e={}){this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??Ri;}passthrough(e){if(!e||e.length===0)return {tools:[],droppedIds:[],reason:"\
|
|
121
|
+
no tools provided",setIsStable:true};let n=e.slice(0,this.maxTools),o=e.slice(this.maxTools).map(r=>r.id);return {tools:n,droppedIds:o,reason:`router off: caller tools passed through unfiltered (${n.length}\
|
|
122
|
+
/${e.length}, capped at maxTools=${this.maxTools}; risk gating is the caller's responsibility while routing is off)`,setIsStable:true}}select(e,n,o){if(!n||n.length===0)return {tools:[],droppedIds:[],reason:"\
|
|
123
|
+
no tools provided",setIsStable:true};let r=o==="TOOL_ACTION",s=n.filter(p=>r||p.risk==="read"),i=p=>r&&p.risk!=="read",a=s.filter(p=>!i(p)),c=s.filter(p=>i(p)),l=c.map(p=>({tool:p,score:this.scoreIntentMatch(
|
|
123
124
|
e,p)})).sort((p,g)=>g.score-p.score).map(p=>p.tool),u=a.map(p=>({tool:p,score:this.scoreIntentMatch(e,p)})).filter(p=>p.score>0).sort((p,g)=>g.score-p.score).map(p=>p.tool),f=[...l.slice(0,this.maxTools),
|
|
124
125
|
...u.slice(0,Math.max(0,this.maxTools-c.length))].map(p=>({tool:p})).map(p=>p.tool).sort((p,g)=>p.id<g.id?-1:p.id>g.id?1:0),m=new Set(f.map(p=>p.id)),h=n.filter(p=>!m.has(p.id)).map(p=>p.id);return {tools:f,
|
|
125
|
-
droppedIds:h,reason:`selected ${f.length}/${n.length} by intent match (writes ${
|
|
126
|
-
s&&(n.includes(s)?
|
|
127
|
-
0)-(i.score??0));if(
|
|
128
|
-
i);else break}return s}async function
|
|
129
|
-
let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,
|
|
130
|
-
(
|
|
131
|
-
...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
${
|
|
126
|
+
droppedIds:h,reason:`selected ${f.length}/${n.length} by intent match (writes ${r?"allowed":"blocked"})`,setIsStable:h.length===0}}};function Ri(t,e){let n=xt(t),o=0;for(let r of e.intents){let s=xt(r);
|
|
127
|
+
s&&(n.includes(s)?o+=2:s.split(/\s+/).some(i=>i.length>3&&n.includes(i))&&(o+=1));}return o}function Ci(t){let e=new Set,n=[];for(let o of t){let r=o.hash??Oi(o.text);e.has(r)||(e.add(r),n.push(o));}return n}function Ii(t,e={maxDocuments:5}){let n=e.minDocuments??1,o=[...t].sort((i,a)=>(a.score??
|
|
128
|
+
0)-(i.score??0));if(o.length<=n)return o;let r=o[0]?.score??0;if(r<=0)return o.slice(0,e.maxDocuments);let s=[];for(let i of o){let a=(i.score??0)/r;if(s.length<n||a>=.4&&s.length<e.maxDocuments)s.push(
|
|
129
|
+
i);else break}return s}async function Jo(t,e){if(t.execution==="NO_RETRIEVAL"||t.execution==="TOOL_ACTION"||t.execution==="NON_CACHEABLE"||!e.retriever)return {docs:[],rounds:0,retrievedCount:0,keptCount:0};
|
|
130
|
+
let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,o=[];for(let i=0;i<n;i++){let a=await e.retriever.retrieve(t.query,t.maxDocuments*2);o.push(...a);}let r=o.length;o=Ci(o),e.reranker&&
|
|
131
|
+
(o=await e.reranker.rerank(t.query,o));let s=Ii(o,{maxDocuments:t.maxDocuments});return {docs:s,rounds:n,retrievedCount:r,keptCount:s.length}}function Oi(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function Ul(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function ql(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{
|
|
132
|
+
...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[o,r]of Object.entries(e.set??{}))o==="userPreferences"&&Pi(r)?Object.assign(n.userPreferences,
|
|
133
|
+
r):n.confirmedFacts[o]=r;for(let[o,r]of Object.entries(e.append??{})){let s=Di(n,o);s?s.push(...r.map(String)):n.confirmedFacts[o]=r;}for(let o of e.remove??[])delete n.confirmedFacts[o],delete n.userPreferences[o],
|
|
134
|
+
Ai(n,o);return n}function Hl(t){let e=t.rawTurns??3,n=[],o=_i(t.state);o&&n.push({role:"system",content:`Conversation state:
|
|
135
|
+
${o}`});let r=t.history.slice(-e);return n.push(...r,t.current),n}function _i(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`fa\
|
|
135
136
|
cts: ${JSON.stringify(t.confirmedFacts)}`),Object.keys(t.userPreferences).length&&e.push(`preferences: ${JSON.stringify(t.userPreferences)}`),t.decisions.length&&e.push(`decisions: ${t.decisions.join(
|
|
136
137
|
"; ")}`),t.openItems.length&&e.push(`open: ${t.openItems.join("; ")}`),e.join(`
|
|
137
|
-
`)}function
|
|
138
|
-
for(let n of ["goals","decisions","openItems","evidenceRefs"]){let
|
|
139
|
-
`).filter(c=>c.trim().length>0).map(c=>({indent:
|
|
140
|
-
c[2],n),d=Number(c[1]),f=[];for(let m=0,h=1;m<d&&h<s.length;m++,h++){let p=s[h];if(p.indent!==1)break;let g=$e(p.content,n),x={};u.forEach((b,y)=>{x[b]=
|
|
141
|
-
match(/^\[(\d+)\]:\s*(.*)$/);if(l){let u=l[2];return Number(l[1])===0||u.trim()===""?[]:$e(u,n).map(
|
|
142
|
-
function
|
|
143
|
-
kind:l}=a;if(l.type==="scalar")
|
|
144
|
-
s<t.length;d++,s++){let f=t[s];if(f.indent!==n+1)break;let m=$e(f.content,
|
|
145
|
-
s]}function
|
|
146
|
-
let s=Number(
|
|
147
|
-
|
|
148
|
-
'"'?(
|
|
138
|
+
`)}function Di(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 Ai(t,e){
|
|
139
|
+
for(let n of ["goals","decisions","openItems","evidenceRefs"]){let o=t[n].indexOf(e);o>=0&&t[n].splice(o,1);}}function Pi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Wo={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function Go(t,e={}){let n=e.delimiter??",",o=e.indent??" ",s=t.split(`
|
|
140
|
+
`).filter(c=>c.trim().length>0).map(c=>({indent:Li(c,o),content:c.slice(Yo(c,o))}));if(s.length===0)return {};let i=s[0];if(i.indent===0){let c=i.content.match(/^\[(\d+)\]\{(.*)\}:\s*$/);if(c){let u=$e(
|
|
141
|
+
c[2],n),d=Number(c[1]),f=[];for(let m=0,h=1;m<d&&h<s.length;m++,h++){let p=s[h];if(p.indent!==1)break;let g=$e(p.content,n),x={};u.forEach((b,y)=>{x[b]=ot(g[y]??"null");}),f.push(x);}return f}let l=i.content.
|
|
142
|
+
match(/^\[(\d+)\]:\s*(.*)$/);if(l){let u=l[2];return Number(l[1])===0||u.trim()===""?[]:$e(u,n).map(ot)}}let[a]=Zo(s,0,0,n);return a}function Yo(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}
|
|
143
|
+
function Li(t,e){return Yo(t,e)/e.length}function Zo(t,e,n,o){let r={},s=e;for(;s<t.length;){let i=t[s];if(i.indent<n)break;if(i.indent>n){s++;continue}let a=Mi(i.content,o);if(!a){s++;continue}let{key:c,
|
|
144
|
+
kind:l}=a;if(l.type==="scalar")r[c]=l.value,s++;else if(l.type==="inlineArray")r[c]=l.values,s++;else if(l.type==="emptyArray")r[c]=[],s++;else if(l.type==="table"){let u=[];s++;for(let d=0;d<l.count&&
|
|
145
|
+
s<t.length;d++,s++){let f=t[s];if(f.indent!==n+1)break;let m=$e(f.content,o),h={};l.columns.forEach((p,g)=>{h[p]=ot(m[g]??"null");}),u.push(h);}r[c]=u;}else {let[u,d]=Zo(t,s+1,n+1,o);r[c]=u,s=d;}}return [r,
|
|
146
|
+
s]}function Mi(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:St(n[1]),kind:{type:"table",count:Number(n[2]),columns:$e(n[3],e)}};let o=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(o){
|
|
147
|
+
let s=Number(o[2]),i=o[3];return s===0||i.trim()===""?{key:St(o[1]),kind:{type:"emptyArray"}}:{key:St(o[1]),kind:{type:"inlineArray",values:$e(i,e).map(ot)}}}let r=t.match(/^([^:]+):\s*(.*)$/);if(r){let s=St(
|
|
148
|
+
r[1]),i=r[2];return i===""?{key:s,kind:{type:"object"}}:{key:s,kind:{type:"scalar",value:ot(i)}}}return null}function $e(t,e){let n=[],o="",r=false;for(let s=0;s<t.length;s++){let i=t[s];r?i==='"'?t[s+1]===
|
|
149
|
+
'"'?(o+='"',s++):r=false:o+=i:i==='"'?r=true:i===e?(n.push(o),o=""):o+=i;}return n.push(o),n.map(s=>s.trim())}function ot(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,
|
|
149
150
|
'"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function St(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,
|
|
150
|
-
'"'):e}function
|
|
151
|
-
`)}function
|
|
152
|
-
e))
|
|
153
|
-
join(
|
|
154
|
-
return}
|
|
155
|
-
|
|
156
|
-
|
|
151
|
+
'"'):e}function Bi(t,e={}){let n=e.delimiter??",",o=e.indent??" ",r=[];return Cn(null,t,0,r,n,o),r.join(`
|
|
152
|
+
`)}function Cn(t,e,n,o,r,s){let i=s.repeat(n),a=t===null?"":`${ji(t)}`;if(Array.isArray(e)){Ni(a,e,n,o,r,s);return}if(Rn(e)){t!==null&&o.push(`${i}${a}:`);let c=t===null?n:n+1;for(let[l,u]of Object.entries(
|
|
153
|
+
e))Cn(l,u,c,o,r,s);return}o.push(`${i}${a}: ${Tt(e,r)}`);}function Ni(t,e,n,o,r,s){let i=s.repeat(n),a=t===""?"":t;if(e.length===0){o.push(`${i}${a}[0]:`);return}if(e.every(En)){let d=e.map(f=>Tt(f,r)).
|
|
154
|
+
join(r);o.push(`${i}${a}[${e.length}]: ${d}`);return}let c=Et(e);if(c){o.push(`${i}${a}[${e.length}]{${c.join(r)}}:`);let d=s.repeat(n+1);for(let f of e){let m=c.map(h=>Tt(f[h],r)).join(r);o.push(`${d}${m}`);}
|
|
155
|
+
return}o.push(`${i}${a}[${e.length}]:`);let l=n+1,u=s.repeat(l);for(let d of e)if(En(d))o.push(`${u}- ${Tt(d,r)}`);else {let f=[];Cn(null,d,0,f,r,s);let[m,...h]=f;o.push(`${u}- ${m??""}`);for(let p of h)
|
|
156
|
+
o.push(`${u}${s}${p}`);}}function Et(t){if(t.length===0)return null;let e=t[0];if(!Rn(e))return null;let n=Object.keys(e);if(n.length===0)return null;let o=n.slice().sort().join("\0");for(let r of t){if(!Rn(
|
|
157
|
+
r))return null;let s=Object.keys(r);if(s.slice().sort().join("\0")!==o)return null;for(let i of s)if(!En(r[i]))return null}return n}function ji(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:Xo(t)}function Tt(t,e){
|
|
157
158
|
if(t==null)return "null";if(typeof t=="number")return Number.isFinite(t)?String(t):"null";if(typeof t=="boolean")return t?"true":"false";let n=String(t);return n===""||n.includes(e)||n.includes(`
|
|
158
|
-
`)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?
|
|
159
|
-
"number"||typeof t=="boolean"}function
|
|
160
|
-
ch following indented line is one row of delimiter-separated values. `key[N]: a,b` is an inline list. Quoted values use CSV-style escaping.";function
|
|
161
|
-
encode(e){return
|
|
162
|
-
`)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function
|
|
163
|
-
'""')}"`:e}var Rt=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[
|
|
164
|
-
64,this.minSavingsRatio=e.minimumSavingsRatio??.08,this.qualityPenalty=e.qualityPenalty??(()=>0);}choose(e,n){let
|
|
165
|
-
e))continue;let u=l.encode(e);if(l.format!=="json-compact"&&!
|
|
166
|
-
|
|
167
|
-
return l?
|
|
168
|
-
ulted to JSON"}}let a=s,c="json baseline (no challenger cleared thresholds)";for(let l of
|
|
169
|
-
d>=this.minSavingsRatio&&l.total<a.total&&(a=l,c=`${l.format} saved ${u} tokens (${(d*100).toFixed(1)}%) vs json`);}return
|
|
170
|
-
n)}catch{return false}}function
|
|
171
|
-
length)return false;for(let i=0;i<t.length;i++)if(!
|
|
172
|
-
call(e,i)||!
|
|
173
|
-
string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function
|
|
174
|
-
e.type??
|
|
175
|
-
message:"expected boolean"});break;case "null":t!==null&&
|
|
176
|
-
message:"expected object"});return}let
|
|
177
|
-
Object.keys(e.properties));for(let i of Object.keys(
|
|
178
|
-
|
|
179
|
-
ms ${e.maxItems}`}),e.minItems!=null&&t.length<e.minItems&&
|
|
180
|
-
"string"){
|
|
181
|
-
minLength&&
|
|
182
|
-
sion: ${e.pattern}`});}
|
|
183
|
-
e.type==="integer"&&!Number.isInteger(t)&&
|
|
184
|
-
minimum&&
|
|
185
|
-
e,n,
|
|
186
|
-
.${
|
|
187
|
-
tring should set maxLength or use an enum`);}function
|
|
188
|
-
ate + repair"}}function
|
|
189
|
-
return
|
|
190
|
-
let u=`\0PROTECT_${l}\0`;
|
|
191
|
-
span:l}of
|
|
192
|
-
originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var
|
|
193
|
-
compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function
|
|
194
|
-
" ").replace(/\s+/g," ").trim(),
|
|
159
|
+
`)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?Xo(n):n}function Xo(t){return `"${t.replace(/"/g,'""')}"`}function En(t){return t===null||typeof t=="string"||typeof t==
|
|
160
|
+
"number"||typeof t=="boolean"}function Rn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var $i="Data is the compact encoder: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; ea\
|
|
161
|
+
ch following indented line is one row of delimiter-separated values. `key[N]: a,b` is an inline list. Quoted values use CSV-style escaping.";function Fi(t={}){return {format:"compact-rows",supports(){return true},
|
|
162
|
+
encode(e){return Bi(e,t)},instruction(){return $i},decode(e){return Go(e,t)}}}var Qo=Fi();var tr={format:"csv",supports(t){return Array.isArray(t)&&Et(t)!==null},encode(t){let e=t,n=Et(e),o=n.map(er).join(","),r=e.map(s=>n.map(i=>er(s[i])).join(","));return [o,...r].join(`
|
|
163
|
+
`)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function er(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,
|
|
164
|
+
'""')}"`:e}var Rt=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[Wo,Qo,tr],this.minSavingsTokens=e.minimumSavingsTokens??
|
|
165
|
+
64,this.minSavingsRatio=e.minimumSavingsRatio??.08,this.qualityPenalty=e.qualityPenalty??(()=>0);}choose(e,n){let o={model:n.model,tokenizer:n.tokenizer},r=[];for(let l of this.serializers){if(!l.supports(
|
|
166
|
+
e))continue;let u=l.encode(e);if(l.format!=="json-compact"&&!zi(l,u,e))continue;let d=l.instruction(e),f=this.tokenizer.count(u,o),m=d?this.tokenizer.count(d,o):0,h=this.qualityPenalty(n.model??"",l.format);
|
|
167
|
+
r.push({format:l.format,encoded:u,instruction:d,payloadTokens:f,instructionTokens:m,penalty:h,total:f+m+h});}let s=r.find(l=>l.format==="json-compact"),i={};for(let l of r)i[l.format]=l.total;if(!s){let l=r[0];
|
|
168
|
+
return l?nr(l,i,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:i,instructionOverheadTokens:0,reason:"no serializer supported payload; defa\
|
|
169
|
+
ulted to JSON"}}let a=s,c="json baseline (no challenger cleared thresholds)";for(let l of r){if(l.format==="json-compact")continue;let u=s.total-l.total,d=s.total===0?0:u/s.total;u>=this.minSavingsTokens&&
|
|
170
|
+
d>=this.minSavingsRatio&&l.total<a.total&&(a=l,c=`${l.format} saved ${u} tokens (${(d*100).toFixed(1)}%) vs json`);}return nr(a,i,c)}};function zi(t,e,n){if(!t.decode)return false;try{return In(t.decode(e),
|
|
171
|
+
n)}catch{return false}}function In(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.isArray(t),o=Array.isArray(e);if(n||o){if(!n||!o||t.length!==e.
|
|
172
|
+
length)return false;for(let i=0;i<t.length;i++)if(!In(t[i],e[i]))return false;return true}let r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return false;for(let i of r)if(!Object.prototype.hasOwnProperty.
|
|
173
|
+
call(e,i)||!In(t[i],e[i]))return false;return true}function nr(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function ae(t,e,n="$"){let o=[];return On(t,e,n,o),{valid:o.length===0,errors:o}}function Vi(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
|
|
174
|
+
string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function On(t,e,n,o){switch(e.enum&&!e.enum.some(s=>Ji(s,t))&&o.push({path:n,message:"value not in enum"}),
|
|
175
|
+
e.type??Vi(t)){case "object":Ui(t,e,n,o);break;case "array":qi(t,e,n,o);break;case "string":Hi(t,e,n,o);break;case "number":case "integer":Ki(t,e,n,o);break;case "boolean":typeof t!="boolean"&&o.push({path:n,
|
|
176
|
+
message:"expected boolean"});break;case "null":t!==null&&o.push({path:n,message:"expected null"});break;}}function Ui(t,e,n,o){if(typeof t!="object"||t===null||Array.isArray(t)){o.push({path:n,
|
|
177
|
+
message:"expected object"});return}let r=t;for(let s of e.required??[])s in r||o.push({path:`${n}.${s}`,message:"missing required property"});if(e.additionalProperties===false&&e.properties){let s=new Set(
|
|
178
|
+
Object.keys(e.properties));for(let i of Object.keys(r))s.has(i)||o.push({path:`${n}.${i}`,message:"additional property not allowed"});}if(e.properties)for(let[s,i]of Object.entries(e.properties))s in r&&
|
|
179
|
+
On(r[s],i,`${n}.${s}`,o);}function qi(t,e,n,o){if(!Array.isArray(t)){o.push({path:n,message:"expected array"});return}e.maxItems!=null&&t.length>e.maxItems&&o.push({path:n,message:`array exceeds maxIte\
|
|
180
|
+
ms ${e.maxItems}`}),e.minItems!=null&&t.length<e.minItems&&o.push({path:n,message:`array below minItems ${e.minItems}`}),e.items&&t.forEach((r,s)=>On(r,e.items,`${n}[${s}]`,o));}function Hi(t,e,n,o){if(typeof t!=
|
|
181
|
+
"string"){o.push({path:n,message:"expected string"});return}if(e.maxLength!=null&&t.length>e.maxLength&&o.push({path:n,message:`string exceeds maxLength ${e.maxLength}`}),e.minLength!=null&&t.length<e.
|
|
182
|
+
minLength&&o.push({path:n,message:`string below minLength ${e.minLength}`}),e.pattern){let r=null;try{r=new RegExp(e.pattern);}catch{o.push({path:n,message:`schema pattern is not a valid regular expres\
|
|
183
|
+
sion: ${e.pattern}`});}r&&!r.test(t)&&o.push({path:n,message:"string does not match pattern"});}}function Ki(t,e,n,o){if(typeof t!="number"||Number.isNaN(t)){o.push({path:n,message:"expected number"});return}
|
|
184
|
+
e.type==="integer"&&!Number.isInteger(t)&&o.push({path:n,message:"expected integer"}),e.maximum!=null&&t>e.maximum&&o.push({path:n,message:`number exceeds maximum ${e.maximum}`}),e.minimum!=null&&t<e.
|
|
185
|
+
minimum&&o.push({path:n,message:`number below minimum ${e.minimum}`});}function Ji(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var Ct=class{contracts=new Map;register(e){return this.contracts.set(e.contractId,e),this}resolve(e){return this.contracts.get(e)}has(e){return this.contracts.has(e)}static lint(e,n="$"){let o=[];return _n(
|
|
186
|
+
e,n,o),o}};function _n(t,e,n){if(t.type==="object"){t.additionalProperties!==false&&n.push(`${e}: object should set additionalProperties:false`);for(let[o,r]of Object.entries(t.properties??{}))_n(r,`${e}\
|
|
187
|
+
.${o}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&_n(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: s\
|
|
188
|
+
tring should set maxLength or use an enum`);}function or(t,e,n){for(let o of n)if(o.supports(t,e))return {backend:o.id,reason:`first supporting backend: ${o.id}`};return {backend:"none",reason:"no constrained-decoding backend available; will valid\
|
|
189
|
+
ate + repair"}}function mu(t=()=>true){return {id:"provider-native",supports:t}}function Dn(t){let e=t.minimumContextTokens??2e3,n=t.minimumNetTokens??200;if(t.contextTokens<e)return {compress:false,reason:`context ${t.contextTokens} < ${e} min`};let o=t.projectedEliminable-t.compressorCostTokens;
|
|
190
|
+
return o<n?{compress:false,reason:`net saving ${o} < ${n} min`}:{compress:true,reason:`net saving ${o} tokens`}}function ku(t){return {async compress(e){let n=e.protectedSpans??[],o=e.text,r=[];n.forEach((c,l)=>{
|
|
191
|
+
let u=`\0PROTECT_${l}\0`;r.push({token:u,span:c}),o=o.split(c.text).join(u);});let s=await t.compress({text:o,...e.targetRatio!=null?{targetRatio:e.targetRatio}:{}}),i=s.compressed,a=true;for(let{token:c,
|
|
192
|
+
span:l}of r){if(!i.includes(c)){a=false;break}i=i.split(c).join(l.text);}return a?{...s,compressed:i,protectedSpans:n.length,fidelityPassed:true}:{compressed:e.text,originalTokens:s.originalTokens,compressedTokens:s.
|
|
193
|
+
originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var wu={async compress(t){return {compressed:t.text,originalTokens:0,
|
|
194
|
+
compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function rr(t,e){let n=i=>i.toLowerCase().replace(/[.,;:!¡?¿()[\]{}"«»…]/g,
|
|
195
|
+
" ").replace(/\s+/g," ").trim(),r=n((i=>{let a=new Set,c=[];for(let l of i.split(`
|
|
195
196
|
`)){let u=l.trim();u&&a.has(u)||(u&&a.add(u),c.push(l));}return c.join(`
|
|
196
|
-
`)})(t)),s=n(e);return !(!
|
|
197
|
-
`),
|
|
198
|
-
options.data??It(e.schema);
|
|
199
|
-
inputTokens:
|
|
200
|
-
switch(t.type){case "object":{let e={};for(let n of t.required??[]){let
|
|
201
|
-
items?[It(t.items)]:[];case "string":return "mock";case "number":case "integer":return t.minimum??0;case "boolean":return true;case "null":return null;default:return null}}function
|
|
202
|
-
{servido:t,factor:e,conDescuento:e<1}}function
|
|
197
|
+
`)})(t)),s=n(e);return !(!Sn(et(r),et(s))||nt(tt(r))!==nt(tt(s)))}var sr=new WeakSet;function ir(t){sr.add(t);}var An=class{id="mock";options;constructor(e={}){this.options=e,ir(this);}async generate(e){let n=e.messages.map(a=>a.content).join(`
|
|
198
|
+
`),o=Ne.count(n);if(e.tools&&e.tools.length>0){let a=JSON.stringify(e.tools.map(c=>({name:c.id,description:c.description,parameters:c.parameters??{}})));o+=Ne.count(a);}let r,s=false;if(e.schema){let a=this.
|
|
199
|
+
options.data??It(e.schema);r=JSON.stringify(a),s=true;}else r=this.options.answer??`mock-response(${e.model})`;let i=Math.min(e.maxOutputTokens??Number.MAX_SAFE_INTEGER,Ne.count(r));return {text:r,usage:{
|
|
200
|
+
inputTokens:o,outputTokens:i,...this.options.cachedInputTokens!=null?{cachedInputTokens:this.options.cachedInputTokens}:{}},structuredNatively:s}}};function It(t){if(t.enum&&t.enum.length>0)return t.enum[0];
|
|
201
|
+
switch(t.type){case "object":{let e={};for(let n of t.required??[]){let o=t.properties?.[n];e[n]=o?It(o):null;}for(let[n,o]of Object.entries(t.properties??{}))n in e||(e[n]=It(o));return e}case "array":return t.
|
|
202
|
+
items?[It(t.items)]:[];case "string":return "mock";case "number":case "integer":return t.minimum??0;case "boolean":return true;case "null":return null;default:return null}}function Ou(t){return new An(t)}var Wi={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},Ot="flex";function cr(t){if(t==null||t==="")return null;let e=Wi[t];return e==null?{servido:t,factor:null,conDescuento:false}:
|
|
203
|
+
{servido:t,factor:e,conDescuento:e<1}}function lr(t,e){return !t||t.factor==null||!t.conDescuento||!Number.isFinite(e)||e<=0?null:e*(1-t.factor)}var Gi="slower and variable: OpenAI publishes no latency\
|
|
203
204
|
commitment for the flex tier. What IS documented is the failure shape \u2014 the default SDK timeout is 10 minutes and a request that exceeds it returns 408, and when flex capacity is short the request re\
|
|
204
|
-
turns 429 and is not charged. Do not put a deferrable request on a user-facing path.",
|
|
205
|
-
was scheduled exactly as it would have been.",
|
|
206
|
-
count lives only in the asynchronous batch API, which is not a request/response call";function
|
|
207
|
-
"${t}" tier.`}var
|
|
208
|
-
map(String):[];if(
|
|
209
|
-
isArray(s)&&s.some(i=>!De(i)))return false}let
|
|
210
|
-
test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.test(t)}function
|
|
205
|
+
turns 429 and is not charged. Do not put a deferrable request on a user-facing path.",Yi="unchanged: this provider has no cheaper synchronous processing tier, so nothing was asked for and the request \
|
|
206
|
+
was scheduled exactly as it would have been.",ur="this provider has no cheaper synchronous processing tier, so the request was sent unchanged and nothing is credited; on this provider the deferred dis\
|
|
207
|
+
count lives only in the asynchronous batch API, which is not a request/response call";function dr(t){return t==null||t===""?Yi:t===Ot?Gi:`unknown: this layer has no published latency statement for the\
|
|
208
|
+
"${t}" tier.`}var pr=new Set;function G(t,e){pr.has(t)||(pr.add(t),console.warn(e));}function De(t){if(t==null||typeof t!="object")return true;let e=t,n=e.properties;if(n&&typeof n=="object"){if(e.additionalProperties!==false)return false;let r=Object.keys(n),s=Array.isArray(e.required)?e.required.
|
|
209
|
+
map(String):[];if(r.some(i=>!s.includes(i)))return false;for(let i of Object.values(n))if(!De(i))return false}if(e.items!==void 0&&!De(e.items))return false;for(let r of ["anyOf","oneOf","allOf"]){let s=e[r];if(Array.
|
|
210
|
+
isArray(s)&&s.some(i=>!De(i)))return false}let o=e.$defs??e.definitions;return !(o&&typeof o=="object"&&Object.values(o).some(r=>!De(r)))}function Zi(t){return !/response_format/i.test(t)||/invalid schema/i.
|
|
211
|
+
test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.test(t)}function Xi(t){return `Respond with a single JSON object and nothing else: no prose, no\
|
|
211
212
|
explanation, no markdown code fences. The object must validate against this JSON Schema:
|
|
212
|
-
`+JSON.stringify(t)}var
|
|
213
|
-
opts.stripProviderPrefix?e.model.replace(/^[^/]+\//,""):e.model,
|
|
214
|
-
`provider ${
|
|
213
|
+
`+JSON.stringify(t)}var fr=class{id;opts;fetchImpl;sinResponseFormat=new Set;constructor(e){this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch;}async generate(e){let n=this.
|
|
214
|
+
opts.stripProviderPrefix?e.model.replace(/^[^/]+\//,""):e.model,o=e.schema!=null&&!this.sinResponseFormat.has(n),r=await this.enviar(n,e,o);if(!r.ok&&r.status===400&&o){let s=await mr(r);if(!Zi(s))throw new Error(
|
|
215
|
+
`provider ${r.status}: ${s}`);this.sinResponseFormat.add(n),G(`sin-response-format:${n}`,`[bvsala] El modelo "${n}" rechaza \`response_format\` con un 400: no tiene structured outputs. Se repite la peti\
|
|
215
216
|
ci\xF3n pidiendo el JSON por prompt (una sola vez: el modelo queda anotado y las siguientes van directas). El esquema sigue viajando y el layer sigue validando, pero la garant\xEDa la da el layer, no el pro\
|
|
216
|
-
veedor, y el informe lo dice: \`constraints.backend: "none"\`. Para recuperar la garant\xEDa nativa, usa un modelo con structured outputs (gpt-4o o posterior).`),
|
|
217
|
-
ok){let s=await
|
|
217
|
+
veedor, y el informe lo dice: \`constraints.backend: "none"\`. Para recuperar la garant\xEDa nativa, usa un modelo con structured outputs (gpt-4o o posterior).`),o=false,r=await this.enviar(n,e,false);}if(!r.
|
|
218
|
+
ok){let s=await mr(r);throw new Error(`provider ${r.status}: ${s}`)}return this.leer(r,e,o)}async enviar(e,n,o){let r=n.messages.map(i=>i.role==="tool"?{role:"tool",content:i.content,tool_call_id:i.toolCallId??
|
|
218
219
|
i.metadata?.tool_call_id,...i.name?{name:i.name}:{}}:i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0?{role:"assistant",content:i.content||null,tool_calls:i.toolCalls.map((a,c)=>({id:a.id??`cal\
|
|
219
|
-
l_${c}`,type:"function",function:{name:a.name,arguments:a.arguments}}))}:{role:i.role,content:i.content});n.schema&&!r
|
|
220
|
+
l_${c}`,type:"function",function:{name:a.name,arguments:a.arguments}}))}:{role:i.role,content:i.content});n.schema&&!o&&r.push({role:"system",content:Xi(n.schema)});let s={model:e,messages:r};if(n.maxOutputTokens!=
|
|
220
221
|
null&&(s.max_tokens=n.maxOutputTokens),n.temperature!=null&&(s.temperature=n.temperature),n.seed!=null&&(s.seed=n.seed),n.promptCacheKey!=null&&(s.prompt_cache_key=n.promptCacheKey),n.deferrable===true&&
|
|
221
|
-
(s.service_tier=Ot),n.schema&&
|
|
222
|
+
(s.service_tier=Ot),n.schema&&o){let i=De(n.schema);i||G("strict-incompatible","[bvsala] El contrato de respuesta no cumple el modo `strict` de OpenAI (en strict, `required` debe listar TODAS las clav\
|
|
222
223
|
es de `properties`, y todo objeto necesita `additionalProperties: false`). Se env\xEDa el esquema con `strict: false`: el modelo sigue guiado y el layer sigue validando, pero la garant\xEDa la da el layer, \
|
|
223
224
|
no el proveedor. Para recuperarla, haz obligatorias todas las claves del contrato."),s.response_format={type:"json_schema",json_schema:{name:"bvsala_contract",schema:n.schema,strict:i}};}return n.tools&&
|
|
224
225
|
n.tools.length>0&&(s.tools=n.tools.map(i=>({type:"function",function:{name:i.id,...i.description?{description:i.description}:{},parameters:i.parameters??{type:"object",properties:{}}}}))),await this.fetchImpl(
|
|
225
226
|
`${this.opts.baseUrl.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.headers},
|
|
226
|
-
body:JSON.stringify(s)})}async leer(e,n,
|
|
227
|
-
arguments??""})).filter(p=>p.name!==""),c=
|
|
227
|
+
body:JSON.stringify(s)})}async leer(e,n,o){let r=await e.json(),s=r.choices?.[0]?.message,i=s?.content??"",a=(s?.tool_calls??[]).map(p=>({...p.id?{id:p.id}:{},name:p.function?.name??"",arguments:p.function?.
|
|
228
|
+
arguments??""})).filter(p=>p.name!==""),c=r.usage??{},l=c.prompt_tokens??0,u=c.completion_tokens??0,d=typeof c.prompt_tokens!="number",f=typeof c.completion_tokens!="number";if(this.opts.requireUsage&&
|
|
228
229
|
(d||f))throw new Error(`provider returned incomplete usage (prompt=${c.prompt_tokens??"absent"}, completion=${c.completion_tokens??"absent"}); cannot measure cost. For gateways/streaming, ensure usage\
|
|
229
|
-
reporting is enabled.`);let m=
|
|
230
|
+
reporting is enabled.`);let m=r.choices?.[0]?.finish_reason,h=typeof r.service_tier=="string"&&r.service_tier!==""?r.service_tier:void 0;return {text:i,...a.length>0?{toolCalls:a}:{},...m?{finishReason:m}:
|
|
230
231
|
{},...h?{servedServiceTier:h}:{},...n.deferrable===true?{requestedServiceTier:Ot}:{},usage:{inputTokens:l,outputTokens:u,...c.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:c.prompt_tokens_details.
|
|
231
|
-
cached_tokens}:{}},structuredNatively:n.schema!=null&&
|
|
232
|
-
`+JSON.stringify(t)}var
|
|
233
|
-
let n=this.construirCuerpo(e),
|
|
234
|
-
anthropic-version":this.opts.apiVersion??"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},body:JSON.stringify(n.body)});if(!
|
|
235
|
-
: ${await
|
|
236
|
-
t has no user/assistant message. The Messages API needs at least one, and system prompts travel in the `system` field \u2014 they do not count.");let i=(e.tools??[]).map(
|
|
237
|
-
{description:
|
|
232
|
+
cached_tokens}:{}},structuredNatively:n.schema!=null&&o,raw:r}}};async function mr(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function hr(t){return `Respond with a single JSON object and nothing else: no prose, no explanation, no markdown code fences. The object must validate against this JSON Schema:
|
|
233
|
+
`+JSON.stringify(t)}var _t=4,Fe="bvsala_contract",gr=class{id;opts;fetchImpl;constructor(e={}){this.opts=e,this.id=`anthropic:${e.baseUrl??"https://api.anthropic.com/v1"}`,this.fetchImpl=e.fetchImpl??fetch;}async generate(e){
|
|
234
|
+
let n=this.construirCuerpo(e),o=(this.opts.baseUrl??"https://api.anthropic.com/v1").replace(/\/$/,""),r=await this.fetchImpl(`${o}/messages`,{method:"POST",headers:{"content-type":"application/json","\
|
|
235
|
+
anthropic-version":this.opts.apiVersion??"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},body:JSON.stringify(n.body)});if(!r.ok)throw new Error(`provider ${r.status}\
|
|
236
|
+
: ${await ta(r)}`);return this.leer(r,e,n.contratoNativo)}construirCuerpo(e){let{system:n,messages:o,prefijoEnMensajes:r,prefijoEnSystem:s}=Qi(e);if(o.length===0)throw new Error("anthropic: the reques\
|
|
237
|
+
t has no user/assistant message. The Messages API needs at least one, and system prompts travel in the `system` field \u2014 they do not count.");let i=(e.tools??[]).map(d=>({name:d.id,...d.description?
|
|
238
|
+
{description:d.description}:{},input_schema:d.parameters??{type:"object",properties:{}}})),a=false,c=false;if(e.schema){let d=i.length>0,f=i.some(h=>h.name===Fe),m=De(e.schema);f?(n.push({type:"text",text:hr(
|
|
238
239
|
e.schema)}),G("anthropic-contrato-nombre-ocupado",`[bvsala] One of your tools is already named \`${Fe}\`, so the output contract cannot travel as a tool without colliding with it (duplicate tool names \
|
|
239
|
-
are a provider error). The schema is sent as prompt text instead, which is measurably more expensive on this API. Rename that tool to get the cheaper path.`)):(!
|
|
240
|
+
are a provider error). The schema is sent as prompt text instead, which is measurably more expensive on this API. Rename that tool to get the cheaper path.`)):(!m&&!d&&G("anthropic-strict-incompatible",
|
|
240
241
|
"[bvsala] El contrato de respuesta no cumple el modo `strict` (en strict, `required` debe listar TODAS las claves de `properties`, y todo objeto necesita `additionalProperties: false`). Se env\xEDa el es\
|
|
241
|
-
quema sin `strict`: el modelo sigue guiado y el layer sigue validando, pero la garant\xEDa la da el layer, no el proveedor."),a=
|
|
242
|
+
quema sin `strict`: el modelo sigue guiado y el layer sigue validando, pero la garant\xEDa la da el layer, no el proveedor."),a=m&&!d,i.push({name:Fe,description:d?"Return the final answer in the requ\
|
|
242
243
|
ired shape. Use the other tools first if you need data; call this one instead of writing the answer as text.":"Return the final answer in the required shape.",input_schema:e.schema,...a?{strict:true}:{}}),
|
|
243
|
-
|
|
244
|
+
d&&(c=this.opts.forceAnswerThroughTool!==false,G("anthropic-contrato-con-herramientas","[bvsala] This request carries BOTH your tools and an output contract. On Anthropic's Messages API a specific shape \
|
|
244
245
|
is only GUARANTEED by forcing that exact tool, and forcing ours would leave the model unable to call yours. The contract travels as one extra tool"+(c?' and the request is sent with `tool_choice: {typ\
|
|
245
246
|
e: "any"}`, so the model must answer through SOME tool \u2014 yours or the contract \u2014 and can no longer reply in prose. Your tool turn is untouched. The guarantee is still the layer\'s, not the provider\'s (\
|
|
246
247
|
`constraints.backend: "none"`), because the model may pick one of your tools and defer the final answer to the next turn.':", not forced (`forceAnswerThroughTool: false`). The guarantee is the layer's\
|
|
247
248
|
, not the provider's (`constraints.backend: \"none\"`), and if the model answers in prose the layer pays a second full call to repair it \u2014 on this API that second call re-pays the whole tool-use overhea\
|
|
248
|
-
d.")+" Dropping either the tools or the contract from this request is what makes the guarantee free.")));}let l={model:e.model,max_tokens:e.maxOutputTokens??this.opts.defaultMaxOutputTokens??4096,messages:
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
{},...
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
return "<no body>"}}var
|
|
264
|
-
now()-this.start}all(){return this.events}};var Ae=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function
|
|
265
|
-
`"${e}" `;throw new TypeError(`${n}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let n=e&&`"${e}" `;throw new RangeError(`${n}expected integer >= 0, got ${t}`)}}function
|
|
266
|
-
let
|
|
267
|
-
new TypeError(l)}return t}function
|
|
268
|
-
o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function st(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function
|
|
269
|
-
let e="";for(let n=0;n<t.length;n++)e+=
|
|
270
|
-
t<=he.f)return t-(he.a-10)}function it(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(
|
|
271
|
-
new RangeError(
|
|
272
|
-
s)),a=
|
|
273
|
-
|
|
274
|
-
`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var
|
|
275
|
-
new Uint8Array(e),this.view=
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
ha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s);}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let
|
|
280
|
-
constructor,e.set(...this.get());let{blockLen:n,buffer:
|
|
281
|
-
|
|
282
|
-
n+r+
|
|
249
|
+
d.")+" Dropping either the tools or the contract from this request is what makes the guarantee free.")));}let l={model:e.model,max_tokens:e.maxOutputTokens??this.opts.defaultMaxOutputTokens??4096,messages:o};
|
|
250
|
+
n.length>0&&(l.system=n),e.temperature!=null&&(l.temperature=e.temperature),i.length>0&&(l.tools=i),a?l.tool_choice={type:"tool",name:Fe}:c&&(l.tool_choice={type:"any"}),e.deferrable===true&&G("anthropi\
|
|
251
|
+
c-sin-tier-diferible","[bvsala] Esta petici\xF3n se declar\xF3 diferible, pero la API de Mensajes de Anthropic NO tiene un tier s\xEDncrono m\xE1s barato: su `service_tier` elige entre capacidad prioritaria (m\xE1s \
|
|
252
|
+
cara) y est\xE1ndar, no un flex. La petici\xF3n sale sin cambios y el informe no acredita ning\xFAn descuento. El 50% por diferir existe en la Message Batches API, que es as\xEDncrona y no cabe en una llamada de \
|
|
253
|
+
petici\xF3n/respuesta.");let u=this.marcarCache(e,n,o,r,s);return this.opts.automaticCache===true&&e.stablePrefixMessages!=null&&u<Math.min(this.opts.maxCacheBreakpoints??_t,_t)&&(l.cache_control={type:"\
|
|
254
|
+
ephemeral"}),{body:l,contratoNativo:a}}marcarCache(e,n,o,r,s){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return 0;let i=Math.min(this.opts.maxCacheBreakpoints??_t,_t);if(i<=0)return 0;let a=i,
|
|
255
|
+
c=s>0?n[s-1]:void 0;if(c&&(c.cache_control={type:"ephemeral"},i-=1),i>0&&r>0){let l=o[Math.min(r,o.length)-1],u=l?.content[l.content.length-1];u&&(u.cache_control={type:"ephemeral"},i-=1);}return a-i}async leer(e,n,o){
|
|
256
|
+
let r=await e.json(),s=r.content??[],i=s.filter(b=>b.type==="text").map(b=>b.text??"").join(""),a=s.filter(b=>b.type==="tool_use"&&b.name!==Fe).map(b=>({...b.id?{id:b.id}:{},name:b.name??"",arguments:JSON.
|
|
257
|
+
stringify(b.input??{})})).filter(b=>b.name!==""),c=s.find(b=>b.type==="tool_use"&&b.name===Fe),l=c?JSON.stringify(c.input??{}):i,u=r.usage??{},d=u.cache_read_input_tokens,f=u.cache_creation_input_tokens,
|
|
258
|
+
m=(u.input_tokens??0)+(f??0)+(d??0),h=u.output_tokens??0,p=typeof u.input_tokens!="number",g=typeof u.output_tokens!="number";if(this.opts.requireUsage&&(p||g))throw new Error(`provider returned incom\
|
|
259
|
+
plete usage (input=${u.input_tokens??"absent"}, output=${u.output_tokens??"absent"}); cannot measure cost.`);let x=typeof u.service_tier=="string"&&u.service_tier!==""?u.service_tier:void 0;return {text:l,
|
|
260
|
+
...a.length>0?{toolCalls:a}:{},...r.stop_reason?{finishReason:ea(r.stop_reason)}:{},...x?{servedServiceTier:x}:{},usage:{inputTokens:m,outputTokens:h,...d!=null?{cachedInputTokens:d}:{},...f!=null?{cacheWriteInputTokens:f}:
|
|
261
|
+
{}},structuredNatively:n.schema!=null&&o,raw:r}}};function Qi(t){let e=[],n=[],o=t.stablePrefixMessages??0,r=0,s=0,i=true;return t.messages.forEach((a,c)=>{if(a.role==="system"&&i){e.push({type:"text",text:a.
|
|
262
|
+
content}),c<o&&(s=e.length);return}i=false,n.push({role:a.role==="assistant"?"assistant":"user",content:[{type:"text",text:a.content}]}),c<o&&(r=n.length);}),n.length>0&&n[0].role==="assistant"&&(n.unshift(
|
|
263
|
+
{role:"user",content:[{type:"text",text:"(continue)"}]}),r>0&&(r+=1)),{system:e,messages:n,prefijoEnMensajes:r,prefijoEnSystem:s}}function ea(t){switch(t){case "end_turn":return "stop";case "max_tokens":
|
|
264
|
+
return "length";case "tool_use":return "tool_calls";case "refusal":return "content_filter";default:return t}}async function ta(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}var rt=class{events=[];start;now;constructor(e=()=>Date.now()){this.now=e,this.start=e();}record(e,n,o){this.events.push({stage:e,outcome:n,...o?{detail:o}:{},atMs:this.now()-this.start});}elapsed(){return this.
|
|
265
|
+
now()-this.start}all(){return this.events}};var Ae=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function Pn(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Dt(t,e=""){if(typeof t!="number"){let n=e&&
|
|
266
|
+
`"${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 oe(t,e,n=""){
|
|
267
|
+
let o=Pn(t),r=t?.length,s=e!==void 0;if(!o||s&&r!==e){let i=n&&`"${n}" `,a=s?` of length ${e}`:"",c=o?`length=${r}`:`type=${typeof t}`,l=i+"expected Uint8Array"+a+", got "+c;throw o?new RangeError(l):
|
|
268
|
+
new TypeError(l)}return t}function Ln(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 xr(t,e){oe(t,void 0,"digestInt\
|
|
269
|
+
o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function st(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function At(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var yr=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",na=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Pt(t){if(oe(t),yr)return t.toHex();
|
|
270
|
+
let e="";for(let n=0;n<t.length;n++)e+=na[t[n]];return e}var he={_0:48,_9:57,A:65,F:70,a:97,f:102};function br(t){if(t>=he._0&&t<=he._9)return t-he._0;if(t>=he.A&&t<=he.F)return t-(he.A-10);if(t>=he.a&&
|
|
271
|
+
t<=he.f)return t-(he.a-10)}function it(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(yr)try{return Uint8Array.fromHex(t)}catch(r){throw r instanceof SyntaxError?
|
|
272
|
+
new RangeError(r.message):r}let e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let o=new Uint8Array(n);for(let r=0,s=0;r<n;r++,s+=2){let i=br(t.charCodeAt(
|
|
273
|
+
s)),a=br(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}o[r]=i*16+a;}return o}function Mn(...t){let e=0;for(let o=0;o<t.length;o++){let r=t[o];oe(r),e+=r.length;}let n=new Uint8Array(e);for(let o=0,r=0;o<t.length;o++){let s=t[o];n.set(s,r),r+=s.length;}return n}function vr(t,e={}){let n=(r,s)=>t(s).update(r).digest(),o=t(void 0);return n.outputLen=o.outputLen,n.blockLen=o.blockLen,n.canXOF=o.canXOF,n.create=r=>t(r),Object.assign(n,e),Object.freeze(n)}function kr(t=32){
|
|
274
|
+
Dt(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(
|
|
275
|
+
`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var wr=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var Lt=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(e,n,o,r){this.blockLen=e,this.outputLen=n,this.padOffset=o,this.isLE=r,this.buffer=
|
|
276
|
+
new Uint8Array(e),this.view=At(this.buffer);}update(e){Ln(this),oe(e);let{view:n,buffer:o,blockLen:r}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(r-this.pos,s-i);if(a===r){let c=At(e);for(;r<=s-i;i+=
|
|
277
|
+
r)this.process(c,i);continue}o.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===r&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ln(this),
|
|
278
|
+
xr(e,this),this.finished=true;let{buffer:n,view:o,blockLen:r,isLE:s}=this,{pos:i}=this;n[i++]=128,st(this.buffer.subarray(i)),this.padOffset>r-i&&(this.process(o,0),i=0);for(let d=i;d<r;d++)n[d]=0;o.setBigUint64(
|
|
279
|
+
r-8,BigInt(this.length*8),s),this.process(o,0);let a=At(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_s\
|
|
280
|
+
ha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s);}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let o=e.slice(0,n);return this.destroy(),o}_cloneInto(e){e||=new this.
|
|
281
|
+
constructor,e.set(...this.get());let{blockLen:n,buffer:o,length:r,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=r,e.pos=a,r%n&&e.buffer.set(o),e}clone(){return this._cloneInto()}};var K=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Mt=BigInt(4294967295),Sr=BigInt(32);function oa(t,e=false){return e?{h:Number(t&Mt),l:Number(t>>Sr&Mt)}:{h:Number(t>>Sr&Mt)|0,l:Number(t&Mt)|0}}function Tr(t,e=false){let n=t.length,o=new Uint32Array(n),
|
|
282
|
+
r=new Uint32Array(n);for(let s=0;s<n;s++){let{h:i,l:a}=oa(t[s],e);[o[s],r[s]]=[i,a];}return [o,r]}var Bn=(t,e,n)=>t>>>n,Nn=(t,e,n)=>t<<32-n|e>>>n,Pe=(t,e,n)=>t>>>n|e<<32-n,Le=(t,e,n)=>t<<32-n|e>>>n,at=(t,e,n)=>t<<64-n|e>>>n-32,ct=(t,e,n)=>t>>>n-32|e<<64-n;function ce(t,e,n,o){let r=(e>>>0)+(o>>>0);return {h:t+n+(r/2**32|0)|0,l:r|0}}var Er=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Rr=(t,e,n,o)=>e+n+o+(t/2**32|0)|0,Cr=(t,e,n,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Ir=(t,e,n,o,r)=>e+
|
|
283
|
+
n+o+r+(t/2**32|0)|0,Or=(t,e,n,o,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0)+(r>>>0),_r=(t,e,n,o,r,s)=>e+n+o+r+s+(t/2**32|0)|0;var Dr=Tr(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
|
|
283
284
|
"0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
|
|
284
285
|
8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
|
|
285
286
|
0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
|
|
@@ -287,329 +288,336 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
|
|
|
287
288
|
x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
|
|
288
289
|
efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
|
|
289
290
|
eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
|
|
290
|
-
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),
|
|
291
|
-
super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:
|
|
292
|
-
e|0,this.Al=n|0,this.Bh=
|
|
293
|
-
16;y++,n+=4)Te[y]=e.getUint32(n),Ee[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){let
|
|
294
|
-
|
|
295
|
-
Gh:p,Gl:g,Hh:x,Hl:b}=this;for(let y=0;y<80;y++){let
|
|
296
|
-
|
|
297
|
-
let P=
|
|
298
|
-
u|0),{h:d,l:f}=ce(this.Eh|0,this.El|0,d|0,f|0),{h:m,l:h}=ce(this.Fh|0,this.Fl|0,m|0,h|0),{h:p,l:g}=ce(this.Gh|0,this.Gl|0,p|0,g|0),{h:x,l:b}=ce(this.Hh|0,this.Hl|0,x|0,b|0),this.set(r,
|
|
299
|
-
f,m,h,p,g,x,b);}roundClean(){st(Te,Ee);}destroy(){this.destroyed=true,st(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}}
|
|
300
|
-
0;Dh=
|
|
301
|
-
xpected boolean, got type="+typeof t)}return t}function
|
|
302
|
-
"number"){let n=e&&`"${e}" `;throw new TypeError(n+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let n=e&&`"${e}" `;throw new RangeError(n+"expected safe integer, got "+t)}}function
|
|
303
|
-
function
|
|
304
|
-
return
|
|
305
|
-
"expected valid "+t+": "+n+" <= n < "+
|
|
306
|
-
`param "${s}" is invalid: expected own property`);let c=t[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${l}`)}let
|
|
307
|
-
entries(s).forEach(([a,c])=>
|
|
308
|
-
ulus, got "+e);let n=t%e;return n>=
|
|
309
|
-
umber");if(e<=
|
|
310
|
-
"invert: does not exist");return
|
|
311
|
-
e),
|
|
312
|
-
e.ONE)),
|
|
313
|
-
eql(l.sqr(d),c),x=l.cmov(u,d,g);return
|
|
314
|
-
1;)if(
|
|
291
|
+
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),sa=Dr[0],ia=Dr[1],Te=new Uint32Array(80),Ee=new Uint32Array(80),jn=class extends Lt{constructor(e){
|
|
292
|
+
super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:o,Bl:r,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:m,Gl:h,Hh:p,Hl:g}=this;return [e,n,o,r,s,i,a,c,l,u,d,f,m,h,p,g]}set(e,n,o,r,s,i,a,c,l,u,d,f,m,h,p,g){this.Ah=
|
|
293
|
+
e|0,this.Al=n|0,this.Bh=o|0,this.Bl=r|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=m|0,this.Gl=h|0,this.Hh=p|0,this.Hl=g|0;}process(e,n){for(let y=0;y<
|
|
294
|
+
16;y++,n+=4)Te[y]=e.getUint32(n),Ee[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){let T=Te[y-15]|0,C=Ee[y-15]|0,O=Pe(T,C,1)^Pe(T,C,8)^Bn(T,C,7),E=Le(T,C,1)^Le(T,C,8)^Nn(T,C,7),A=Te[y-2]|0,R=Ee[y-2]|0,S=Pe(
|
|
295
|
+
A,R,19)^at(A,R,61)^Bn(A,R,6),B=Le(A,R,19)^ct(A,R,61)^Nn(A,R,6),k=Cr(E,B,Ee[y-7],Ee[y-16]),w=Ir(k,O,S,Te[y-7],Te[y-16]);Te[y]=w|0,Ee[y]=k|0;}let{Ah:o,Al:r,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:m,Fl:h,
|
|
296
|
+
Gh:p,Gl:g,Hh:x,Hl:b}=this;for(let y=0;y<80;y++){let T=Pe(d,f,14)^Pe(d,f,18)^at(d,f,41),C=Le(d,f,14)^Le(d,f,18)^ct(d,f,41),O=d&m^~d&p,E=f&h^~f&g,A=Or(b,C,E,ia[y],Ee[y]),R=_r(A,x,T,O,sa[y],Te[y]),S=A|0,
|
|
297
|
+
B=Pe(o,r,28)^at(o,r,34)^at(o,r,39),k=Le(o,r,28)^ct(o,r,34)^ct(o,r,39),w=o&s^o&a^s&a,_=r&i^r&c^i&c;x=p|0,b=g|0,p=m|0,g=h|0,m=d|0,h=f|0,{h:d,l:f}=ce(l|0,u|0,R|0,S|0),l=a|0,u=c|0,a=s|0,c=i|0,s=o|0,i=r|0;
|
|
298
|
+
let P=Er(S,k,_);o=Rr(P,R,B,w),r=P|0;}(({h:o,l:r}=ce(this.Ah|0,this.Al|0,o|0,r|0))),{h:s,l:i}=ce(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ce(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ce(this.Dh|0,this.Dl|0,l|0,
|
|
299
|
+
u|0),{h:d,l:f}=ce(this.Eh|0,this.El|0,d|0,f|0),{h:m,l:h}=ce(this.Fh|0,this.Fl|0,m|0,h|0),{h:p,l:g}=ce(this.Gh|0,this.Gl|0,p|0,g|0),{h:x,l:b}=ce(this.Hh|0,this.Hl|0,x|0,b|0),this.set(o,r,s,i,a,c,l,u,d,
|
|
300
|
+
f,m,h,p,g,x,b);}roundClean(){st(Te,Ee);}destroy(){this.destroyed=true,st(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},$n=class extends jn{Ah=K[0]|0;Al=K[1]|0;Bh=K[2]|0;Bl=K[3]|0;Ch=K[4]|0;Cl=K[5]|
|
|
301
|
+
0;Dh=K[6]|0;Dl=K[7]|0;Eh=K[8]|0;El=K[9]|0;Fh=K[10]|0;Fl=K[11]|0;Gh=K[12]|0;Gl=K[13]|0;Hh=K[14]|0;Hl=K[15]|0;constructor(){super(64);}};var Bt=vr(()=>new $n,wr(3));var z=(t,e,n)=>oe(t,e,n),zn=Dt,Vn=Pt,le=(...t)=>Mn(...t),Ar=t=>it(t),$t=Pn,Pr=t=>kr(t),jt=BigInt(0),Fn=BigInt(1);function ze(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"e\
|
|
302
|
+
xpected boolean, got type="+typeof t)}return t}function aa(t){if(typeof t=="bigint"){if(!Nt(t))throw new RangeError("positive bigint expected, got "+t)}else zn(t);return t}function ge(t,e=""){if(typeof t!=
|
|
303
|
+
"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 Lr(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?jt:BigInt("0x"+t)}function Un(t){return Lr(Pt(t))}function be(t){return Lr(Pt(lt(oe(t)).reverse()))}
|
|
304
|
+
function qn(t,e){if(Dt(e),e===0)throw new RangeError("zero length");t=aa(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return it(n.padStart(e*2,"0"))}function Mr(t,e){
|
|
305
|
+
return qn(t,e).reverse()}function Br(t,e){if(t=z(t),e=z(e),t.length!==e.length)return false;let n=0;for(let o=0;o<t.length;o++)n|=t[o]^e[o];return n===0}function lt(t){return Uint8Array.from(z(t))}var Nt=t=>typeof t=="bigint"&&jt<=t;function ca(t,e,n){return Nt(t)&&Nt(e)&&Nt(n)&&e<=t&&t<n}function Hn(t,e,n,o){if(!ca(e,n,o))throw new RangeError(
|
|
306
|
+
"expected valid "+t+": "+n+" <= n < "+o+", got "+e)}function Kn(t){if(t<jt)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>jt;t>>=Fn,e+=1);return e}var Nr=t=>(Fn<<BigInt(t))-Fn;function Me(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function o(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(
|
|
307
|
+
`param "${s}" is invalid: expected own property`);let c=t[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${l}`)}let r=(s,i)=>Object.
|
|
308
|
+
entries(s).forEach(([a,c])=>o(a,c,i));r(e,false),r(n,true);}var Jn=()=>{throw new Error("not implemented")};var J=BigInt(0),q=BigInt(1),Be=BigInt(2),zr=BigInt(3),Vr=BigInt(4),Ur=BigInt(5),la=BigInt(7),qr=BigInt(8),ua=BigInt(9),Hr=BigInt(16);function j(t,e){if(e<=J)throw new Error("mod: expected positive mod\
|
|
309
|
+
ulus, got "+e);let n=t%e;return n>=J?n:e+n}function re(t,e,n){if(e<J)throw new Error("pow2: expected non-negative exponent, got "+e);let o=t;for(;e-- >J;)o*=o,o%=n;return o}function jr(t,e){if(t===J)throw new Error("invert: expected non-zero n\
|
|
310
|
+
umber");if(e<=J)throw new Error("invert: expected positive modulus, got "+e);let n=j(t,e),o=e,r=J,i=q;for(;n!==J;){let l=o/n,u=o-n*l,d=r-i*l;o=n,n=u,r=i,i=d;}if(o!==q)throw new Error(
|
|
311
|
+
"invert: does not exist");return j(r,e)}function Wn(t,e,n){let o=t;if(!o.eql(o.sqr(e),n))throw new Error("Cannot find square root")}function Kr(t,e){let n=t,o=(n.ORDER+q)/Vr,r=n.pow(e,o);return Wn(n,r,
|
|
312
|
+
e),r}function da(t,e){let n=t,o=(n.ORDER-Ur)/qr,r=n.mul(e,Be),s=n.pow(r,o),i=n.mul(e,s),a=n.mul(n.mul(i,Be),s),c=n.mul(i,n.sub(a,n.ONE));return Wn(n,c,e),c}function pa(t){let e=Ut(t),n=Jr(t),o=n(e,e.neg(
|
|
313
|
+
e.ONE)),r=n(e,o),s=n(e,e.neg(o)),i=(t+la)/Hr;return((a,c)=>{let l=a,u=l.pow(c,i),d=l.mul(u,o),f=l.mul(u,r),m=l.mul(u,s),h=l.eql(l.sqr(d),c),p=l.eql(l.sqr(f),c);u=l.cmov(u,d,h),d=l.cmov(m,f,p);let g=l.
|
|
314
|
+
eql(l.sqr(d),c),x=l.cmov(u,d,g);return Wn(l,x,c),x})}function Jr(t){if(t<zr)throw new Error("sqrt is not defined for small field");let e=t-q,n=0;for(;e%Be===J;)e/=Be,n++;let o=Be,r=Ut(t);for(;$r(r,o)===
|
|
315
|
+
1;)if(o++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Kr;let s=r.pow(o,e),i=(e+q)/Be;return function(c,l){let u=c;if(u.is0(l))return l;if($r(u,l)!==1)throw new Error(
|
|
315
316
|
"Cannot find square root");let d=n,f=u.mul(u.ONE,s),m=u.pow(l,e),h=u.pow(l,i);for(;!u.eql(m,u.ONE);){if(u.is0(m))return u.ZERO;let p=1,g=u.sqr(m);for(;!u.eql(g,u.ONE);)if(p++,g=u.sqr(g),p===d)throw new Error(
|
|
316
|
-
"Cannot find square root");let x=
|
|
317
|
-
t,e)&
|
|
318
|
-
reduce((r
|
|
319
|
-
id field: expected ORDER > 1, got "+t.ORDER);return t}function
|
|
320
|
-
for(;n>
|
|
321
|
-
reduceRight((a,c,l)=>
|
|
322
|
-
let n=
|
|
323
|
-
|
|
324
|
-
BITS=="number"&&(
|
|
325
|
-
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:
|
|
326
|
-
048 bytes");this.ORDER=e,this.BITS=
|
|
327
|
-
"+typeof e);return
|
|
328
|
-
e*e,this.ORDER)}add(e,n){return
|
|
329
|
-
return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return
|
|
330
|
-
isLE?
|
|
331
|
-
: expected "+
|
|
332
|
-
|
|
333
|
-
freeze(
|
|
334
|
-
throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function
|
|
335
|
-
shiftBy:i}}function
|
|
336
|
-
isNeg:f,isNegF:m,offsetF:l}}var
|
|
337
|
-
e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,
|
|
338
|
-
i=e,a=i;for(let c=0;c<
|
|
339
|
-
i=
|
|
340
|
-
ZERO){let s=
|
|
341
|
-
get(n);return
|
|
342
|
-
e);return s===1?this._unsafeLadder(e,n,
|
|
343
|
-
ds"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of ["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>
|
|
344
|
-
let
|
|
345
|
-
freeze(Object.assign({},e)),{CURVE:e,Fp:
|
|
346
|
-
let n=e,
|
|
347
|
-
sqrt(
|
|
348
|
-
b,c),g}function f(p){if(!(p instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,
|
|
317
|
+
"Cannot find square root");let x=q<<BigInt(d-p-1),b=u.pow(f,x);d=p,f=u.sqr(b),m=u.mul(m,f),h=u.mul(h,b);}return h}}function fa(t){return t%Vr===zr?Kr:t%qr===Ur?da:t%Hr===ua?pa(t):Jr(t)}var xe=(t,e)=>(j(
|
|
318
|
+
t,e)&q)===q,ma=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Wr(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=ma.
|
|
319
|
+
reduce((o,r)=>(o[r]="function",o),e);if(Me(t,n),ge(t.BYTES,"BYTES"),ge(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=q)throw new Error("inval\
|
|
320
|
+
id field: expected ORDER > 1, got "+t.ORDER);return t}function ha(t,e,n){let o=t;if(n<J)throw new Error("invalid exponent, negatives unsupported");if(n===J)return o.ONE;if(n===q)return e;let r=o.ONE,s=e;
|
|
321
|
+
for(;n>J;)n&q&&(r=o.mul(r,s)),s=o.sqr(s),n>>=q;return r}function Vt(t,e,n=false){let o=t,r=new Array(e.length).fill(n?o.ZERO:void 0),s=e.reduce((a,c,l)=>o.is0(c)?a:(r[l]=a,o.mul(a,c)),o.ONE),i=o.inv(s);return e.
|
|
322
|
+
reduceRight((a,c,l)=>o.is0(c)?a:(r[l]=o.mul(a,r[l]),o.mul(a,c)),i),r}function $r(t,e){let n=t,o=(n.ORDER-q)/Be,r=n.pow(e,o),s=n.eql(r,n.ONE),i=n.eql(r,n.ZERO),a=n.eql(r,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function ga(t,e){if(e!==void 0&&zn(e),t<=J)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);
|
|
323
|
+
let n=Kn(t);if(e!==void 0&&e<n)throw new Error(`invalid n length: expected bit length (${n}) >= n.length (${e})`);let o=e!==void 0?e:n,r=Math.ceil(o/8);return {nBitLength:o,nByteLength:r}}var Fr=new WeakMap,
|
|
324
|
+
zt=class{ORDER;BITS;BYTES;isLE;ZERO=J;ONE=q;_lengths;_mod;constructor(e,n={}){if(e<=q)throw new Error("invalid field: expected ORDER > 1, got "+e);let o;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
|
|
325
|
+
BITS=="number"&&(o=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:true}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.
|
|
326
|
+
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:r,nByteLength:s}=ga(e,o);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2\
|
|
327
|
+
048 bytes");this.ORDER=e,this.BITS=r,this.BYTES=s,Object.freeze(this);}create(e){return j(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got\
|
|
328
|
+
"+typeof e);return J<=e&&e<this.ORDER}is0(e){return e===J}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&q)===q}neg(e){return j(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return j(
|
|
329
|
+
e*e,this.ORDER)}add(e,n){return j(e+n,this.ORDER)}sub(e,n){return j(e-n,this.ORDER)}mul(e,n){return j(e*n,this.ORDER)}pow(e,n){return ha(this,e,n)}div(e,n){return j(e*jr(n,this.ORDER),this.ORDER)}sqrN(e){
|
|
330
|
+
return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return jr(e,this.ORDER)}sqrt(e){let n=Fr.get(this);return n||Fr.set(this,n=fa(this.ORDER)),n(this,e)}toBytes(e){return this.
|
|
331
|
+
isLE?Mr(e,this.BYTES):qn(e,this.BYTES)}fromBytes(e,n=false){z(e);let{_lengths:o,BYTES:r,isLE:s,ORDER:i,_mod:a}=this;if(o){if(e.length<1||!o.includes(e.length)||e.length>r)throw new Error("Field.fromBytes\
|
|
332
|
+
: expected "+o+" bytes, got "+e.length);let l=new Uint8Array(r);l.set(e,s?0:l.length-e.length),e=l;}if(e.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=s?be(e):
|
|
333
|
+
Un(e);if(a&&(c=j(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Vt(this,e)}cmov(e,n,o){return ze(o,"condition"),o?n:e}};Object.
|
|
334
|
+
freeze(zt.prototype);function Ut(t,e={}){return new zt(t,e)}var qt=BigInt(0),Xn=BigInt(1);function Gr(t,e){let n=e.negate();return t?n:e}function Kt(t,e){let n=Vt(t.Fp,e.map(o=>o.Z));return e.map((o,r)=>t.fromAffine(o.toAffine(n[r])))}function Qr(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
|
|
335
|
+
throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Gn(t,e){Qr(t,e);let n=Math.ceil(e/t)+1,o=2**(t-1),r=2**t,s=Nr(t),i=BigInt(t);return {windows:n,windowSize:o,mask:s,maxNumber:r,
|
|
336
|
+
shiftBy:i}}function Yr(t,e,n){let{windowSize:o,mask:r,maxNumber:s,shiftBy:i}=n,a=Number(t&r),c=t>>i;a>o&&(a-=s,c+=Xn);let l=e*o,u=l+Math.abs(a)-1,d=a===0,f=a<0,m=e%2!==0;return {nextN:c,offset:u,isZero:d,
|
|
337
|
+
isNeg:f,isNegF:m,offsetF:l}}var Yn=new WeakMap,es=new WeakMap;function Zn(t){return es.get(t)||1}function Zr(t){if(t!==qt)throw new Error("invalid wNAF")}var Ht=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
|
|
338
|
+
e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,o=this.ZERO){let r=e;for(;n>qt;)n&Xn&&(o=o.add(r)),r=r.double(),n>>=Xn;return o}precomputeWindow(e,n){let{windows:o,windowSize:r}=Gn(n,this.bits),s=[],
|
|
339
|
+
i=e,a=i;for(let c=0;c<o;c++){a=i,s.push(a);for(let l=1;l<r;l++)a=a.add(i),s.push(a);i=a.double();}return s}wNAF(e,n,o){if(!this.Fn.isValid(o))throw new Error("invalid scalar");let r=this.ZERO,s=this.BASE,
|
|
340
|
+
i=Gn(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:f,offsetF:m}=Yr(o,a,i);o=c,u?s=s.add(Gr(f,n[m])):r=r.add(Gr(d,n[l]));}return Zr(o),{p:r,f:s}}wNAFUnsafe(e,n,o,r=this.
|
|
341
|
+
ZERO){let s=Gn(e,this.bits);for(let i=0;i<s.windows&&o!==qt;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Yr(o,i,s);if(o=a,!l){let d=n[c];r=r.add(u?d.negate():d);}}return Zr(o),r}getPrecomputes(e,n,o){let r=Yn.
|
|
342
|
+
get(n);return r||(r=this.precomputeWindow(n,e),e!==1&&(typeof o=="function"&&(r=o(r)),Yn.set(n,r))),r}cached(e,n,o){let r=Zn(e);return this.wNAF(r,this.getPrecomputes(r,e,o),n)}unsafe(e,n,o,r){let s=Zn(
|
|
343
|
+
e);return s===1?this._unsafeLadder(e,n,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,o),n,r)}createCache(e,n){Qr(n,this.bits),es.set(e,n),Yn.delete(e);}hasCache(e){return Zn(e)!==1}};function Xr(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Wr(e),e}else return Ut(t,{isLE:n})}function ts(t,e,n={},o){if(o===void 0&&(o=t==="edwar\
|
|
344
|
+
ds"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of ["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>qt))throw new Error(`CURVE.${c} must be positive bigint`)}
|
|
345
|
+
let r=Xr(e.p,n.Fp,o),s=Xr(e.n,n.Fn,o),a=["Gx","Gy","a","d"];for(let c of a)if(!r.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.
|
|
346
|
+
freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:s}}function ns(t,e){return function(o){let r=t(o);return {secretKey:r,publicKey:e(r)}}}var Re=BigInt(0),H=BigInt(1),Qn=BigInt(2),ba=BigInt(8);function xa(t,e,n,o){let r=t.sqr(n),s=t.sqr(o),i=t.add(t.mul(e.a,r),s),a=t.add(t.ONE,t.mul(e.d,t.mul(r,s)));return t.eql(i,a)}function os(t,e={}){
|
|
347
|
+
let n=e,o=ts("edwards",t,n,n.FpFnLE),{Fp:r,Fn:s}=o,i=o.CURVE,{h:a}=i;Me(n,{},{uvRatio:"function"});let c=Qn<<BigInt(s.BYTES*8)-H,l=p=>r.create(p),u=n.uvRatio===void 0?(p,g)=>{try{return {isValid:!0,value:r.
|
|
348
|
+
sqrt(r.div(p,g))}}catch{return {isValid:false,value:Re}}}:n.uvRatio;if(!xa(r,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(p,g,x=false){let b=x?H:Re;return Hn("coordinate "+p,g,
|
|
349
|
+
b,c),g}function f(p){if(!(p instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,H,l(i.Gx*i.Gy));static ZERO=new m(Re,H,H,Re);static Fp=r;static Fn=s;X;Y;Z;T;constructor(g,x,b,y){
|
|
349
350
|
this.X=d("x",g),this.Y=d("y",x),this.Z=d("z",b,true),this.T=d("t",y),Object.freeze(this);}static CURVE(){return i}static fromAffine(g){if(g instanceof m)throw new Error("extended point not allowed");let{
|
|
350
|
-
x,y:b}=g||{};return d("x",x),d("y",b),new m(x,b,
|
|
351
|
-
ORDER;
|
|
352
|
-
"bad point: x=0 and x_0=1");return P!==_&&(w=l(-w)),m.fromAffine({x:w,y:
|
|
353
|
-
return h.createCache(this,g),x||this.multiply(
|
|
354
|
-
|
|
355
|
-
f(g);let{X:x,Y:b,Z:y}=this,{X:
|
|
356
|
-
let{a:g}=i,{X:x,Y:b,Z:y}=this,
|
|
357
|
-
Y:
|
|
358
|
-
this.add(g.negate())}multiply(g){if(!s.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:b}=h.cached(this,g,y=>
|
|
359
|
-
if(!s.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===Re?m.ZERO:this.is0()||g===
|
|
360
|
-
return h.unsafe(this,i.n).is0()}toAffine(g){let x=this,b=g,{X:y,Y:
|
|
361
|
-
was invalid");return {x:
|
|
362
|
-
return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let h=new
|
|
363
|
-
this.ep=e;}static fromBytes(e){
|
|
364
|
-
return this.ep.toAffine(e)}toHex(){return
|
|
351
|
+
x,y:b}=g||{};return d("x",x),d("y",b),new m(x,b,H,l(x*b))}static fromBytes(g,x=false){let b=r.BYTES,{a:y,d:T}=i;g=lt(z(g,b,"point")),ze(x,"zip215");let C=lt(g),O=g[b-1];C[b-1]=O&-129;let E=be(C),A=x?c:r.
|
|
352
|
+
ORDER;Hn("point.y",E,Re,A);let R=l(E*E),S=l(R-H),B=l(T*R-y),{isValid:k,value:w}=u(S,B);if(!k)throw new Error("bad point: invalid y coordinate");let _=(w&H)===H,P=(O&128)!==0;if(!x&&w===Re&&P)throw new Error(
|
|
353
|
+
"bad point: x=0 and x_0=1");return P!==_&&(w=l(-w)),m.fromAffine({x:w,y:E})}static fromHex(g,x=false){return m.fromBytes(Ar(g),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,x=true){
|
|
354
|
+
return h.createCache(this,g),x||this.multiply(Qn),this}assertValidity(){let g=this,{a:x,d:b}=i;if(g.is0())throw new Error("bad point: ZERO");let{X:y,Y:T,Z:C,T:O}=g,E=l(y*y),A=l(T*T),R=l(C*C),S=l(R*R),
|
|
355
|
+
B=l(E*x),k=l(R*l(B+A)),w=l(S+l(b*l(E*A)));if(k!==w)throw new Error("bad point: equation left != right (1)");let _=l(y*T),P=l(C*O);if(_!==P)throw new Error("bad point: equation left != right (2)")}equals(g){
|
|
356
|
+
f(g);let{X:x,Y:b,Z:y}=this,{X:T,Y:C,Z:O}=g,E=l(x*O),A=l(T*y),R=l(b*O),S=l(C*y);return E===A&&R===S}is0(){return this.equals(m.ZERO)}negate(){return new m(l(-this.X),this.Y,this.Z,l(-this.T))}double(){
|
|
357
|
+
let{a:g}=i,{X:x,Y:b,Z:y}=this,T=l(x*x),C=l(b*b),O=l(Qn*l(y*y)),E=l(g*T),A=x+b,R=l(l(A*A)-T-C),S=E+C,B=S-O,k=E-C,w=l(R*B),_=l(S*k),P=l(R*k),N=l(B*S);return new m(w,_,N,P)}add(g){f(g);let{a:x,d:b}=i,{X:y,
|
|
358
|
+
Y:T,Z:C,T:O}=this,{X:E,Y:A,Z:R,T:S}=g,B=l(y*E),k=l(T*A),w=l(O*b*S),_=l(C*R),P=l((y+T)*(E+A)-B-k),N=_-w,V=_+w,I=l(k-x*B),X=l(P*N),$=l(V*I),Q=l(P*I),W=l(N*V);return new m(X,$,W,Q)}subtract(g){return f(g),
|
|
359
|
+
this.add(g.negate())}multiply(g){if(!s.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:b}=h.cached(this,g,y=>Kt(m,y));return Kt(m,[x,b])[0]}multiplyUnsafe(g){
|
|
360
|
+
if(!s.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===Re?m.ZERO:this.is0()||g===H?this:h.unsafe(this,g,x=>Kt(m,x))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){
|
|
361
|
+
return h.unsafe(this,i.n).is0()}toAffine(g){let x=this,b=g,{X:y,Y:T,Z:C}=x,O=x.is0();b==null&&(b=O?ba:r.inv(C));let E=l(y*b),A=l(T*b),R=r.mul(C,b);if(O)return {x:Re,y:H};if(R!==H)throw new Error("invZ \
|
|
362
|
+
was invalid");return {x:E,y:A}}clearCofactor(){return a===H?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:x}=this.toAffine(),b=r.toBytes(x);return b[b.length-1]|=g&H?128:0,b}toHex(){return Vn(this.toBytes())}toString(){
|
|
363
|
+
return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let h=new Ht(m,s.BITS);return s.BITS>=8&&m.BASE.precompute(8),Object.freeze(m.prototype),Object.freeze(m),m}var Jt=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){
|
|
364
|
+
this.ep=e;}static fromBytes(e){Jn();}static fromHex(e){Jn();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){
|
|
365
|
+
return this.ep.toAffine(e)}toHex(){return Vn(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return true}isSmallOrder(){return false}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){
|
|
365
366
|
return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.
|
|
366
|
-
ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function
|
|
367
|
-
equired');let
|
|
368
|
-
outputLen,u=2*a.BYTES;if(l!==void 0&&(ge(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=
|
|
369
|
-
|
|
370
|
-
let w=
|
|
371
|
-
|
|
372
|
-
"context"),!!s)))}function y(
|
|
373
|
-
if(!c.isValid(Q))throw new Error("sign failed: invalid s");let
|
|
374
|
-
!!
|
|
375
|
-
ue,ve;try{
|
|
376
|
-
is0()}let O=a.BYTES,
|
|
377
|
-
try{return !!t.fromBytes(
|
|
378
|
-
P=_===32;if(!P&&_!==57)throw new Error("only defined for 25519 and 448");let
|
|
379
|
-
w));return f(_).subarray(0,w)}};return Object.freeze(
|
|
367
|
+
ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function rs(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is r\
|
|
368
|
+
equired');let o=e,r=n;Me(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=r,{BASE:i,Fp:a,Fn:c}=t,l=o.
|
|
369
|
+
outputLen,u=2*a.BYTES;if(l!==void 0&&(ge(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=r.randomBytes===void 0?Pr:r.randomBytes,f=r.adjustScalarBytes===void 0?
|
|
370
|
+
k=>k:r.adjustScalarBytes,m=r.domain===void 0?(k,w,_)=>{if(ze(_,"phflag"),w.length||_)throw new Error("Contexts/pre-hash are not supported");return k}:r.domain;function h(k){return c.create(be(k))}function p(k){
|
|
371
|
+
let w=E.secretKey;z(k,E.secretKey,"secretKey");let _=z(o(k),2*w,"hashedSecretKey"),P=f(_.slice(0,w)),N=_.slice(w,2*w),V=h(P);return {head:P,prefix:N,scalar:V}}function g(k){let{head:w,prefix:_,scalar:P}=p(
|
|
372
|
+
k),N=i.multiply(P),V=N.toBytes();return {head:w,prefix:_,scalar:P,point:N,pointBytes:V}}function x(k){return g(k).pointBytes}function b(k=Uint8Array.of(),...w){let _=le(...w);return h(o(m(_,z(k,void 0,
|
|
373
|
+
"context"),!!s)))}function y(k,w,_={}){k=z(k,void 0,"message"),s&&(k=s(k));let{prefix:P,scalar:N,pointBytes:V}=g(w),I=b(_.context,P,k),X=i.multiply(I).toBytes(),$=b(_.context,X,V,k),Q=c.create(I+$*N);
|
|
374
|
+
if(!c.isValid(Q))throw new Error("sign failed: invalid s");let W=le(X,c.toBytes(Q));return z(W,E.signature,"result")}let T={zip215:r.zip215};function C(k,w,_,P=T){let{context:N}=P,V=P.zip215===void 0?
|
|
375
|
+
!!T.zip215:P.zip215,I=E.signature;k=z(k,I,"signature"),w=z(w,void 0,"message"),_=z(_,E.publicKey,"publicKey"),V!==void 0&&ze(V,"zip215"),s&&(w=s(w));let X=I/2,$=k.subarray(0,X),Q=be(k.subarray(X,I)),W,
|
|
376
|
+
ue,ve;try{W=t.fromBytes(_,V),ue=t.fromBytes($,V),ve=i.multiplyUnsafe(Q);}catch{return false}if(!V&&W.isSmallOrder())return false;let ke=b(N,$,_,w);return ue.add(W.multiplyUnsafe(ke)).subtract(ve).clearCofactor().
|
|
377
|
+
is0()}let O=a.BYTES,E={secretKey:O,publicKey:O,signature:2*O,seed:O};function A(k){return k=k===void 0?d(E.seed):k,z(k,E.seed,"seed")}function R(k){return $t(k)&&k.length===E.secretKey}function S(k,w){
|
|
378
|
+
try{return !!t.fromBytes(k,w===void 0?T.zip215:w)}catch{return false}}let B={getExtendedPublicKey:g,randomSecretKey:A,isValidSecretKey:R,isValidPublicKey:S,toMontgomery(k){let{y:w}=t.fromBytes(k),_=E.publicKey,
|
|
379
|
+
P=_===32;if(!P&&_!==57)throw new Error("only defined for 25519 and 448");let N=P?a.div(H+w,H-w):a.div(w-H,w+H);return a.toBytes(N)},toMontgomerySecret(k){let w=E.secretKey;z(k,w);let _=o(k.subarray(0,
|
|
380
|
+
w));return f(_).subarray(0,w)}};return Object.freeze(E),Object.freeze(B),Object.freeze({keygen:ns(A,x),getPublicKey:x,sign:y,verify:C,utils:B,Point:t,lengths:E})}var ka=BigInt(0),ye=BigInt(1),is=BigInt(2);var wa=BigInt(5),Sa=BigInt(8),Ve=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ro={p:Ve,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Sa,
|
|
380
381
|
a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
|
|
381
|
-
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function
|
|
382
|
-
s*t%s,c=
|
|
383
|
-
return t[0]&=248,t[31]&=127,t[31]|=64,t}var
|
|
384
|
-
i=
|
|
385
|
-
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var
|
|
386
|
-
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
|
|
387
|
-
Ie.BASE);static ZERO=new t(Ie.ZERO);static Fp=Ce;static Fn=
|
|
388
|
-
oint expected")}init(e){return new t(e)}static fromBytes(e){
|
|
389
|
-
let a=s(i*i),c=s(ye+n*a),l=s(ye-n*a),u=s(c*c),d=s(l*l),f=s(n*
|
|
390
|
-
"invalid ristretto255 encoding 2");return new t(new Ie(x,b,ye,y))}static fromHex(e){return t.fromBytes(it(e))}toBytes(){let{X:e,Y:n,Z:
|
|
391
|
-
l=i(c*c),{value:u}=
|
|
392
|
-
p)}equals(e){this.assertSame(e);let{X:n,Y:
|
|
393
|
-
Oe.ZERO);Object.freeze(Oe.prototype);Object.freeze(Oe);var
|
|
382
|
+
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ta(t){let e=BigInt(10),n=BigInt(20),o=BigInt(40),r=BigInt(80),s=Ve,a=t*t%
|
|
383
|
+
s*t%s,c=re(a,is,s)*a%s,l=re(c,ye,s)*t%s,u=re(l,wa,s)*l%s,d=re(u,e,s)*u%s,f=re(d,n,s)*d%s,m=re(f,o,s)*f%s,h=re(m,r,s)*m%s,p=re(h,r,s)*m%s,g=re(p,e,s)*u%s;return {pow_p_5_8:re(g,is,s)*t%s,b2:a}}function Ea(t){
|
|
384
|
+
return t[0]&=248,t[31]&=127,t[31]|=64,t}var to=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function so(t,e){let n=Ve,o=j(e*e*e,n),r=j(o*o*e,n),s=Ta(t*r).pow_p_5_8,
|
|
385
|
+
i=j(t*o*s,n),a=j(e*i*i,n),c=i,l=j(i*to,n),u=a===t,d=a===j(-t,n),f=a===j(-t*to,n);return u&&(i=c),(d||f)&&(i=l),xe(i,n)&&(i=j(-i,n)),{isValid:u||d,value:i}}var Ie=os(ro,{uvRatio:so}),Ce=Ie.Fp,ls=Ie.Fn;function Ra(t){return rs(Ie,Bt,Object.assign({adjustScalarBytes:Ea,zip215:true},t))}var us=Ra({});var no=to;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Ia=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
|
|
386
|
+
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var as=t=>so(ye,t),Da=BigInt("0x7\
|
|
387
|
+
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),oo=t=>Ce.create(be(t)&Da);var Oe=class t extends Jt{static BASE=new t(
|
|
388
|
+
Ie.BASE);static ZERO=new t(Ie.ZERO);static Fp=Ce;static Fn=ls;constructor(e){super(e);}static fromAffine(e){return new t(Ie.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoP\
|
|
389
|
+
oint expected")}init(e){return new t(e)}static fromBytes(e){oe(e,32);let{a:n,d:o}=ro,r=Ve,s=T=>Ce.create(T),i=oo(e);if(!Br(Ce.toBytes(i),e)||xe(i,r))throw new Error("invalid ristretto255 encoding 1");
|
|
390
|
+
let a=s(i*i),c=s(ye+n*a),l=s(ye-n*a),u=s(c*c),d=s(l*l),f=s(n*o*u-d),{isValid:m,value:h}=as(s(f*d)),p=s(h*l),g=s(h*p*f),x=s((i+i)*p);xe(x,r)&&(x=s(-x));let b=s(c*g),y=s(x*b);if(!m||xe(y,r)||b===ka)throw new Error(
|
|
391
|
+
"invalid ristretto255 encoding 2");return new t(new Ie(x,b,ye,y))}static fromHex(e){return t.fromBytes(it(e))}toBytes(){let{X:e,Y:n,Z:o,T:r}=this.ep,s=Ve,i=g=>Ce.create(g),a=i(i(o+n)*i(o-n)),c=i(e*n),
|
|
392
|
+
l=i(c*c),{value:u}=as(i(a*l)),d=i(u*a),f=i(u*c),m=i(d*f*r),h;if(xe(r*m,s)){let g=i(n*no),x=i(e*no);e=g,n=x,h=i(d*Ia);}else h=f;xe(e*m,s)&&(n=i(-n));let p=i((o-n)*h);return xe(p,s)&&(p=i(-p)),Ce.toBytes(
|
|
393
|
+
p)}equals(e){this.assertSame(e);let{X:n,Y:o}=this.ep,{X:r,Y:s}=e.ep,i=l=>Ce.create(l),a=i(n*s)===i(o*r),c=i(o*s)===i(n*r);return a||c}is0(){return this.equals(t.ZERO)}};Object.freeze(Oe.BASE);Object.freeze(
|
|
394
|
+
Oe.ZERO);Object.freeze(Oe.prototype);Object.freeze(Oe);var ds=`-----BEGIN PUBLIC KEY-----
|
|
394
395
|
MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
|
|
395
|
-
-----END PUBLIC KEY-----`;function
|
|
396
|
-
length%4?"=".repeat(4-e.length%4):"";return
|
|
397
|
-
function
|
|
398
|
-
decode(
|
|
399
|
-
if(!e)return {ok:false,reason:"no verification key"};a=e;}let c;try{if(c=
|
|
400
|
-
|
|
401
|
-
ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(
|
|
402
|
-
d is not valid JSON"}}}function
|
|
403
|
-
e);if(!
|
|
404
|
-
payload:
|
|
405
|
-
if(
|
|
406
|
-
seq!="number"||typeof s.asOf!="number"||!Array.isArray(s.revoked))return
|
|
407
|
-
nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??
|
|
396
|
+
-----END PUBLIC KEY-----`;function ps(t){let e=atob(t),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n}function io(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.
|
|
397
|
+
length%4?"=".repeat(4-e.length%4):"";return ps(e+n)}function Pa(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=ps(e);return n.subarray(n.length-32)}var La=new TextEncoder,fs=new TextDecoder;
|
|
398
|
+
function Ma(t){return typeof t=="object"&&t!==null&&"keys"in t}function ao(t,e){let n=t.split(".");if(n.length!==3)return {ok:false,reason:"malformed token"};let o=n[0],r=n[1],s=n[2],i;try{i=JSON.parse(fs.
|
|
399
|
+
decode(io(o)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(Ma(e)){let u=typeof i.kid=="string"?i.kid:e.defaultKid,d=e.keys[u];if(!d)return {ok:false,reason:`unknown key id "${u}"`};a=d;}else {
|
|
400
|
+
if(!e)return {ok:false,reason:"no verification key"};a=e;}let c;try{if(c=Pa(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{return {ok:false,reason:"invalid public key"}}let l=false;try{l=us.verify(
|
|
401
|
+
io(s),La.encode(`${o}.${r}`),c);}catch{return {ok:false,reason:"signature verification error"}}return l?{ok:true,header:i,payloadBytes:io(r)}:{ok:false,reason:"bad signature"}}function Ue(t,e){let n=ao(t,e);if(!n.
|
|
402
|
+
ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(fs.decode(n.payloadBytes))}}catch{return {signatureValid:false,reason:"payloa\
|
|
403
|
+
d is not valid JSON"}}}function co(t,e,n){if(n?.has(t.jti))return "revoked";let o=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"active":e<=o?"grace":"expired"}function _d(t,e,n={}){let o=Ue(t,
|
|
404
|
+
e);if(!o.signatureValid||!o.payload)return {status:"invalid",...o.reason?{reason:o.reason}:{}};let r=o.payload,s=n.nowSeconds??Math.floor(Date.now()/1e3),i=co(r,s,n.revoked);return i==="revoked"?{status:i,
|
|
405
|
+
payload:r,reason:"license revoked"}:{status:i,payload:r}}var ms="BVSALA-REVOC",Ba=300,Na=new TextDecoder;function hs(t,e,n={}){let o=l=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:l}),r=ao(t,e);if(!r.ok||!r.payloadBytes)return o(r.reason??"bad signature");
|
|
406
|
+
if(r.header?.typ!==ms)return o(`unexpected token type "${String(r.header?.typ??"")}" (want ${ms})`);let s;try{s=JSON.parse(Na.decode(r.payloadBytes));}catch{return o("payload is not valid JSON")}if(typeof s.
|
|
407
|
+
seq!="number"||typeof s.asOf!="number"||!Array.isArray(s.revoked))return o("malformed revocation payload");let i=n.minSeq??0;if(s.seq<i)return o(`stale/rolled-back list (seq ${s.seq} < ${i})`);let a=n.
|
|
408
|
+
nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??Ba;return s.asOf>a+c?o(`asOf too far in the future (${s.asOf} > ${a+c})`):{ok:true,seq:s.seq,asOf:s.asOf,revoked:new Set(s.revoked)}}var qe=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
|
|
408
409
|
return this._seq}get asOf(){return this._asOf}get lastContactAt(){return this._lastContactAt}markContact(e){e>this._lastContactAt&&(this._lastContactAt=e);}has(e){return this.set.has(e)}snapshot(){return this.
|
|
409
|
-
set}apply(e){if(e.seq<this._seq)return false;let n=this.set.size;for(let s of e.revoked)this.set.add(s);let
|
|
410
|
-
(this._asOf=e.asOf),r
|
|
411
|
-
i,
|
|
412
|
-
return "stale"}return u},l=()=>{let u=c();return u==="active"||u==="grace"};return {isEntitled:u=>l()&&a.has(u),isActive:()=>l(),status:c,refreshAfter:()=>{if(i)return Math.min(i.expires_at,
|
|
413
|
-
0){let
|
|
414
|
-
|
|
410
|
+
set}apply(e){if(e.seq<this._seq)return false;let n=this.set.size;for(let s of e.revoked)this.set.add(s);let o=this.set.size>n,r=e.seq>this._seq;return e.seq>this._seq&&(this._seq=e.seq),e.asOf>this._asOf&&
|
|
411
|
+
(this._asOf=e.asOf),o||r}};function Wt(t,e,n){let o=()=>Math.floor((n.now?n.now():Date.now())/1e3),r=n.startedAt??o(),s=Ue(t,e),i=s.signatureValid?s.payload:void 0,a=new Set(i?.features??[]),c=()=>{if(!i)return "invalid";let u=co(
|
|
412
|
+
i,o(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(u==="active"||u==="grace")){let d=i.expires_at+i.grace_days*86400,f=Math.min(r,d),m=Math.max(n.revocation.lastContactAt,f);if(o()-m>n.maxStalenessSeconds)
|
|
413
|
+
return "stale"}return u},l=()=>{let u=c();return u==="active"||u==="grace"};return {isEntitled:u=>l()&&a.has(u),isActive:()=>l(),status:c,refreshAfter:()=>{if(i)return Math.min(i.expires_at,o()+86400)}}}function gs(t,e,n){return Wt(t,e,{revocation:new qe,...n?{now:n}:{}})}var He={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},bs=3,ja=12;function $a(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
|
|
414
|
+
0){let r=Math.pow(2,Math.min(t.consecutiveFailures,4));n=Math.min(t.maxIntervalSeconds,t.floorSeconds*r);}else {let r=t.refreshAfter!=null?t.refreshAfter-t.nowSeconds:t.pollIntervalSeconds,s=r<0?t.pollIntervalSeconds:
|
|
415
|
+
r;n=Math.min(t.pollIntervalSeconds,Math.max(t.floorSeconds,s));}let o=1+(e()*2-1)*t.jitterRatio;return Math.max(t.floorSeconds,n*o)}var Fa=10,Gt=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;warnedNoFetch=false;lastEtag=null;consecutive304=0;now(){
|
|
415
416
|
return this.opts.nowSeconds?this.opts.nowSeconds():Math.floor(Date.now()/1e3)}resolveFetch(){return this.opts.fetchImpl?this.opts.fetchImpl:typeof fetch<"u"?fetch:void 0}async pollOnce(){let e=this.resolveFetch();
|
|
416
417
|
if(!e){this.warnedNoFetch||(this.warnedNoFetch=true,console.warn("[bv-sala] no global fetch available; revocation call-home disabled (offline). License expiry is still enforced from the token.")),this.opts.
|
|
417
|
-
onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let
|
|
418
|
+
onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let o=this.opts.requestTimeoutMs??He.requestTimeoutMs,r=setTimeout(()=>n.abort(),o);r.unref?.();let s={accept:"applicati\
|
|
418
419
|
on/json"};this.lastEtag&&(s["if-none-match"]=this.lastEtag);try{let i=await e(this.opts.url,{signal:n.signal,headers:s});if(i.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.
|
|
419
|
-
now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=
|
|
420
|
-
ok)throw new Error(`revocations HTTP ${i.status}`);let a=i.headers.get("etag"),c=await i.json();if(!c.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let l=
|
|
420
|
+
now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=Fa&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!i.
|
|
421
|
+
ok)throw new Error(`revocations HTTP ${i.status}`);let a=i.headers.get("etag"),c=await i.json();if(!c.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let l=hs(c.list,this.opts.
|
|
421
422
|
publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??He.maxSkewSeconds});if(!l.ok){let d=l.reason??"rejected";this.opts.onEvent?.({type:"rejected",
|
|
422
423
|
reason:d}),this.avisar(`rechazada:${d}`,`[bv-sala] la lista de revocaciones NO verifica (${d}). Se mantiene la \xFAltima buena conocida, as\xED que las revocaciones YA conocidas se siguen aplicando, pero la\
|
|
423
424
|
s nuevas no llegan. Revise ${this.opts.url}.`);return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let u=this.opts.snapshot.apply(l);this.opts.onEvent?.(u?{type:"applied",seq:l.seq,
|
|
424
|
-
size:this.opts.snapshot.snapshot().size}:{type:"unchanged",seq:l.seq});}catch(i){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:i}),this.avisarFalloDeRed(i);}finally{clearTimeout(
|
|
425
|
+
size:this.opts.snapshot.snapshot().size}:{type:"unchanged",seq:l.seq});}catch(i){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:i}),this.avisarFalloDeRed(i);}finally{clearTimeout(r),
|
|
425
426
|
this.controller=null;}}callado(){return !!(this.opts.silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||G(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;
|
|
426
|
-
let n=this.consecutiveFailures;if(n<
|
|
427
|
-
eguidas (${
|
|
428
|
-
this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)return;let e
|
|
427
|
+
let n=this.consecutiveFailures;if(n<bs||(n-bs)%ja!==0)return;let o=e instanceof Error?e.message:String(e);console.warn(`[bv-sala] no se ha podido contactar con el servidor de revocaciones ${n} veces s\
|
|
428
|
+
eguidas (${o}). La licencia SIGUE funcionando y las revocaciones ya conocidas se siguen aplicando, pero las NUEVAS no est\xE1n llegando. Compruebe la salida hacia ${this.opts.url}.`);}start(){this.started||
|
|
429
|
+
this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){if(this.stopped)return;let e=$a({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.
|
|
429
430
|
consecutiveFailures,floorSeconds:this.opts.floorSeconds??He.floorSeconds,pollIntervalSeconds:this.opts.pollIntervalSeconds??He.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??He.maxIntervalSeconds,
|
|
430
431
|
jitterRatio:this.opts.jitterRatio??He.jitterRatio,...this.opts.random?{random:this.opts.random}:{}});this.timer=setTimeout(()=>{this.pollOnce().finally(()=>this.schedule());},e*1e3),this.timer.unref?.();}stop(){
|
|
431
432
|
this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.controller?.abort();}};var dt=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;inflight=null;fallosSeguidos=0;constructor(e){this.options=e,this.now=e.now??(()=>Date.now()),this.flushIntervalMs=
|
|
432
433
|
e.flushIntervalMs??15e3,this.maxBatch=e.maxBatch??50,this.maxBuffer=e.maxBuffer??1e3,this.ci=e.ci??false;}setSeat(e,n){e&&(this.seatId=e),this.ci=n;}record(e){this.buffer.push({report:e,at:this.now()}),this.
|
|
433
434
|
buffer.length>this.maxBuffer&&this.buffer.splice(0,this.buffer.length-this.maxBuffer),this.buffer.length>=this.maxBatch&&this.flush();}start(){this.timer||(this.timer=setInterval(()=>{this.flush();},this.
|
|
434
435
|
flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async stopAndDrain(e){this.timer&&(clearInterval(this.timer),this.timer=void 0);let n=e??
|
|
435
|
-
Math.ceil(this.maxBuffer/this.maxBatch)+4,
|
|
436
|
+
Math.ceil(this.maxBuffer/this.maxBatch)+4,o=0;for(let r=0;r<n&&this.buffer.length>0;r++){let s=this.buffer.length;if(await this.flush(),o=this.buffer.length>=s?o+1:0,o>=2)break}}async flush(){if(this.
|
|
436
437
|
inflight)return this.inflight;if(this.buffer.length!==0){this.inflight=this.hacerFlush();try{await this.inflight;}finally{this.inflight=null;}}}async hacerFlush(){let e=this.options.fetchImpl??globalThis.
|
|
437
|
-
fetch;if(!e)return;let n=this.buffer.splice(0,this.maxBatch);try{let
|
|
438
|
-
er ${this.options.serviceAccountKey}`},body:JSON.stringify(
|
|
439
|
-
|
|
440
|
-
revocada? \xBFde otra organizaci\xF3n?). Mientras no funcione NO se reporta uso: el panel dir\xE1 que no ve tr\xE1fico y los asientos facturables saldr\xE1n a cero.`),this.options.onAuthError?.(
|
|
441
|
-
(this.fallosSeguidos++,this.avisarDeFallo(
|
|
442
|
-
fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
|
|
438
|
+
fetch;if(!e)return;let n=this.buffer.splice(0,this.maxBatch);try{let o=n.map(s=>this.toWire(s)),r=await e(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bear\
|
|
439
|
+
er ${this.options.serviceAccountKey}`},body:JSON.stringify(o)});r.ok?this.fallosSeguidos=0:r.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(`el servidor respondi\xF3 ${r.status}`)):
|
|
440
|
+
r.status===401||r.status===403?(G(`metering-auth-${r.status}`,`[bv-sala] el env\xEDo de uso est\xE1 siendo rechazado con HTTP ${r.status} en ${this.options.url}. Revisa 'serviceAccountKey' (\xBFrotada? \xBF\
|
|
441
|
+
revocada? \xBFde otra organizaci\xF3n?). Mientras no funcione NO se reporta uso: el panel dir\xE1 que no ve tr\xE1fico y los asientos facturables saldr\xE1n a cero.`),this.options.onAuthError?.(r.status)):
|
|
442
|
+
(this.fallosSeguidos++,this.avisarDeFallo(r.status===404||r.status===405?`HTTP ${r.status}: la URL de env\xEDo parece equivocada`:`el servidor rechaz\xF3 el lote con HTTP ${r.status}`));}catch(o){this.
|
|
443
|
+
fallosSeguidos++,this.requeue(n),this.avisarDeFallo(o instanceof Error?o.message:"error de red");}}avisarDeFallo(e){if(this.options.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.
|
|
443
444
|
warn(`[bv-sala] el env\xEDo de uso lleva ${n} intentos seguidos fallando contra ${this.options.url} (${e}). Las peticiones SIGUEN funcionando, pero el uso no est\xE1 llegando: el panel dir\xE1 que no ve tr\xE1\
|
|
444
445
|
fico y los asientos facturables saldr\xE1n a cero. Comprueba 'meteringUrl' \u2014 por defecto es \`\${licenseServerUrl}/api/metering/usage\`.`);}requeue(e){this.buffer=[...e,...this.buffer],this.buffer.
|
|
445
446
|
length>this.maxBuffer&&(this.buffer.length=this.maxBuffer);}toWire(e){let n=e.report;return {orgId:this.options.orgId??"self",...this.seatId?{seatId:this.seatId}:{},...this.ci?{ci:true}:{},requestId:n.requestId,
|
|
446
447
|
model:n.model,at:e.at,avoidedLlm:n.calls.avoidedLlm,actualLlm:n.calls.actualLlm,baselineInputTokens:n.tokens.baselineInput,actualInputTokens:n.tokens.actualInput,eliminatedInputTokens:n.tokens.eliminatedInput,
|
|
447
448
|
compressedInputTokens:n.tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutputTokens:n.tokens.actualOutput,providerCachedInputTokens:n.tokens.providerCachedInput??0,cacheResult:n.
|
|
448
449
|
cache.result,baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{},...n.attribution?.sessionId?{sessionId:n.attribution.sessionId}:
|
|
449
|
-
{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function
|
|
450
|
-
]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function
|
|
451
|
-
t.NETLIFY)}async function
|
|
452
|
-
if(t.KUBERNETES_SERVICE_HOST||
|
|
453
|
-
t.arch,t.execPath,n,e.USER??e.USERNAME??e.LOGNAME,e.HOME??e.USERPROFILE].filter(
|
|
454
|
-
ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function
|
|
455
|
-
return false;for(let e of
|
|
456
|
-
|
|
457
|
-
|${e}`;for(let i=0;i<s.length;i++)
|
|
458
|
-
if(!
|
|
459
|
-
new wt,formatSelector:t.formatSelector??new Rt({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new Ct,constraintBackends:t.constraintBackends??[]}}var
|
|
460
|
-
e,this.pollIntervalMs=e.pollIntervalMs??
|
|
450
|
+
{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function Yt(){return globalThis.process}function za(t){if(/^[0-9a-f]{12}$/.test(t)||/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||/^ip-\d{1,3}(-\d{1,3}){3}$/i.test(t))return true;let e="[bcdfghjklmnpqrstvwxz2456789\
|
|
451
|
+
]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function Va(t){return !!(t.AWS_LAMBDA_FUNCTION_NAME??t.LAMBDA_TASK_ROOT??t.VERCEL??t.VERCEL_ENV??t.K_SERVICE??t.FUNCTION_TARGET??t.FUNCTIONS_WORKER_RUNTIME??
|
|
452
|
+
t.NETLIFY)}async function Ua(){if(Yt()?.execPath)try{let e=await import(["node","os"].join(":")),n=typeof e.hostname=="function"?e.hostname():"";return n.length>0?n:void 0}catch{return}}async function qa(t,e=Ua){
|
|
453
|
+
if(t.KUBERNETES_SERVICE_HOST||Va(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||za(n)))return n}async function Ha(){let t=Yt();if(!t||!t.env)return;let e=t.env,n=await qa(e),o=[t.platform,
|
|
454
|
+
t.arch,t.execPath,n,e.USER??e.USERNAME??e.LOGNAME,e.HOME??e.USERPROFILE].filter(r=>typeof r=="string"&&r.length>0);return o.length?o.join("|"):void 0}var Ka=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
|
|
455
|
+
ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function lo(){let t=Yt()?.env;if(!t)
|
|
456
|
+
return false;for(let e of Ka){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function Ja(t,e){let n=globalThis.crypto,o=new TextEncoder;if(n?.subtle)try{let i=await n.subtle.importKey("raw",
|
|
457
|
+
o.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",i,o.encode(e));return [...new Uint8Array(a)].map(c=>c.toString(16).padStart(2,"0")).join("")}catch{}let r=2166136261,s=`${t}\
|
|
458
|
+
|${e}`;for(let i=0;i<s.length;i++)r^=s.charCodeAt(i),r=Math.imul(r,16777619);return (r>>>0).toString(16).padStart(8,"0")}async function uo(t){let n=Yt()?.env?.BVSALA_SEAT_ID;if(n&&Wa.test(n))return n;let o=await Ha();
|
|
459
|
+
if(!o)return;let r=await Ja(t,o);if(r)return `m-${r.slice(0,32)}`}var Wa=/^[A-Za-z0-9._:/-]{1,128}$/;var xs={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function ys(t){return {exactCache:t.exactCache??new yt,semanticCache:t.semanticCache,singleflight:t.singleflight??new vt,resolvers:t.resolvers??Ho(),router:t.router??new kt,toolSelector:t.toolSelector??
|
|
460
|
+
new wt,formatSelector:t.formatSelector??new Rt({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new Ct,constraintBackends:t.constraintBackends??[]}}var Ga=36e5,Ya=7*86400,Za=3e4,Zt=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;avisadoDeCredencial=false;currentExpiresAt;currentOrg;constructor(e){this.opts=
|
|
461
|
+
e,this.pollIntervalMs=e.pollIntervalMs??Ga,this.refreshLeadSeconds=e.refreshLeadSeconds??Ya;let n=Ue(e.initialToken,e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.expires_at:
|
|
461
462
|
0,this.currentOrg=n.signatureValid?n.payload?.org_id:void 0;}start(){this.timer||(this.checkNow(),this.timer=setInterval(()=>{this.checkNow();},this.pollIntervalMs),this.timer.unref?.());}stop(){this.parado=
|
|
462
463
|
true,this.timer&&clearInterval(this.timer),this.timer=null,this.controller?.abort(),this.controller=null;}nowSeconds(){return Math.floor((this.opts.now?this.opts.now():Date.now())/1e3)}async checkNow(){if(this.
|
|
463
464
|
enVuelo||this.parado||this.currentExpiresAt-this.nowSeconds()>this.refreshLeadSeconds)return false;this.enVuelo=true;let e=new AbortController;this.controller=e;let n=setTimeout(()=>e.abort(),this.opts.requestTimeoutMs??
|
|
464
|
-
|
|
465
|
-
n/json"}});if(!
|
|
466
|
-
da falla con HTTP ${
|
|
467
|
-
de operar al terminar el periodo de gracia.`)),!1;let s=await
|
|
465
|
+
Za);n.unref?.();try{let r=await(this.opts.fetchImpl??globalThis.fetch.bind(globalThis))(this.opts.url,{signal:e.signal,headers:{authorization:`Bearer ${this.opts.serviceAccountKey}`,accept:"applicatio\
|
|
466
|
+
n/json"}});if(!r.ok)return (r.status===401||r.status===403||r.status===404)&&!this.avisadoDeCredencial&&(this.avisadoDeCredencial=!0,console.warn(`[bv-sala] la recogida autom\xE1tica de la licencia renova\
|
|
467
|
+
da falla con HTTP ${r.status} en ${this.opts.url}. Revisa 'serviceAccountKey' (\xBFrotada? \xBFde otra organizaci\xF3n?) y 'licenseServerUrl': mientras no funcione, el token NO se renovar\xE1 solo y el SDK dejar\xE1\
|
|
468
|
+
de operar al terminar el periodo de gracia.`)),!1;let s=await r.json();if(typeof s.token!="string")return !1;let i=Ue(s.token,this.opts.publicKey);return !i.signatureValid||!i.payload||i.payload.expires_at<=
|
|
468
469
|
this.currentExpiresAt||this.currentOrg&&i.payload.org_id!==this.currentOrg||this.opts.revocados?.snapshot().has(i.payload.jti)||this.parado?!1:(this.currentExpiresAt=i.payload.expires_at,this.currentOrg=
|
|
469
|
-
i.payload.org_id,this.opts.onNewToken(s.token),!0)}catch{return false}finally{clearTimeout(n),this.controller===e&&(this.controller=null),this.enVuelo=false;}}};var
|
|
470
|
-
|
|
471
|
-
n)),
|
|
472
|
-
|
|
473
|
-
|
|
470
|
+
i.payload.org_id,this.opts.onNewToken(s.token),!0)}catch{return false}finally{clearTimeout(n),this.controller===e&&(this.controller=null),this.enVuelo=false;}}};var po={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},vs={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},Xa=[["claude-fable-5-1",512],["claude-mytho\
|
|
471
|
+
s-5-1",512],["claude-fable-5",512],["claude-mythos-5",512],["claude-opus-5",512],["claude-opus-4-7",2048],["claude-opus-4-6",4096],["claude-opus-4-5",4096],["claude-haiku-4-5",4096],["claude-3-5-haiku",
|
|
472
|
+
2048]];function fo(t){for(let[e,n]of Xa)if(t===e||t.startsWith(`${e}-`))return {...vs,minimumCacheTokens:n};return vs}var mo={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1};var ks={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function Xt(t,e,n,o){let r=o.minimumCacheTokens;if(r==null||t<r)return t;let s=Math.min(e,t),i=t-s,a=Math.min(1,Math.max(0,
|
|
473
|
+
n)),c=a*s*o.cacheReadMultiplier+(1-a)*s*o.cacheWriteMultiplier;return i+c}function ho(t){let e=Xt(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=Xt(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??
|
|
474
|
+
0),o=e-n,r=t.tier.minimumCacheTokens,i=r!=null&&t.originalTokens>=r&&t.compressedTokens<r,a;if(o<=0){let c=e<t.originalTokens;a=i?`compressing drops the prompt out of the cacheable tier (${t.compressedTokens}\
|
|
475
|
+
< ${r}) and costs more than it saves`:c?`not compressing is cheaper: the provider's prefix cache already discounts this prompt (${e.toFixed(0)} vs ${n.toFixed(0)} equivalent tokens, at a ${(t.prefixHitRate*
|
|
474
476
|
100).toFixed(0)}% hit rate)`:"the saving does not cover the compressor's cost";}else i?a=`pays off even after losing the prefix cache (${(t.prefixHitRate*100).toFixed(0)}% hit rate)`:a="pays off and do\
|
|
475
|
-
es not touch the cache tier";return {comprimir:
|
|
476
|
-
|
|
477
|
-
totalTokens?null:1)}var
|
|
478
|
-
1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let
|
|
479
|
-
{marcar:true,razon:"marking cannot lose money at this tier (no write premium)",umbral:
|
|
480
|
-
|
|
481
|
-
is only observable on requests that were marked`,umbral:
|
|
482
|
-
razon:`prefix-cache marking OFF: measured hit rate ${Ke(s)} did not reach the ${Ke(
|
|
483
|
-
tokensLeidos:0,tokensEscritos:0,apagada:false};
|
|
484
|
-
if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function Ke(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var
|
|
485
|
-
if(!t||!e)return null;let
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
length||e.localeCompare(n))}function
|
|
490
|
-
for(let n of
|
|
491
|
-
e)}decidir(e,n){let
|
|
492
|
-
ation rate ${i(
|
|
493
|
-
); the escalation rate is only observable on requests that were actually routed`,observada:
|
|
494
|
-
n.equilibrio)} break-even (this is a MONEY check, not a quality one)`,observada:
|
|
495
|
-
is at or above the ${i(n.equilibrio)} break-even, so routing was costing money`,observada:
|
|
496
|
-
n&&(
|
|
497
|
-
for(let
|
|
498
|
-
[]).filter(
|
|
477
|
+
es not touch the cache tier";return {comprimir:o>0,costeComprimido:n,costeSinComprimir:e,ganancia:o,razon:a}}function ws(t){let e=r=>ho({...t,prefixHitRate:r}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,
|
|
478
|
+
o=1;for(let r=0;r<40;r++){let s=(n+o)/2;e(s)>0?n=s:o=s;}return (n+o)/2}function Qa(t){let e=ws({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(Xt(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.
|
|
479
|
+
totalTokens?null:1)}var Qt=class{exploracion;estados=new Map;constructor(e={}){this.exploracion=Math.max(1,e.exploracion??8);}costeDeExploracion(e,n){return this.exploracion*Math.max(0,n.cacheWriteMultiplier-
|
|
480
|
+
1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let o=Qa(n),r=this.estados.get(e),s=ec(r);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:o,observada:s}:o==null?
|
|
481
|
+
{marcar:true,razon:"marking cannot lose money at this tier (no write premium)",umbral:o,observada:s}:r?.apagada?{marcar:false,razon:`prefix-cache marking OFF: measured hit rate ${Ke(s)} did not reach the ${Ke(
|
|
482
|
+
o)} break-even, so marking was costing money`,umbral:o,observada:s}:r==null||r.marcadas<this.exploracion?{marcar:true,razon:`exploring the prefix cache (${r?.marcadas??0}/${this.exploracion}); hit rate \
|
|
483
|
+
is only observable on requests that were marked`,umbral:o,observada:s}:s!=null&&s>o?{marcar:true,razon:`measured hit rate ${Ke(s)} beats the ${Ke(o)} break-even`,umbral:o,observada:s}:(r.apagada=true,{marcar:false,
|
|
484
|
+
razon:`prefix-cache marking OFF: measured hit rate ${Ke(s)} did not reach the ${Ke(o)} break-even, so marking was costing money`,umbral:o,observada:s})}registrar(e,n){let o=this.estados.get(e)??{marcadas:0,
|
|
485
|
+
tokensLeidos:0,tokensEscritos:0,apagada:false};o.marcadas+=1,o.tokensLeidos+=Math.max(0,n.cachedInputTokens??0),o.tokensEscritos+=Math.max(0,n.cacheWriteInputTokens??0),this.estados.set(e,o);}};function ec(t){
|
|
486
|
+
if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function Ke(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var Ss=.5;function tc(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function nc(t){return 1-t}function oc(t,e=Ss){return e-t}function Ts(t,e,n=Ss){
|
|
487
|
+
if(!t||!e)return null;let o=tc(t,e);if(o==null||!Number.isFinite(o))return null;let r=nc(o),s=oc(o,n),i=s>0,a=c=>`${(c*100).toFixed(1)}%`;return {r:o,equilibrio:r,escaladoMaximo:s,viable:i,razon:i?`the\
|
|
488
|
+
cheap model costs ${a(o)} of the strong one, so routing pays off while escalations stay under ${a(s)} (it stops saving money at ${a(r)})`:`the cheap model costs ${a(o)} of the strong one: even with z\
|
|
489
|
+
ero escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var go={"gpt-4":"gpt-4o","gpt-4-turbo":"gpt-4o-mini","gpt-4o":"gpt-4o-mini","gpt-4.1":"gpt-4.1-mini","c\
|
|
490
|
+
laude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-opus":"claude-3-haiku","claude-3-5-sonnet":"claude-3-5-haiku"};function rc(t){return Object.keys(t).sort((e,n)=>n.length-
|
|
491
|
+
e.length||e.localeCompare(n))}function Es(t,e=go){if(!t)return null;let n=t.lastIndexOf("/"),o=n>=0?t.slice(0,n+1):"",r=n>=0?t.slice(n+1):t,s=e[t]??e[r]??sc(r,e);return !s||s===r?null:o+s}function sc(t,e){
|
|
492
|
+
for(let n of rc(e))if(t.startsWith(n)&&t.charAt(n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var en=class{exploracion;estados=new Map;constructor(e={}){this.exploracion=Math.max(1,e.exploracion??20);}costeDeExploracion(e){return this.exploracion*Math.max(0,e)}estado(e){return this.estados.get(
|
|
493
|
+
e)}decidir(e,n){let o=this.estados.get(e),r=ic(o),s=o?.enrutadas??0,i=a=>a==null?"n/a":`${(a*100).toFixed(1)}%`;return o?.apagada?{enrutar:false,razon:`model cascade OFF for this workload: measured escal\
|
|
494
|
+
ation rate ${i(r)} is at or above the ${i(n.equilibrio)} break-even, so routing was costing money`,observada:r,muestras:s}:s<this.exploracion?{enrutar:true,razon:`measuring this workload (${s}/${this.exploracion}\
|
|
495
|
+
); the escalation rate is only observable on requests that were actually routed`,observada:r,muestras:s}:r!=null&&r<n.equilibrio?{enrutar:true,razon:`measured escalation rate ${i(r)} stays under the ${i(
|
|
496
|
+
n.equilibrio)} break-even (this is a MONEY check, not a quality one)`,observada:r,muestras:s}:(o&&(o.apagada=true),{enrutar:false,razon:`model cascade OFF for this workload: measured escalation rate ${i(r)}\
|
|
497
|
+
is at or above the ${i(n.equilibrio)} break-even, so routing was costing money`,observada:r,muestras:s})}registrar(e,n){let o=this.estados.get(e)??{enrutadas:0,escaladas:0,apagada:false};o.enrutadas+=1,
|
|
498
|
+
n&&(o.escaladas+=1),this.estados.set(e,o);}};function ic(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var ac=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function cc(t){return t?bo(t)?"value-constrained":"structural":"none"}function bo(t,e=0){if(e>12)return false;let n=t;
|
|
499
|
+
for(let o of ac)if(n[o]!==void 0)return true;if(t.properties){for(let o of Object.values(t.properties))if(bo(o,e+1))return true}return !!(t.items&&bo(t.items,e+1))}function Rs(t){let e=cc(t.schema),n=(t.tools??
|
|
500
|
+
[]).filter(o=>o.risk==="write"||o.risk==="destructive");return n.length>0?{elegible:false,fuerza:e,razon:`the request carries ${n.length} write/destructive tool(s); a cheaper model's choice of ACTION can\
|
|
499
501
|
not be checked by an output contract, so the cascade never applies here`}:e==="none"?{elegible:false,fuerza:e,razon:"no output contract: the deterministic verifier would accept anything, which would repo\
|
|
500
502
|
rt a perfect escalation rate over answers nobody checked. Declare `response.schema` to route"}:{elegible:true,fuerza:e,razon:e==="value-constrained"?"output contract carries value constraints, so wrong \
|
|
501
|
-
content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function
|
|
503
|
+
content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function xo(t){let e=[];if(e.push("non-empty"),t.texto.trim()==="")return {acepta:false,
|
|
502
504
|
motivo:"the cheap model returned an empty answer",comprobaciones:e};if(e.push("final-answer"),t.pidioHerramientas)return {acepta:false,motivo:"the cheap model asked to run tools: that is an action, not a \
|
|
503
505
|
final answer, and the output contract cannot check it",comprobaciones:e};if(e.push("not-truncated"),t.finishReason==="length")return {acepta:false,motivo:"the cheap model's answer was cut off by maxOutput\
|
|
504
506
|
Tokens",comprobaciones:e};if(e.push("output-contract"),!t.schema)return {acepta:false,motivo:"no output contract to verify against",comprobaciones:e};let n;try{n=JSON.parse(t.texto);}catch{return {acepta:false,
|
|
505
|
-
motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let
|
|
506
|
-
acepta:false,motivo:`the cheap model's answer does not satisfy the output contract (${
|
|
507
|
-
JSON.parse(t),
|
|
508
|
-
le facts (free prose only)"}:
|
|
509
|
-
of a false valid \u2014 it is a reason to look, never a verdict"}}var
|
|
510
|
-
an")n.push(`b:${t}`);else if(typeof t=="string"){let
|
|
511
|
-
t")for(let
|
|
512
|
-
, because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function
|
|
513
|
-
0,t)}function
|
|
514
|
-
"object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:
|
|
515
|
-
{valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=
|
|
516
|
-
ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r
|
|
517
|
-
t);return e?JSON.stringify(e.valor):null}function
|
|
518
|
-
let o
|
|
507
|
+
motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let o=ae(n,t.schema);return o.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
|
|
508
|
+
acepta:false,motivo:`the cheap model's answer does not satisfy the output contract (${o.errors.slice(0,3).map(s=>`${s.path}: ${s.message}`).join("; ")})`,comprobaciones:e}}function Cs(t,e){let n,o;try{n=
|
|
509
|
+
JSON.parse(t),o=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let r=tn(n),s=tn(o);return r.length===0&&s.length===0?{divergen:false,motivo:"no comparab\
|
|
510
|
+
le facts (free prose only)"}:uc(r,s)?{divergen:false,motivo:"the hard values agree"}:{divergen:true,motivo:"both answers satisfy the contract but disagree on at least one hard value; this is the signature \
|
|
511
|
+
of a false valid \u2014 it is a reason to look, never a verdict"}}var lc=40;function tn(t,e=0,n=[]){if(e>12)return n;if(typeof t=="number"&&Number.isFinite(t))n.push(`n:${t}`);else if(typeof t=="boole\
|
|
512
|
+
an")n.push(`b:${t}`);else if(typeof t=="string"){let o=t.trim();o.length>0&&o.length<=lc&&n.push(`s:${o.toLowerCase()}`);}else if(Array.isArray(t))for(let o of t)tn(o,e+1,n);else if(t&&typeof t=="objec\
|
|
513
|
+
t")for(let o of Object.keys(t).sort())tn(t[o],e+1,n);return n.sort()}function uc(t,e){if(t.length!==e.length)return false;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return false;return true}var Is="the layer measures both worlds against the same provider so that no baseline can be fabricated, keeps one ledger per lever, and refuses to publish a saving whose answer got worse along the way\
|
|
514
|
+
, because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function dc(t){if(t<=0)return "";let e=Is;for(;e.length<t;)e+=Is;return e.slice(
|
|
515
|
+
0,t)}function pc(t){let e=t[0],n=-1;for(let o of t){let r=JSON.stringify(o)?.length??0;r>n&&(n=r,e=o);}return e}function yo(t){if(t.enum&&t.enum.length>0)return {valor:pc(t.enum)};switch(t.type??(t.properties?
|
|
516
|
+
"object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:dc(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?
|
|
517
|
+
{valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=yo(t.items);return n?{valor:Array.from({length:t.maxItems},()=>n.valor)}:void 0}case "ob\
|
|
518
|
+
ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[o,r]of Object.entries(t.properties)){let s=yo(r);if(!s)return;n[o]=s.valor;}return {valor:n}}default:return}}function fc(t){let e=yo(
|
|
519
|
+
t);return e?JSON.stringify(e.valor):null}function Os(t,e){let n=fc(t);return n===null?null:e(n)}var nn=16,_s=64,mc=8,hc="measured live on the same triage contract, 8 paired reps each: gpt-4o-mini wrote 16 tokens MORE (-8.2% net) and gpt-4o wrote 3 tokens FEWER (+8.0% net)";function Ds(t,e,n,o={}){
|
|
520
|
+
let r=o.minimumSavingsTokens??mc,s;try{if(wo(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};s=To(t,0);}catch(S){return {applied:false,reason:S instanceof
|
|
519
521
|
RangeError?"schema too deep or cyclic":"schema could not be compacted"}}if(s.renamed===0&&s.coded===0)return {applied:false,reason:"nothing to compact (no renameable keys, no codeable enums)"};let i=s.node;
|
|
520
|
-
if(!i)return {applied:false,reason:"nothing to compact"};let a=S=>Je(S,i,true),c=S=>Je(S,i,false),l=
|
|
521
|
-
s.compact)),m=d-f,h=Number.POSITIVE_INFINITY;for(let S of l){let
|
|
522
|
-
x=p(
|
|
522
|
+
if(!i)return {applied:false,reason:"nothing to compact"};let a=S=>Je(S,i,true),c=S=>Je(S,i,false),l=kc(t),u=gc(t,s.compact,i,l);if(!u.ok)return {applied:false,reason:u.reason};let d=e(JSON.stringify(t)),f=e(JSON.stringify(
|
|
523
|
+
s.compact)),m=d-f,h=Number.POSITIVE_INFINITY;for(let S of l){let B=e(JSON.stringify(S))-e(JSON.stringify(a(S)));B<h&&(h=B);}Number.isFinite(h)||(h=0);let p=S=>S/1e3*n.inputPer1k,g=S=>S/1e3*n.outputPer1k,
|
|
524
|
+
x=p(r),b=n.outputPer1k>0?(r-m)*n.inputPer1k/n.outputPer1k:Number.NEGATIVE_INFINITY,y=Number.isFinite(b)?b.toFixed(1):"any",T=n.inputPer1k>0?`${(n.outputPer1k/n.inputPer1k).toFixed(1)}x`:"more than",C=o.
|
|
523
525
|
evidencia;if(C==null)return {applied:false,reason:`no measured output delta for this model, so the codebook is not applied. Short field names change how much the model WRITES, and that is a property of th\
|
|
524
|
-
e model, not of the schema: ${
|
|
526
|
+
e model, not of the schema: ${hc}. Here the compact contract saves ${m} input tokens and output is billed ${T} input, so it only pays while the output delta stays above ${y} tokens. Measure yours (ben\
|
|
525
527
|
chmarks/ab-live.ts) and pass it in`};let O=C.deltaTokens;if(O<0)return {applied:false,reason:`the measured output delta is ${O} tokens: this model writes MORE from a compact contract (${C.procedencia}). T\
|
|
526
|
-
he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${
|
|
527
|
-
n.inputPer1k:m,R=`+${O} tokens (${O>0?"the model wrote LESS":"no measured change"}), ${C.procedencia}`;return
|
|
528
|
-
ut tokens ($${x.toFixed(9)}): the compact contract saves ${m} input tokens and the measured output delta is ${R}; break-even at ${y}`}:{applied:true,reason:`net saving $${
|
|
528
|
+
he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${T} input, so no schema is big enough to buy it back`};let E=p(m)+g(O),A=n.inputPer1k>0?E*1e3/
|
|
529
|
+
n.inputPer1k:m,R=`+${O} tokens (${O>0?"the model wrote LESS":"no measured change"}), ${C.procedencia}`;return E<x?{applied:false,reason:`net saving $${E.toFixed(9)}/request is below the floor of ${r} inp\
|
|
530
|
+
ut tokens ($${x.toFixed(9)}): the compact contract saves ${m} input tokens and the measured output delta is ${R}; break-even at ${y}`}:{applied:true,reason:`net saving $${E.toFixed(9)}/request (${A.toFixed(
|
|
529
531
|
1)} input tokens equivalent): the compact contract saves ${m} input tokens and the measured output delta is ${R}; break-even at ${y}`,plan:{compactSchema:s.compact,expand:c,compact:a,renamedKeys:s.renamed,
|
|
530
|
-
codedEnumValues:s.coded,schemaTokensOriginal:d,schemaTokensCompact:f,modelledShapeSavingTokens:h,measuredOutputDeltaTokens:O,outputDeltaProvenance:C.procedencia,breakEvenOutputDeltaTokens:b,netSavingUsd:
|
|
531
|
-
function
|
|
532
|
-
ok:false,reason:"compact witness does not validate against the compact schema"};if(!
|
|
533
|
-
ject"||t.type==null&&t.properties!=null}function
|
|
534
|
-
ng")?null:e}function
|
|
535
|
-
coded:0};let
|
|
536
|
-
enumBack:s},renamed:0,coded:
|
|
537
|
-
let
|
|
532
|
+
codedEnumValues:s.coded,schemaTokensOriginal:d,schemaTokensCompact:f,modelledShapeSavingTokens:h,measuredOutputDeltaTokens:O,outputDeltaProvenance:C.procedencia,breakEvenOutputDeltaTokens:b,netSavingUsd:E}}}
|
|
533
|
+
function gc(t,e,n,o){for(let r of o){if(!ae(r,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let s=Je(r,n,true);if(!ae(s,e).valid)return {
|
|
534
|
+
ok:false,reason:"compact witness does not validate against the compact schema"};if(!So(Je(s,n,false),r))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function As(t){return t.type==="ob\
|
|
535
|
+
ject"||t.type==null&&t.properties!=null}function Ps(t){return t.type==="array"||t.type==null&&t.items!=null}function bc(t){let e=t.enum;return !e||e.length===0||e.length>_s||!e.every(n=>typeof n=="stri\
|
|
536
|
+
ng")?null:e}function To(t,e){if(e>nn)throw new RangeError("schema too deep");let n=bc(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let o=Ls(n,true);if(!o)return {compact:t,renamed:0,
|
|
537
|
+
coded:0};let r=[...o].filter(([i,a])=>i!==a).length;if(r===0)return {compact:t,renamed:0,coded:0};let s=new Map;for(let[i,a]of o)s.set(a,i);return {compact:{...t,enum:n.map(i=>o.get(i))},node:{enumFwd:o,
|
|
538
|
+
enumBack:s},renamed:0,coded:r}}return As(t)?xc(t,e):Ps(t)?yc(t,e):{compact:t,renamed:0,coded:0}}function xc(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};
|
|
539
|
+
let o=0,r=0,s=new Map,i=new Map;for(let[f,m]of n){let h=To(m,e+1);i.set(f,h.compact),h.node&&s.set(f,h.node),o+=h.renamed,r+=h.coded;}let a=null;t.additionalProperties===false&&(a=Ls(n.map(([f])=>f),false));
|
|
538
540
|
let c={};for(let[f]of n)c[a?.get(f)??f]=i.get(f);let l={...t,properties:c};t.required&&(l.required=t.required.map(f=>a?.get(f)??f));let u={};if(a){let f=new Map;for(let[h,p]of a)f.set(p,h);let m=false;for(let[
|
|
539
|
-
h,p]of a)h!==p&&(m=true);if(m){u.keysFwd=a,u.keysBack=f;for(let[h,p]of a)h!==p&&(
|
|
540
|
-
if(!t.items)return {compact:t,renamed:0,coded:0};let n=
|
|
541
|
-
...t].sort(),
|
|
542
|
-
!
|
|
543
|
-
t;if(e.items&&Array.isArray(t))return t.map(s=>Je(s,e.items,n));let
|
|
544
|
-
l);s[c]=u?Je(a,u,n):a;}return s}return t}function
|
|
545
|
-
|
|
546
|
-
if(n>
|
|
547
|
-
0)return [];let
|
|
548
|
-
let
|
|
549
|
-
"integer"?Math.round(
|
|
550
|
-
values(t.properties??{}))if(
|
|
551
|
-
isArray(t),
|
|
552
|
-
return false;for(let i of
|
|
553
|
-
enums)",pares:8}},
|
|
554
|
-
Number.isFinite(
|
|
555
|
-
origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let s=
|
|
556
|
-
Velio on ${e} (${
|
|
557
|
-
|
|
541
|
+
h,p]of a)h!==p&&(m=true);if(m){u.keysFwd=a,u.keysBack=f;for(let[h,p]of a)h!==p&&(o+=1);}}s.size>0&&(u.props=s);let d=!u.keysFwd&&!u.props;return {compact:l,...d?{}:{node:u},renamed:o,coded:r}}function yc(t,e){
|
|
542
|
+
if(!t.items)return {compact:t,renamed:0,coded:0};let n=To(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function Ls(t,e){let n=[
|
|
543
|
+
...t].sort(),o=new Set,r=new Map;n.forEach((i,a)=>{let c=e?i.toUpperCase():i,l=i;for(let u=1;u<i.length;u++){let d=c.slice(0,u);if(!o.has(d)){l=d;break}}if(l===i){let u=a.toString(36);u.length<i.length&&
|
|
544
|
+
!o.has(u)&&(l=u);}o.add(l),r.set(i,l);});let s=new Set(t);for(let[i,a]of r)if(a!==i&&s.has(a))return null;return r}function Je(t,e,n){let o=n?e.enumFwd:e.enumBack;if(o&&typeof t=="string")return o.get(t)??
|
|
545
|
+
t;if(e.items&&Array.isArray(t))return t.map(s=>Je(s,e.items,n));let r=n?e.keysFwd:e.keysBack;if((r||e.props)&&vc(t)){let s={};for(let[i,a]of Object.entries(t)){let c=r?.get(i)??i,l=n?i:c,u=e.props?.get(
|
|
546
|
+
l);s[c]=u?Je(a,u,n):a;}return s}return t}function vc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function kc(t){let e=Math.min(_s,Math.max(1,vo(t,0))),n=[];for(let o=0;o<e;o++)n.push(ko(t,
|
|
547
|
+
o,0));return n}function vo(t,e){if(e>nn)return 0;let n=t.enum?.length??0;for(let o of Object.values(t.properties??{}))n=Math.max(n,vo(o,e+1));return t.items&&(n=Math.max(n,vo(t.items,e+1))),n}function ko(t,e,n){
|
|
548
|
+
if(n>nn)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(As(t)){let o={};for(let[r,s]of Object.entries(t.properties??{}))o[r]=ko(s,e,n+1);return o}if(Ps(t)){if(t.maxItems===
|
|
549
|
+
0)return [];let o=Math.max(1,t.minItems??1),r=t.maxItems!=null?Math.min(o,t.maxItems):o,s=t.items;return Array.from({length:r},()=>s?ko(s,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";
|
|
550
|
+
let o=Math.max(1,t.minLength??1),r=t.maxLength!=null?Math.min(o,t.maxLength):o;return "x".repeat(r)}case "number":case "integer":{let o=t.minimum??1;return t.maximum!=null&&o>t.maximum&&(o=t.maximum),t.type===
|
|
551
|
+
"integer"?Math.round(o):o}case "boolean":return true;case "null":return null;default:return null}}function wo(t,e){if(e>nn)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.
|
|
552
|
+
values(t.properties??{}))if(wo(n,e+1))return true;return !!(t.items&&wo(t.items,e+1))}function So(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.
|
|
553
|
+
isArray(t),o=Array.isArray(e);if(n||o){if(!n||!o||t.length!==e.length)return false;for(let i=0;i<t.length;i++)if(!So(t[i],e[i]))return false;return true}let r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)
|
|
554
|
+
return false;for(let i of r)if(!Object.prototype.hasOwnProperty.call(e,i)||!So(t[i],e[i]))return false;return true}var wc="2026-08-14",Ms={"gpt-4o-mini":{deltaTokens:-16,salidaDelBrazoA:72,contrato:"triage (6 fields, long enums)",pares:8},"gpt-4o":{deltaTokens:3,salidaDelBrazoA:75,contrato:"triage (6 fields, long \
|
|
555
|
+
enums)",pares:8}},Sc=pn(Ms);function Tc(t){return dn(Ms,Sc,t)}var on=class t{deltas=new Map;static clave(e,n){return `${e}\0${n}`}recordar(e,n,o){this.deltas.set(t.clave(e,n),o);}resolver(e,n,o){if(o!=null&&
|
|
556
|
+
Number.isFinite(o))return this.recordar(e,n,o),{deltaTokens:o,origen:"caller",procedencia:`measured by the caller for this contract on ${e}`};let r=this.deltas.get(t.clave(e,n));if(r!=null)return {deltaTokens:r,
|
|
557
|
+
origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let s=Tc(e);return s?{deltaTokens:s.deltaTokens,origen:"catalogue",procedencia:`measured by Bi\
|
|
558
|
+
Velio on ${e} (${wc}, ${s.pares} paired reps, ${s.contrato}, ${s.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};var Ro="[BiVelio Savings: resultado de herramienta antiguo recortado para bajar el coste; los resultados recientes viajan enteros.]",Ec=new TextEncoder;function Rc(t){return Ec.encode(t).length}function Cc(t,e){if(!t)return null;let n=(e??"").trim();if(n===""||n==="{}"||n==="[]")return null;let o;try{let r=JSON.parse(n);if(r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0)return null;
|
|
559
|
+
o=Eo(r);}catch{o=n;}return `${t} ${o}`}function Eo(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(Eo).join(",")}]`:`{${Object.keys(t).sort().map(n=>`${JSON.stringify(
|
|
560
|
+
n)}:${Eo(t[n])}`).join(",")}}`}function Bs(t){let e=new Map,n=new Map;for(let l of t)if(l.role==="assistant"&&l.toolCalls)for(let u of l.toolCalls)u.id&&(e.set(u.id,u.arguments),n.set(u.id,u.name));let o=[],
|
|
561
|
+
r=new Map;for(let l=0;l<t.length;l++){let u=t[l];if(u.role!=="tool")continue;o.push(l);let d=(u.toolCallId?n.get(u.toolCallId):void 0)??u.name,f=u.toolCallId?e.get(u.toolCallId):void 0,m=Cc(d,f);m!==null&&
|
|
562
|
+
r.set(l,m);}let s=o.length?o[o.length-1]:-1,i=new Map;for(let l of o){let u=r.get(l);if(u===void 0)continue;let d=i.get(u);(d===void 0||l>d)&&i.set(u,l);}let a=[],c=0;for(let l of o){if(l===s)continue;let u=r.
|
|
563
|
+
get(l);if(u===void 0||i.get(u)===l)continue;let d=Rc(t[l].content);d<1024||(a.push(l),c+=d);}return {indices:a,bytesOriginales:c}}function Ns(t,e){if(e.length===0)return t;let n=new Set(e);return t.map(
|
|
564
|
+
(o,r)=>n.has(r)?{...o,content:Ro}:o)}function Co(t,e){if(e?.cacheTier)return e.cacheTier;let n=t.toLowerCase(),o=n.indexOf("/"),r=o>0?n.slice(0,o):"",s=o>=0?n.slice(o+1):n;return r==="openai"||r==="azure-openai"?po:r==="anthropic"?fo(s):
|
|
565
|
+
r==="google"||r==="google-vertex"?mo:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(s)?po:s.startsWith("claude")?fo(s):s.startsWith("gemini")?mo:ks}function js(t){let e=t.prefix!=null,n=ho({originalTokens:t.originalTokens,
|
|
558
566
|
compressedTokens:t.compressedTokens,stablePrefixTokens:t.prefix?.stableTokens??0,prefixHitRate:t.prefix?.hitRate??0,tier:t.tier,...t.compressorCostTokens!=null?{compressorCostTokens:t.compressorCostTokens}:
|
|
559
|
-
{}});if(e)return n;let
|
|
560
|
-
compressedTokens} < ${
|
|
561
|
-
s=
|
|
567
|
+
{}});if(e)return n;let o=t.tier.minimumCacheTokens;return o!=null&&t.originalTokens>=o&&t.compressedTokens<o?{...n,comprimir:false,razon:`compressing would drop the prompt out of the cacheable tier (${t.
|
|
568
|
+
compressedTokens} < ${o}) and nobody has measured the prefix hit rate, so it cannot be claimed to pay for itself. Declare it in \`compressionEconomics.prefix\` to unlock the full decision`}:n}function Fs(t){let e=u=>u/1e3*t.precio.inputPer1k,n=u=>u/1e3*t.precio.outputPer1k,o=e(t.promptTokens+t.descriptoresLigeros)+n(t.salidaDelSondeo),r=e(t.promptTokens+t.esquemasCompletos)+n(t.salidaFinal),
|
|
569
|
+
s=o+e(t.promptTokens+t.esquemasDeLaSegunda)+n(t.salidaFinal),i=r-s,a=o,c=i>0&&i>=a,l;return i<=0?l=`descubrir cuesta m\xE1s de lo que ahorra: el prompt (${t.promptTokens} tokens) se paga dos veces y l\
|
|
562
570
|
os esquemas que se evitan (${t.esquemasCompletos-t.esquemasDeLaSegunda}) no lo cubren`:c?l=`se evitan ${t.esquemasCompletos-t.esquemasDeLaSegunda} tokens de esquema en el peor caso, bastante para paga\
|
|
563
|
-
r el prompt repetido y el sondeo`:l="la ganancia no cubre el coste de degradar: si el sondeo no elige, la petici\xF3n sale igual con todos los esquemas y el sondeo es coste puro",{aplicar:c,costeDeUnaLlamada:
|
|
564
|
-
costeDeDosLlamadas:s,ganancia:i,perdidaSiDegrada:a,razon:l}}function
|
|
565
|
-
return {id:t.id,intents:t.intents,risk:t.risk,...
|
|
566
|
-
continue}
|
|
567
|
-
|
|
568
|
-
BiVelio license key is not valid (it does not verify). Check you pasted the WHOLE key, and that it is the license key from your dashboard \u2014 not the `bvk_` service-account key, which goes in
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
a connectivity problem, not a billing one: your license is still valid. Allow outbound HTTPS to your `licenseServerUrl` (https://savings.bivelio.com by default) and retry. (license status
|
|
572
|
-
expired":case "grace":return `BiVelio license is not active. Renew your subscription at https://savings.bivelio.com/dashboard/account (license status: ${t})`;default:return `BiVelio license
|
|
573
|
-
. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function
|
|
574
|
-
|
|
575
|
-
return "licenseGate must implement isActive(): a gate that cannot prove the license is live is refused. In this published package an injected gate is not a licensing path at
|
|
576
|
-
|
|
577
|
-
this.config=e,this.deps=
|
|
578
|
-
exploration!=null?{exploracion:e.modelCascade.exploration}:{});}async generate(e){this.assertLicensed();let n={llamadas:0,falloDelProveedor:false};try{return await this.generateOptimized(e,n)}catch(
|
|
579
|
-
Ae||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||
|
|
580
|
-
e)}catch(
|
|
581
|
-
record("prefix-cache","skipped",{reason:`no cache read discount for model "${n}" (unrecognised provider, or a declared tier that does not discount reads): not claiming a cacheable prefix`}),c;if(!
|
|
571
|
+
r el prompt repetido y el sondeo`:l="la ganancia no cubre el coste de degradar: si el sondeo no elige, la petici\xF3n sale igual con todos los esquemas y el sondeo es coste puro",{aplicar:c,costeDeUnaLlamada:r,
|
|
572
|
+
costeDeDosLlamadas:s,ganancia:i,perdidaSiDegrada:a,razon:l}}function zs(t){let n=(t.description??t.intents.join("; ")).trim().split(/\r?\n/,1)[0]??"",o=n.length>$s?n.slice(0,$s-1).trimEnd()+"\u2026":n;
|
|
573
|
+
return {id:t.id,intents:t.intents,risk:t.risk,...o?{description:o}:{}}}var $s=200;function Vs(t,e,n){let o=new Map(e.map(c=>[c.id,c])),r=[],s=[],i=new Set;for(let c of t){let l=o.get(c);if(!l){s.push(c);
|
|
574
|
+
continue}r.includes(l.id)||(r.push(l.id),l.risk==="read"&&i.size<Math.max(0,n)&&i.add(l.id));}return {tools:e.filter(c=>c.risk!=="read"||i.has(c.id)),reconocidos:r,ignorados:s}}function Us(t,e){let n=0,
|
|
575
|
+
o=[];for(let r of t)r.risk==="read"?o.push(r.tokens):n+=r.tokens;o.sort((r,s)=>s-r);for(let r of o.slice(0,Math.max(0,e)))n+=r;return n}var Io=true,Js=new WeakSet;function Ic(t){typeof t=="object"&&t!==null&&Js.add(t);}function Oc(t){return typeof t=="object"&&t!==null&&Js.has(t)}function Ks(t){switch(t){case "none":return _c();case "inval\
|
|
576
|
+
id":return "BiVelio license key is not valid (it does not verify). Check you pasted the WHOLE key, and that it is the license key from your dashboard \u2014 not the `bvk_` service-account key, which goes in\
|
|
577
|
+
`serviceAccountKey`. Keys: https://savings.bivelio.com/dashboard/install (license status: invalid)";case "revoked":return "BiVelio license has been revoked. If this is unexpected, check your billing st\
|
|
578
|
+
atus at https://savings.bivelio.com/dashboard/account or write to support@bivelio.com (license status: revoked)";case "stale":return "BiVelio could not confirm your license with the control plane in tim\
|
|
579
|
+
e \u2014 this is a connectivity problem, not a billing one: your license is still valid. Allow outbound HTTPS to your `licenseServerUrl` (https://savings.bivelio.com by default) and retry. (license status:\
|
|
580
|
+
stale)";case "expired":case "grace":return `BiVelio license is not active. Renew your subscription at https://savings.bivelio.com/dashboard/account (license status: ${t})`;default:return `BiVelio license\
|
|
581
|
+
is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function _c(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 the signe\
|
|
582
|
+
d token from your subscription, verified offline. This published package has no unlicensed mode. Copy your key and a ready-to-paste snippet at https://savings.bivelio.com/dashboard/install (license st\
|
|
583
|
+
atus: none)"}function Dc(){return "licenseGate must implement isActive(): a gate that cannot prove the license is live is refused. In this published package an injected gate is not a licensing path at \
|
|
584
|
+
all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var rn=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new Qt;verjaDeCascada;memoriaDelCodebook=new on;constructor(e){
|
|
585
|
+
this.config=e,this.deps=ys(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>fn()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.verjaDeCascada=new en(e.modelCascade?.
|
|
586
|
+
exploration!=null?{exploracion:e.modelCascade.exploration}:{});}async generate(e){this.assertLicensed();let n={llamadas:0,falloDelProveedor:false};try{return await this.generateOptimized(e,n)}catch(o){if(o instanceof
|
|
587
|
+
Ae||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||Oc(o))throw o;return await this.failOpenDirect(e,o)}}async llamarProveedor(e,n){n.llamadas+=1;try{return await this.config.provider.generate(
|
|
588
|
+
e)}catch(o){throw n.falloDelProveedor=true,o}}decidirMarcadoDeCache(e,n,o,r,s,i,a){let c={marcar:false,huella:"",mensajesDePrefijo:0,cacheWriteMultiplier:1},l=$c(n,this.config.compressionEconomics);if(!l)return a.
|
|
589
|
+
record("prefix-cache","skipped",{reason:`no cache read discount for model "${n}" (unrecognised provider, or a declared tier that does not discount reads): not claiming a cacheable prefix`}),c;if(!r.setIsStable)
|
|
582
590
|
return a.record("prefix-cache","skipped",{reason:"the tool SET is selected per request; tools render first, so the prefix cannot hit. Pruning wins here (it is a measured saving); pass the tools you wa\
|
|
583
591
|
nt fixed."}),c;if(s)return a.record("prefix-cache","skipped",{reason:"savings.toolDiscovery is on: which schemas travel is decided by a non-deterministic probe, so the tool block \u2014 which renders first\
|
|
584
592
|
\u2014 varies across requests that would share a prefix fingerprint. Marking would pay the 1.25x write premium for a prefix that cannot hit. Turn tool discovery off to reclaim the prefix cache."}),c;
|
|
585
|
-
if(i<=0)return c;let u=
|
|
593
|
+
if(i<=0)return c;let u=o.slice(0,i),d=this.tokensFor(this.assemblePromptText(u,r.tools),e),f=this.tokensFor(this.assemblePromptText(o,r.tools),e),m=ie(Se({model:n,tools:(r.tools??[]).map(p=>p.id),prefijo:u.
|
|
586
594
|
map(p=>`${p.role}:${p.content}`)})),h=this.verjaDeCache.decidir(m,{totalTokens:f,stablePrefixTokens:d,tier:l});return a.record("prefix-cache",h.marcar?"marked":"skipped",{reason:h.razon,stablePrefixTokens:d,
|
|
587
|
-
breakEvenHitRate:h.umbral,observedHitRate:h.observada}),h.marcar?{marcar:true,huella:m,mensajesDePrefijo:i,cacheWriteMultiplier:l.cacheWriteMultiplier}:c}decidirCascada(e,n,r
|
|
595
|
+
breakEvenHitRate:h.umbral,observedHitRate:h.observada}),h.marcar?{marcar:true,huella:m,mensajesDePrefijo:i,cacheWriteMultiplier:l.cacheWriteMultiplier}:c}decidirCascada(e,n,o,r){let s=o.modelCascade??"o\
|
|
588
596
|
ff",i={modo:"off",modeloPedido:e.model,modeloServido:e.model,candidato:null,enruta:false,elegible:false,razon:"the model cascade is off",fuerza:"none",bucket:"",economia:null,observada:null,muestras:0,precioBarato:null,
|
|
589
|
-
tasaDeMuestreo:0};if(s==="off")return i;let a=
|
|
590
|
-
void 0,d=
|
|
597
|
+
tasaDeMuestreo:0};if(s==="off")return i;let a=Rs({schema:e.response?.schema,tools:e.tools}),c=Es(e.model,this.config.modelCascade?.pairs??go),l=this.precioConocido(e.model),u=c?this.precioConocido(c):
|
|
598
|
+
void 0,d=Ts(u,l),f=ie(Se({tenant:n.tenantId,scope:n.authorizationScope,contract:n.contractId,schema:n.schemaVersion,fuerte:e.model,barato:c,tools:n.toolsetHash})),m=this.verjaDeCascada.estado(f),h={modo:s,
|
|
591
599
|
modeloPedido:e.model,modeloServido:e.model,candidato:c,enruta:false,elegible:false,razon:a.razon,fuerza:a.fuerza,bucket:f,economia:d,observada:m&&m.enrutadas>0?m.escaladas/m.enrutadas:null,muestras:m?.enrutadas??
|
|
592
|
-
0,precioBarato:u??null,tasaDeMuestreo:0},p=b=>(
|
|
600
|
+
0,precioBarato:u??null,tasaDeMuestreo:0},p=b=>(r.record("model-cascade",s==="on"?"not routed":"not eligible",{reason:b}),{...h,razon:b});if(!a.elegible)return p(a.razon);if(!c)return p(`no cheaper mod\
|
|
593
601
|
el is paired with "${e.model}"; declare one in createSavingsLayer({ modelCascade: { pairs } }) if your provider has one`);if(!d){let b=[...this.precioConocido(e.model)?[]:[e.model],...u?[]:[c]];return p(
|
|
594
602
|
`no known price for ${b.map(y=>`"${y}"`).join(" or ")||"this pair"}, so the arithmetic that decides whether routing pays cannot be run. The illustrative default price is deliberately NOT used here: it\
|
|
595
603
|
would approve a pair nobody has priced. Pass \`costModels\` for both models to enable the cascade for them`)}if(!d.viable)return p(d.razon);let g=Math.min(1,Math.max(0,this.config.modelCascade?.shadowSampleRate??
|
|
596
|
-
0));if(s==="shadow")return
|
|
604
|
+
0));if(s==="shadow")return r.record("model-cascade","shadow",{candidateModel:c,costRatio:d.r,breakEvenEscalationRate:d.equilibrio,verifier:a.fuerza,workload:f,note:"measuring only: the request goes to\
|
|
597
605
|
the model you asked for. The escalation rate is not a quality score \u2014 a well-formed answer with wrong content passes the verifier."}),{...h,elegible:true,razon:a.razon,tasaDeMuestreo:g};let x=this.
|
|
598
606
|
verjaDeCascada.decidir(f,d);return x.enrutar?(this.avisar(`cascada:${e.model}->${c}`,`[bv-sala] model cascade ON: requests for "${e.model}" may be answered by "${c}" when a deterministic gate accepts \
|
|
599
607
|
the answer. The gate checks the SHAPE of the answer against your output contract, never its meaning, so a well-formed answer with wrong content is served and counted as a success. report.model always \
|
|
600
|
-
names the model that answered, and report.qualityStatus reads "bounded_degradation".`),
|
|
601
|
-
observada,verifier:a.fuerza,workload:f,reason:x.razon}),{...h,modeloServido:c,enruta:true,elegible:true,razon:x.razon,observada:x.observada,muestras:x.muestras,tasaDeMuestreo:0}):(
|
|
608
|
+
names the model that answered, and report.qualityStatus reads "bounded_degradation".`),r.record("model-cascade","routed",{candidateModel:c,costRatio:d.r,breakEvenEscalationRate:d.equilibrio,observedEscalationRate:x.
|
|
609
|
+
observada,verifier:a.fuerza,workload:f,reason:x.razon}),{...h,modeloServido:c,enruta:true,elegible:true,razon:x.razon,observada:x.observada,muestras:x.muestras,tasaDeMuestreo:0}):(r.record("model-cascade",
|
|
602
610
|
"off (gate)",{reason:x.razon,observedEscalationRate:x.observada,breakEvenEscalationRate:d.equilibrio}),{...h,elegible:true,razon:x.razon,observada:x.observada,muestras:x.muestras})}devOpen(){return false}assertLicensed(){
|
|
603
|
-
if(this.devOpen())return;let e=this.config.licenseGate;if(e&&typeof e.isActive=="function"){if(e.isActive())return;let n=typeof e.status=="function"?e.status():void 0;throw new Ae(
|
|
604
|
-
|
|
611
|
+
if(this.devOpen())return;let e=this.config.licenseGate;if(e&&typeof e.isActive=="function"){if(e.isActive())return;let n=typeof e.status=="function"?e.status():void 0;throw new Ae(Ks(n),n)}throw e?new Ae(
|
|
612
|
+
Dc(),"invalid"):new Ae(Ks("none"),"none")}avisar(e,n){this.config.silenceWarnings||G(e,n);}avisarDeTruncado(e,n,o,r,s){let i=e.response?.maxOutputTokens,a=ht(e)||"(sin contractId)",c=s?" La capa lo ha \
|
|
605
613
|
APUNTADO: las siguientes peticiones de este contrato llevar\xE1n sus l\xEDmites de valor escritos en el prompt, que es lo \xFAnico que puede corregirlo sin tocarte el tope. Si aun as\xED se corta, es que la tarea\
|
|
606
|
-
no cabe en el contrato: ensancha el esquema y sube el tope con \xE9l.":"",l=
|
|
607
|
-
o necesita: ac\xF3talo y el tope deja de ser una apuesta.":i==null?` El contrato autoriza ~${
|
|
608
|
-
ic exige \`max_tokens\` y el adaptador manda 4096 por defecto). Declara \`maxOutputTokens\` y el corte deja de ser una sorpresa.`:
|
|
614
|
+
no cabe en el contrato: ensancha el esquema y sube el tope con \xE9l.":"",l=r===null?" El esquema no acota la respuesta (falta `maxLength`/`maxItems`), as\xED que no hay forma de saber de antemano cu\xE1nt\
|
|
615
|
+
o necesita: ac\xF3talo y el tope deja de ser una apuesta.":i==null?` El contrato autoriza ~${r} tokens y esta petici\xF3n no declara tope, as\xED que quien cort\xF3 fue un tope del PROVEEDOR (la API de Anthrop\
|
|
616
|
+
ic exige \`max_tokens\` y el adaptador manda 4096 por defecto). Declara \`maxOutputTokens\` y el corte deja de ser una sorpresa.`:r>i?` El contrato autoriza respuestas de hasta ~${r} tokens con este m\
|
|
609
617
|
odelo (lo que permiten sus \`maxLength\`/\`maxItems\`) y el tope son ${i}: ninguna respuesta que use lo que el propio esquema permite cabe. Un tope calibrado con otro modelo NO se hereda \u2014 el esquema \
|
|
610
|
-
acota CARACTERES, que son iguales en todas partes, y el tope acota TOKENS, que son distintos en cada tokenizador.`:` El contrato autoriza ~${
|
|
618
|
+
acota CARACTERES, que son iguales en todas partes, y el tope acota TOKENS, que son distintos en cada tokenizador.`:` El contrato autoriza ~${r} tokens y el tope son ${i}, as\xED que el tope no es el prob\
|
|
611
619
|
lema: este modelo est\xE1 escribiendo m\xE1s de lo que su propio esquema permite (ning\xFAn modo estructurado impone \`maxLength\`).${c}`;this.avisar(`salida-truncada:${a}:${n}`,`[bvsala] La respuesta\
|
|
612
|
-
se cort\xF3 al agotar \`maxOutputTokens\`${i!=null?` (${i})`:""} con el modelo ${n} y el contrato \xAB${a}\xBB: el proveedor devolvi\xF3 finish_reason "length" y ${
|
|
620
|
+
se cort\xF3 al agotar \`maxOutputTokens\`${i!=null?` (${i})`:""} con el modelo ${n} y el contrato \xAB${a}\xBB: el proveedor devolvi\xF3 finish_reason "length" y ${o} tokens de salida, as\xED que el JSO\
|
|
613
621
|
N no valida. NO se reintenta: con el mismo tope volver\xEDa a cortarse y ser\xEDa una llamada pagada para el mismo fallo.${l}`);}avisarDePalancasSinConfigurar(e){this.config.silenceWarnings||((e.compression===
|
|
614
622
|
true||e.compression==="auto")&&!this.config.compressor&&this.avisar("palanca-sin-compresor","[bv-sala] se pidi\xF3 `savings.compression` pero esta capa no tiene compresor, as\xED que NO se comprime nada: el c\
|
|
615
623
|
ontexto largo viaja y se paga entero. En el informe, `report.compression` sale AUSENTE y `tokens.eliminatedInput` a 0 \u2014 lo mismo que se ve cuando no hab\xEDa nada que comprimir. El compresor es un sideca\
|
|
@@ -617,172 +625,174 @@ r porque a\xF1ade latencia y c\xF3mputo que solo usted debe decidir pagar: ench
|
|
|
617
625
|
_compression`, har\xE1 falta adem\xE1s esa funci\xF3n. El resto de la capa sigue ahorrando igual."),e.semanticCache&&!this.deps.semanticCache&&this.avisar("palanca-sin-cache-semantica",'[bv-sala] se p\
|
|
618
626
|
idi\xF3 `savings.semanticCache` pero esta capa no tiene cach\xE9 sem\xE1ntica, as\xED que toda pregunta reformulada saldr\xE1 `cache: "miss"` y se pagar\xE1 al proveedor otra vez. No viene por defecto porque necesita u\
|
|
619
627
|
n embebedor, que es coste y proveedor suyos: ench\xFAfela con `createSavingsLayer({ semanticCache: new InMemorySemanticCache({ embed }) })`. La cach\xE9 exacta y el resto de la capa siguen funcionando.'));}async generateOptimized(e,n={
|
|
620
|
-
llamadas:0,falloDelProveedor:false}){this.assertLicensed();let
|
|
621
|
-
costModelFor(c.modeloServido);
|
|
622
|
-
allowSemanticCache});let u=this.tokensFor(this.assembleBaselinePrompt(e),e),d=e.response?.maxOutputTokens??256;if(
|
|
623
|
-
false){let p=this.deps.resolvers.try(s);if(p)return
|
|
624
|
-
eterministic",
|
|
625
|
-
deps.exactCache.get(f);if(p)return
|
|
626
|
-
void 0,void 0,void 0,void 0,this.informeDeCascada(c));
|
|
627
|
-
maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{}}),h=async()=>{try{return await this.expensivePath(n,e,s,i,a,
|
|
628
|
-
p}};if(i.allowSingleflight&&a.singleflight!==false){let{value:p,coalesced:g}=await this.deps.singleflight.run(m,h);return g?(
|
|
629
|
-
tokensFor(p.text??"",e),l,e)):p}return h()}async expensivePath(e,n,r,
|
|
630
|
-
"semantic-cache","degraded: feature not licensed (free tier)"),
|
|
631
|
-
this.tokensFor(
|
|
632
|
-
void 0,void 0,void 0,this.informeDeCascada(d,{servedModel:n.model}));c.record("semantic-cache","miss");}let m=s.router===false,h=m?ft():this.deps.router.classify(
|
|
633
|
-
confidence,reason:h.reason});let p=m?this.deps.toolSelector.passthrough(n.tools):this.deps.toolSelector.select(
|
|
634
|
-
let
|
|
635
|
-
i.baselineRetrieval=h.rounds;let g=await
|
|
628
|
+
llamadas:0,falloDelProveedor:false}){this.assertLicensed();let o=new rt(this.now),r=new je,s=vn(e),i=wn(s),a=e.savings??{};this.avisarDePalancasSinConfigurar(a);let c=this.decidirCascada(e,s,a,o),l=this.
|
|
629
|
+
costModelFor(c.modeloServido);o.record("canonicalize","done",{tenant:s.tenantId,contract:s.contractId}),o.record("policy",i.reasons.join("; ")||"no restrictions",{allowExactCache:i.allowExactCache,allowSemanticCache:i.
|
|
630
|
+
allowSemanticCache});let u=this.tokensFor(this.assembleBaselinePrompt(e),e),d=e.response?.maxOutputTokens??256;if(r.baselineInput=u,r.baselineOutput=d,r.baselineTools=e.tools?.length??0,a.deterministicResolvers!==
|
|
631
|
+
false){let p=this.deps.resolvers.try(s);if(p)return r.avoidCall(u,this.tokensFor(p.text,e)),o.record("resolver",p.resolver,{avoided:true}),this.finish(e,s,{text:p.text,data:p.data,storedAtMs:this.now()},"d\
|
|
632
|
+
eterministic",r,l,o,ft(),mt(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(c,{servedModel:e.model}))}let f=kn(s,{servedModel:c.modeloServido});if(i.allowExactCache&&a.exactCache!==false){let p=await this.
|
|
633
|
+
deps.exactCache.get(f);if(p)return r.avoidCall(u,this.tokensFor(p.text,e)),o.record("exact-cache","hit",{ageMs:this.now()-p.storedAtMs}),this.finish(e,s,p,"exact",r,l,o,ft(),mt(),this.now()-p.storedAtMs,
|
|
634
|
+
void 0,void 0,void 0,void 0,this.informeDeCascada(c));o.record("exact-cache","miss");}let m=Fo(s,{servedModel:c.modeloServido,deferrable:a.deferrable===true,toolDiscovery:a.toolDiscovery===true,...e.response?.
|
|
635
|
+
maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{}}),h=async()=>{try{return await this.expensivePath(n,e,s,i,a,r,l,o,f,u,c)}catch(p){throw (n.falloDelProveedor||n.llamadas>0)&&Ic(p),
|
|
636
|
+
p}};if(i.allowSingleflight&&a.singleflight!==false){let{value:p,coalesced:g}=await this.deps.singleflight.run(m,h);return g?(o.record("singleflight","coalesced",{key:m}),this.asCoalescedFollower(p,u,this.
|
|
637
|
+
tokensFor(p.text??"",e),l,e)):p}return h()}async expensivePath(e,n,o,r,s,i,a,c,l,u,d){let f=this.entitled("semantic_cache");if(r.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&!f&&c.record(
|
|
638
|
+
"semantic-cache","degraded: feature not licensed (free tier)"),r.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache&&f){let v=await this.deps.semanticCache.find(o);if(v)return i.avoidCall(u,
|
|
639
|
+
this.tokensFor(v.record.answer.text,n)),c.record("semantic-cache","hit",{confidence:v.confidence,similarity:v.similarity}),this.finish(n,o,v.record.answer,"semantic",i,a,c,ft(),mt(),v.ageMs,v.confidence,
|
|
640
|
+
void 0,void 0,void 0,this.informeDeCascada(d,{servedModel:n.model}));c.record("semantic-cache","miss");}let m=s.router===false,h=m?ft():this.deps.router.classify(o);c.record("router",h.executionClass,{confidence:h.
|
|
641
|
+
confidence,reason:h.reason});let p=m?this.deps.toolSelector.passthrough(n.tools):this.deps.toolSelector.select(o.normalizedText,n.tools,h.executionClass);if(i.actualTools=p.tools.length,p.droppedIds.length){
|
|
642
|
+
let v=new Set(p.droppedIds),D=(n.tools??[]).filter(M=>v.has(M.id)).reduce((M,U)=>M+this.tokensFor(Oo(U),n),0);i.eliminate(D),c.record("tool-selector",p.reason,{dropped:p.droppedIds,eliminatedTokens:D});}
|
|
643
|
+
i.baselineRetrieval=h.rounds;let g=await Jo({execution:h.executionClass,query:o.normalizedText,maxRounds:n.retrieval?.maxRounds??h.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?
|
|
636
644
|
{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});i.actualRetrieval=g.rounds,g.retrievedCount>0&&c.record("retrieval",`kept ${g.keptCount}/${g.retrievedCount}`,
|
|
637
|
-
{rounds:g.rounds});let x=mt(),b=[...n.messages],y=
|
|
645
|
+
{rounds:g.rounds});let x=mt(),b=[...n.messages],y=Do(n.messages),T=false,C=g.docs.length>0?{role:"system",content:`Retrieved context \u2014 answer using only this evidence and cite sources by [id]:
|
|
638
646
|
|
|
639
|
-
`+g.docs.map((
|
|
640
|
-
${
|
|
647
|
+
`+g.docs.map((v,D)=>`[${v.source??v.id??`doc${D+1}`}]
|
|
648
|
+
${v.text}`).join(`
|
|
641
649
|
|
|
642
|
-
`)}:null,O=ht(n),
|
|
643
|
-
JSON limits (not API-enforced): ${
|
|
644
|
-
{model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let
|
|
645
|
-
`:"")+x.encoded}),c.record("serialization",x.chosen,{reason:x.reason,jsonTokens:
|
|
646
|
-
disabled; sent compact JSON"});}if(C&>(b,C),(s.compression===true||s.compression==="auto")&&
|
|
647
|
-
{},
|
|
648
|
-
{}},
|
|
650
|
+
`)}:null,O=ht(n),E=n.response?.maxOutputTokens!=null?Math.floor(n.response.maxOutputTokens*3.2):null,A=this.contratosQueIncumplen.has(O)?_o(n.response?.schema,"",E):"";if(A&>(b,{role:"system",content:`\
|
|
651
|
+
JSON limits (not API-enforced): ${A}`}),n.structuredData!==void 0){let v=JSON.stringify(n.structuredData),D=this.tokensFor(v,n);if(s.serialization!==false){x=this.deps.formatSelector.choose(n.structuredData,
|
|
652
|
+
{model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let M=this.tokensFor(x.encoded+x.instruction,n);i.compress(D,M),gt(b,{role:"system",content:(x.instruction?x.instruction+`
|
|
653
|
+
`:"")+x.encoded}),c.record("serialization",x.chosen,{reason:x.reason,jsonTokens:D,chosenTokens:M});}else gt(b,{role:"system",content:v}),c.record("serialization","json-compact",{reason:"format selector\
|
|
654
|
+
disabled; sent compact JSON"});}if(C&>(b,C),(s.compression===true||s.compression==="auto")&&r.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let v=this.config.compressionEconomics??
|
|
655
|
+
{},D=Co(n.model,v),M={compressorCostTokens:v.compressorCostTokens??0,...v.minimumContextTokens!=null?{minimumContextTokens:v.minimumContextTokens}:{},...v.minimumNetTokens!=null?{minimumNetTokens:v.minimumNetTokens}:
|
|
656
|
+
{}},U=0,L=0;for(let F of b)F.role==="system"?U+=1:L+=this.tokensFor(F.content,n);let ee=this.tokensFor(this.assemblePromptText(b,p.tools),n),te=Dn({...M,contextTokens:L,projectedEliminable:L}),ne=0,de=0,
|
|
649
657
|
Ze=false,pe=te.reason;if(te.compress){let F=[];for(let fe of b){if(fe.role==="system"){F.push(fe);continue}let Xe=this.tokensFor(fe.content,n),Qe=await this.config.compressor.compress({text:fe.content}),
|
|
650
|
-
|
|
651
|
-
this.assemblePromptText(F,p.tools),n),Z=
|
|
652
|
-
compressorCostTokens});de>=ne?pe="no fidelity-passed net reduction":Z.compress?
|
|
653
|
-
pe=Z.reason;}Ze||(ne=0,de=0),c.record("compression",Ze?"applied":"skipped",{reason:pe,before:ne,after:de,contextTokens:
|
|
654
|
-
prefixRewritten:
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
658
|
+
Po=!Qe.skipped&&Qe.fidelityPassed&&rr(fe.content,Qe.compressed),Lo=Po?this.tokensFor(Qe.compressed,n):Xe;Po&&Lo<Xe?(F.push({...fe,content:Qe.compressed}),ne+=Xe,de+=Lo):F.push(fe);}let Ao=this.tokensFor(
|
|
659
|
+
this.assemblePromptText(F,p.tools),n),Z=Dn({...M,contextTokens:L,projectedEliminable:ne-de}),ln=js({originalTokens:ee,compressedTokens:Ao,tier:D,...v.prefix?{prefix:v.prefix}:{},compressorCostTokens:M.
|
|
660
|
+
compressorCostTokens});de>=ne?pe="no fidelity-passed net reduction":Z.compress?ln.comprimir?(Ze=true,pe=ln.razon,T=F.slice(0,y).some((fe,Xe)=>fe.content!==b[Xe]?.content),b=F,i.compress(ne,de)):pe=ln.razon:
|
|
661
|
+
pe=Z.reason;}Ze||(ne=0,de=0),c.record("compression",Ze?"applied":"skipped",{reason:pe,before:ne,after:de,contextTokens:L,promptTokens:ee,cacheTierMinimum:D.minimumCacheTokens,protectedSystemMessages:U,
|
|
662
|
+
prefixRewritten:T}),i.compressionReport={originalTokens:ne,compressedTokens:de,protectedSpans:U,fidelityPassed:true};}if(s.elision!==false&&r.allowElision&&this.entitled("tool_result_elision")){let v=Bs(b);
|
|
663
|
+
if(v.indices.length>0){let D=this.tokensFor(Ro,n),M=0;for(let U of v.indices){let L=this.tokensFor(b[U].content,n);M+=Math.max(0,L-D);}(v.indices.some(U=>U<y)&&(T=true),b=Ns(b,v.indices),i.eliminate(
|
|
664
|
+
M),i.elididoLocal+=M),c.record("elision","applied",{elided:v.indices.length,eliminatedTokens:M,grossBytes:v.bytesOriginales,live:Io});}else c.record("elision","skipped",{reason:"no old/larg\
|
|
665
|
+
e tool_result over the age\xD7size threshold"});}let R=n.response?.schema,S=R&&s.outputCodebook===true?Ds(R,v=>this.tokensFor(v,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,ht(n),s.outputCodebookMeasuredOutputDeltaTokens)}):
|
|
666
|
+
null;S&&c.record("output-codebook",S.applied?"applied":"skipped",{reason:S.reason,...S.applied?{renamedKeys:S.plan.renamedKeys,codedEnumValues:S.plan.codedEnumValues,schemaTokensOriginal:S.plan.schemaTokensOriginal,
|
|
667
|
+
schemaTokensCompact:S.plan.schemaTokensCompact,modelledShapeSavingTokens:S.plan.modelledShapeSavingTokens,measuredOutputDeltaTokens:S.plan.measuredOutputDeltaTokens,outputDeltaProvenance:S.plan.outputDeltaProvenance,
|
|
668
|
+
breakEvenOutputDeltaTokens:S.plan.breakEvenOutputDeltaTokens,netSavingUsd:S.plan.netSavingUsd,pricedForModel:d.modeloServido}:{}});let B=S?.applied?S.plan.compactSchema:R,k=B?or(d.modeloServido,B,this.
|
|
669
|
+
deps.constraintBackends):{backend:"none",reason:"no output contract"};c.record("constraints",k.backend,{reason:k.reason});let w=this.decidirMarcadoDeCache(n,d.modeloServido,b,p,s.toolDiscovery===true,T?
|
|
670
|
+
Do(b,true):y,c),_=this.now(),P=await this.descubrirHerramientas(e,n,s,p.tools,b,i,a,c),N=P.tools;i.actualTools=N.length;let V={messages:b,...N.length?{tools:N}:{},...B?{schema:B}:{},...n.response?.maxOutputTokens!=
|
|
671
|
+
null?{maxOutputTokens:n.response.maxOutputTokens}:{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{},...s.deferrable?{deferrable:true}:{},constraintBackend:k.backend},
|
|
672
|
+
I=await this.llamarProveedor({model:d.modeloServido,...V,...w.marcar?{stablePrefixMessages:w.mensajesDePrefijo,promptCacheKey:w.huella}:{}},e);i.actualLlm+=1;let X=v=>{if(!S?.applied)return v;let D=We(
|
|
673
|
+
v);return D.ok?JSON.stringify(S.plan.expand(D.value)):v},$=X(I.text),Q=I.usage,W=false;if(d.enruta){let v=xo({texto:$,schema:R,finishReason:I.finishReason,pidioHerramientas:(I.toolCalls?.length??0)>0});this.
|
|
674
|
+
verjaDeCascada.registrar(d.bucket,!v.acepta),c.record("model-cascade",v.acepta?"accepted":"escalating",{servedModel:d.modeloServido,reason:v.motivo,checks:v.comprobaciones}),v.acepta||(W=true,i.cascadeAttempt(
|
|
675
|
+
I.usage,d.precioBarato??a),i.actualLlm+=1,I=await this.llamarProveedor({model:n.model,...V},e),$=X(I.text));}let ue=W?n.model:d.modeloServido,ve=W?this.costModelFor(n.model):a;i.actualInput+=I.usage.inputTokens,
|
|
676
|
+
i.actualOutput+=I.usage.outputTokens,S?.applied&&c.record("output-codebook",We(I.text).ok?"expanded":"not-expanded (response was not JSON)",We(I.text).ok?{localOutputTokensCompact:this.tokensFor(I.text,
|
|
677
|
+
n),localOutputTokensExpanded:this.tokensFor($,n),creditedLedger:"none",note:"local count of the served answer in both shapes; not credited to any ledger"}:{}),R&&k.backend==="provider-native"&&I.structuredNatively===
|
|
678
|
+
false&&(k={backend:"none",reason:"provider did not enforce the contract natively; the schema travelled in the prompt and the layer is the only validator"},c.record("constraints","none",{downgradedFrom:"p\
|
|
679
|
+
rovider-native",reason:k.reason})),i.sentInputLocal=this.tokensFor(this.assemblePromptText(b,N),n),i.removedInputLocal=Math.max(0,u-i.sentInputLocal-i.elididoLocal),i.sentInputLocal+=P.tokensLocalesDelSondeo,
|
|
680
|
+
i.estimatorExact=this.estimatorEsExacto(n),I.usage.cachedInputTokens&&i.providerCached(I.usage.cachedInputTokens),w.marcar&&(i.cacheWritePremium(Q.cacheWriteInputTokens??0,w.cacheWriteMultiplier,d.precioBarato??
|
|
681
|
+
a),this.verjaDeCache.registrar(w.huella,Q),c.record("prefix-cache","measured",{cacheRead:Q.cachedInputTokens??0,cacheWritePremiumTokens:Q.cacheWriteInputTokens??0}));let ke=null;if(d.modo==="shadow"&&
|
|
682
|
+
d.elegible&&d.candidato&&d.precioBarato&&Nc(l,d.tasaDeMuestreo))try{let v=await this.llamarProveedor({model:d.candidato,...V},e);i.actualLlm+=1;let D=i.extraCostUsd;i.cascadeAttempt(v.usage,d.precioBarato);
|
|
683
|
+
let M=X(v.text),U=xo({texto:M,schema:R,finishReason:v.finishReason,pidioHerramientas:(v.toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!U.acepta);let L=U.acepta?Cs(M,$):null;ke={coste:i.
|
|
684
|
+
extraCostUsd-D,divergio:L?L.divergen:null},c.record("model-cascade",U.acepta?"sample accepted":"sample escalated",{candidateModel:d.candidato,reason:U.motivo,sampleCost:ke.coste,...L?{diverged:L.divergen,
|
|
685
|
+
divergence:L.motivo}:{},note:"measurement only: this answer was NEVER served. The escalation rate it feeds is a money figure, not a quality one"});}catch(v){c.record("model-cascade","sample failed (mea\
|
|
686
|
+
surement only; the answer is unaffected)",{error:v instanceof Error?v.message:String(v)});}let Ge=$,_e=true,Ye=(I.toolCalls?.length??0)>0;if(Ye&&(_e=null,R&&c.record("validation","n/a: model requested to\
|
|
687
|
+
ol calls (the output contract applies to the final answer)")),R&&!Ye){let v=We($),D=v.ok?ae(v.value,R):{valid:false,errors:[{path:"$",message:"not valid JSON"}]};v.ok&&v.rescatado!=null&&D.valid&&($=v.rescatado,
|
|
688
|
+
c.record("validation","rescued-locally",{reason:"the model wrapped valid JSON in prose or a markdown fence; it was extracted locally instead of paying a repair call"})),!D.valid&&jc(D.errors)&&this.contratosQueIncumplen.
|
|
689
|
+
add(ht(n));let M=I.finishReason==="length",U=!D.valid&&D.errors.some(L=>/not a valid regular expression/.test(L.message));if(!D.valid&&U)c.record("validation","repair-skipped",{reason:"schema defect (\
|
|
690
|
+
uncompilable pattern); no output can satisfy it, a retry is a wasted call",errors:D.errors}),this.avisar("esquema-roto","[bvsala] El contrato de respuesta tiene un `pattern` que no es un regex valido,\
|
|
691
|
+
asi que ninguna respuesta puede cumplirlo. NO se reintenta (seria una llamada pagada para el mismo fallo). Corrige el `pattern` del esquema.");else if(!D.valid&&M){let L=Os(R,ne=>this.tokensFor(ne,n)),
|
|
692
|
+
ee=n.response?.maxOutputTokens??null,te=L!==null&&ee!=null&&L<=ee;te&&this.contratosQueIncumplen.add(ht(n)),c.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry\
|
|
693
|
+
with the same cap would truncate again",maxOutputTokens:n.response?.maxOutputTokens??null,outputTokens:I.usage.outputTokens,model:ue,...L!==null?{schemaAllowsTokens:L}:{},learnedValueLimits:te}),this.
|
|
694
|
+
avisarDeTruncado(n,ue,I.usage.outputTokens,L,te);}else if(!D.valid&&k.backend==="none"){let L=D.errors.slice(0,5).map(Z=>`- ${Z.path}: ${Z.message}`).join(`
|
|
685
695
|
`),ee=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
|
|
686
696
|
|
|
687
697
|
Previous reply:
|
|
688
698
|
${$}
|
|
689
699
|
|
|
690
700
|
Problems found:
|
|
691
|
-
${
|
|
701
|
+
${L}
|
|
692
702
|
|
|
693
703
|
Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],te=this.tokensFor(this.assemblePromptText(ee),n),ne=i.sentInputLocal>0?i.actualInput/i.sentInputLocal:1,de=Math.
|
|
694
704
|
round(ne*te),Ze=Math.min(I.usage.outputTokens,n.response?.maxOutputTokens??Number.POSITIVE_INFINITY),pe=de/1e3*ve.inputPer1k+Ze/1e3*ve.outputPer1k,F=this.config.skipRepairAboveBaseline?i.estimateCost(
|
|
695
705
|
ve):void 0;if(F!=null&&F.baselineEstimate>0&&F.actual+pe>F.baselineEstimate&&F!=null)c.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the inva\
|
|
696
|
-
lid answer is served as-is and reported as invalid",errors:
|
|
706
|
+
lid answer is served as-is and reported as invalid",errors:D.errors,baselineUsd:F.baselineEstimate,actualUsd:F.actual,repairEstimateUsd:pe}),this.avisar("reparacion-mas-cara-que-el-baseline",`[bvsala]\
|
|
697
707
|
The answer did not satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${F.baselineEstimate}, already spent ~$${F.actual}\
|
|
698
708
|
, repair ~$${pe.toFixed(6)}). The repair was skipped and the invalid answer is returned with \`constraints.structurallyValid: false\` \u2014 check it before using it. This combination is usually a request ca\
|
|
699
|
-
rrying both tools and an output contract; see the adapter warning for the cheaper shapes.`);else {i.retries=1,c.record("validation","repair-attempt",{errors:
|
|
709
|
+
rrying both tools and an output contract; see the adapter warning for the cheaper shapes.`);else {i.retries=1,c.record("validation","repair-attempt",{errors:D.errors}),I=await this.llamarProveedor({model:ue,
|
|
700
710
|
messages:ee,schema:R,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),i.actualLlm+=1,i.actualInput+=I.usage.inputTokens,i.actualOutput+=I.usage.outputTokens,i.repairOutput+=
|
|
701
|
-
I.usage.outputTokens,i.repairInput+=I.usage.inputTokens,i.sentInputLocal+=te,$=I.text;let Z=We($);
|
|
702
|
-
null&&
|
|
711
|
+
I.usage.outputTokens,i.repairInput+=I.usage.inputTokens,i.sentInputLocal+=te,$=I.text;let Z=We($);D=Z.ok?ae(Z.value,R):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},Z.ok&&(Ge=Z.value,Z.rescatado!=
|
|
712
|
+
null&&D.valid&&($=Z.rescatado));}}else v.ok&&(Ge=v.value);_e=D.valid,c.record("validation",_e?"valid":"invalid");}let Ws=this.now()-_,Gs=Lc(Ge),an={text:$,data:Ge,rendered:Gs,storedAtMs:this.now()},we=this.
|
|
703
713
|
informeDeDiferido(s,I,ve);we&&c.record("deferred-tier",we.credited?"credited":"not-credited",{...we.requestedTier?{requestedTier:we.requestedTier}:{},...we.servedTier?{servedTier:we.servedTier}:{},creditedLedger:"\
|
|
704
|
-
none",reason:we.reason});try{let
|
|
705
|
-
e)":_e===!1?"skipped: response fails its output contract":
|
|
706
|
-
: answered with a reduced tool view (tool discovery), so it must not be replayed");let W
|
|
707
|
-
te=
|
|
708
|
-
semanticCache.store(
|
|
709
|
-
che-write","failed (non-fatal; answer already served)",{error:
|
|
710
|
-
{servedModel:ue,...d.enruta?{escalated:
|
|
711
|
-
null?{divergedOnSample:ke.divergio}:{}}:{},...i.cascadeInput>0||i.cascadeOutput>0?{cascadeInputTokens:i.cascadeInput,cascadeOutputTokens:i.cascadeOutput}:{}}),we);return Ye&&(
|
|
712
|
-
I.finishReason!==void 0&&(
|
|
713
|
-
2)return c.record("tool-discovery","skipped (nothing to discover)",{candidates:
|
|
714
|
-
esquemasCompletos:
|
|
714
|
+
none",reason:we.reason});try{let v=P.aplicado,D=I.finishReason==="length",M=_e!==!1&&!Ye&&!v&&!D;M||c.record("cache-write",Ye?"skipped: tool-call turn (an action request must not be replayed from cach\
|
|
715
|
+
e)":_e===!1?"skipped: response fails its output contract":D?'skipped: answer cut off by the output cap (finish_reason "length"); replaying half an answer would bill it as a 100% avoided call':"skipped\
|
|
716
|
+
: answered with a reduced tool view (tool discovery), so it must not be replayed");let U=W?kn(o,{servedModel:ue}):l;if(M&&r.allowExactCache&&s.exactCache!==!1){let ee=this.config.exactCacheTtlMs??864e5,
|
|
717
|
+
te=r.maxCacheAgeMs==null?ee:Math.min(ee,r.maxCacheAgeMs);await this.deps.exactCache.set(U,an,te);}let L=ue!==n.model;M&&!L&&r.allowSemanticCache&&s.semanticCache&&this.deps.semanticCache?await this.deps.
|
|
718
|
+
semanticCache.store(o,an):M&&L&&s.semanticCache&&c.record("cache-write","semantic write skipped: a cheaper model answered, and this cache keys on the model the caller asked for");}catch(v){c.record("ca\
|
|
719
|
+
che-write","failed (non-fatal; answer already served)",{error:v instanceof Error?v.message:String(v)});}let cn=this.finish(n,o,an,"miss",i,ve,c,h,x,void 0,void 0,_e,k.backend,Ws,this.informeDeCascada(d,
|
|
720
|
+
{servedModel:ue,...d.enruta?{escalated:W}:{},...d.elegible&&d.precioBarato?{estimatedSwapSaving:Bc(i,W,d.precioBarato,this.costModelFor(n.model))}:{},...ke?{sampled:true,sampleCost:sn(ke.coste),...ke.divergio!==
|
|
721
|
+
null?{divergedOnSample:ke.divergio}:{}}:{},...i.cascadeInput>0||i.cascadeOutput>0?{cascadeInputTokens:i.cascadeInput,cascadeOutputTokens:i.cascadeOutput}:{}}),we);return Ye&&(cn.toolCalls=I.toolCalls),
|
|
722
|
+
I.finishReason!==void 0&&(cn.finishReason=I.finishReason),cn}async descubrirHerramientas(e,n,o,r,s,i,a,c){let l={tools:r,tokensLocalesDelSondeo:0,aplicado:false};if(o.toolDiscovery!==true)return l;if(r.length<
|
|
723
|
+
2)return c.record("tool-discovery","skipped (nothing to discover)",{candidates:r.length}),l;let u=g=>this.tokensFor(Oo(g),n),d=r.map(zs),f=Fs({promptTokens:this.tokensFor(this.assemblePromptText(s),n),
|
|
724
|
+
esquemasCompletos:r.reduce((g,x)=>g+u(x),0),descriptoresLigeros:d.reduce((g,x)=>g+u(x),0),esquemasDeLaSegunda:Us(r.map(g=>({risk:g.risk,tokens:u(g)})),3),salidaFinal:n.response?.maxOutputTokens??256,salidaDelSondeo:96,
|
|
715
725
|
precio:a});if(!f.aplicar)return c.record("tool-discovery","skipped (not worth a second call)",{reason:f.razon,oneCall:f.costeDeUnaLlamada,twoCalls:f.costeDeDosLlamadas}),l;let m,h=this.tokensFor(this.
|
|
716
726
|
assemblePromptText(s,d),n);try{m=await this.llamarProveedor({model:n.model,messages:s,tools:d,maxOutputTokens:96,...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{}},
|
|
717
727
|
e);}catch(g){return c.record("tool-discovery","failed (falling back to a single call with every schema)",{error:g instanceof Error?g.message:String(g)}),l}i.actualLlm+=1,i.actualInput+=m.usage.inputTokens,
|
|
718
|
-
i.actualOutput+=m.usage.outputTokens,i.discoveryInput+=m.usage.inputTokens,i.discoveryOutput+=m.usage.outputTokens;let p=
|
|
719
|
-
"tool-discovery","degraded: probe named no known tool",{finishReason:m.finishReason??null,...p.ignorados.length?{unknownNames:p.ignorados}:{}}),{tools:
|
|
720
|
-
"tool-discovery","applied (two provider calls)",{chosen:p.reconocidos,sent:p.tools.map(g=>g.id),candidates:
|
|
728
|
+
i.actualOutput+=m.usage.outputTokens,i.discoveryInput+=m.usage.inputTokens,i.discoveryOutput+=m.usage.outputTokens;let p=Vs((m.toolCalls??[]).map(g=>g.name),r,3);return p.reconocidos.length===0?(c.record(
|
|
729
|
+
"tool-discovery","degraded: probe named no known tool",{finishReason:m.finishReason??null,...p.ignorados.length?{unknownNames:p.ignorados}:{}}),{tools:r,tokensLocalesDelSondeo:h,aplicado:false}):(c.record(
|
|
730
|
+
"tool-discovery","applied (two provider calls)",{chosen:p.reconocidos,sent:p.tools.map(g=>g.id),candidates:r.length,...p.ignorados.length?{unknownNames:p.ignorados}:{}}),{tools:p.tools,tokensLocalesDelSondeo:h,
|
|
721
731
|
aplicado:true})}informeDeCascada(e,n={}){if(e.modo!=="off")return {mode:e.modo,servedModel:n.servedModel??e.modeloServido,eligible:e.elegible,reason:e.razon,verifier:e.fuerza,creditedLedger:"none",...e.candidato?
|
|
722
732
|
{candidateModel:e.candidato}:{},...e.economia?{costRatio:pt(e.economia.r),breakEvenEscalationRate:pt(e.economia.equilibrio),targetEscalationRate:pt(e.economia.escaladoMaximo)}:{},...e.bucket?{workload:e.
|
|
723
|
-
bucket}:{},...e.observada!=null?{escalationRate:pt(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,
|
|
724
|
-
s=
|
|
725
|
-
asked the provider for the "${
|
|
726
|
-
and the provider reports serving "${s.servido}", a tier this layer has no published rate for: nothing is credited`};if(!s.conDescuento)return {...i,reason:`asked for "${
|
|
733
|
+
bucket}:{},...e.observada!=null?{escalationRate:pt(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,o){if(e.deferrable!==true)return;let r=n.requestedServiceTier,
|
|
734
|
+
s=cr(n.servedServiceTier),i={...r?{requestedTier:r}:{},...s?{servedTier:s.servido}:{},credited:false,creditedLedger:"none",latency:dr(r),reason:""};if(!r)return {...i,reason:ur};if(!s)return {...i,reason:`\
|
|
735
|
+
asked the provider for the "${r}" tier, and it reported none back: the rate this request was billed at cannot be known, so nothing is credited`};if(s.factor==null)return {...i,reason:`asked for "${r}" \
|
|
736
|
+
and the provider reports serving "${s.servido}", a tier this layer has no published rate for: nothing is credited`};if(!s.conDescuento)return {...i,reason:`asked for "${r}" and the provider reports ser\
|
|
727
737
|
ving "${s.servido}", which bills at the standard rate: this request was billed as if it had never been deferred`};let a=n.usage,c=Math.min(Math.max(0,a.cachedInputTokens??0),Math.max(0,a.inputTokens)),
|
|
728
|
-
l=
|
|
729
|
-
null?{estimatedTierSaving:
|
|
738
|
+
l=o.cachedInputPer1k??o.inputPer1k,u=(Math.max(0,a.inputTokens)-c)/1e3*o.inputPer1k+c/1e3*l+Math.max(0,a.outputTokens)/1e3*o.outputPer1k,d=lr(s,u);return {...i,credited:true,discountRate:pt(s.factor),...d!=
|
|
739
|
+
null?{estimatedTierSaving:sn(d)}:{},reason:`the provider reports serving the "${s.servido}" tier, which bills at ${(s.factor*100).toFixed(0)}% of the standard rate; the discount stacks with provider p\
|
|
730
740
|
refix caching rather than replacing it`}}diferidoSinLlamada(e){if(e.savings?.deferrable===true)return {credited:false,creditedLedger:"none",latency:"not applicable: no provider call was made for this reques\
|
|
731
|
-
t.",reason:"no provider call was made, so no processing tier was served and none is credited; the call was avoided outright, which is worth more than any tier discount on it"}}finish(e,n,r,
|
|
732
|
-
none",h=0,p,g){let x=e.response?.schema,b=f===null?null:f??(x?ae(
|
|
733
|
-
text:
|
|
734
|
-
requestId:this.generateId(),model:h?.servedModel??e.model,calls:{baselineLlm:
|
|
735
|
-
baselineTools:
|
|
736
|
-
baselineOutput:
|
|
737
|
-
void 0?{confidence:u}:{},...l!==void 0?{ageMs:l}:{}},routing:{executionClass:a.executionClass,confidence:a.confidence,rounds:
|
|
738
|
-
candidateTokens,instructionOverheadTokens:c.instructionOverheadTokens},...
|
|
739
|
-
structurallyValid:d}},qualityStatus:
|
|
740
|
-
max(0,x-m),provider:m},traces:i.all()}}async failOpenDirect(e,n){let
|
|
741
|
-
n.message:String(n)});let
|
|
741
|
+
t.",reason:"no provider call was made, so no processing tier was served and none is credited; the call was avoided outright, which is worth more than any tier discount on it"}}finish(e,n,o,r,s,i,a,c,l,u,d,f,m="\
|
|
742
|
+
none",h=0,p,g){let x=e.response?.schema,b=f===null?null:f??(x?ae(o.data,x).valid:true),y=this.buildReport(e,n,r,s,i,a,c,l,u,d,b,m,h,p,g??this.diferidoSinLlamada(e));return {requestId:y.requestId,data:o.data,
|
|
743
|
+
text:o.text,...o.rendered!==void 0?{rendered:o.rendered}:{},report:y}}buildReport(e,n,o,r,s,i,a,c,l,u,d,f,m,h,p){let g=r.estimateCost(s),x=i.elapsed(),b=h!=null&&h.servedModel!==h.requestedModel;return {
|
|
744
|
+
requestId:this.generateId(),model:h?.servedModel??e.model,calls:{baselineLlm:r.baselineLlm,actualLlm:r.actualLlm,avoidedLlm:r.avoidedLlm,baselineRetrieval:r.baselineRetrieval,actualRetrieval:r.actualRetrieval,
|
|
745
|
+
baselineTools:r.baselineTools,actualTools:r.actualTools,retries:r.retries},tokens:{baselineInput:r.baselineInput,actualInput:r.actualInput,eliminatedInput:r.eliminatedInput,compressedInput:r.compressedInput,
|
|
746
|
+
baselineOutput:r.publishedBaselineOutput,actualOutput:r.actualOutput,eliminatedOutput:r.eliminatedOutput,...r.providerCachedInput?{providerCachedInput:r.providerCachedInput}:{}},cache:{result:o,...u!==
|
|
747
|
+
void 0?{confidence:u}:{},...l!==void 0?{ageMs:l}:{}},routing:{executionClass:a.executionClass,confidence:a.confidence,rounds:r.actualRetrieval,reason:a.reason},serialization:{chosen:c.chosen,candidateTokens:c.
|
|
748
|
+
candidateTokens,instructionOverheadTokens:c.instructionOverheadTokens},...r.compressionReport?{compression:r.compressionReport}:{},constraints:{backend:f,schemaVersion:n.schemaVersion,...d===null?{}:{
|
|
749
|
+
structurallyValid:d}},qualityStatus:Mc(o,d,b),...h?{modelCascade:h}:{},...p?{deferred:p}:{},quality:{...o!=="miss"?{freshnessPassed:!wn(n).requiresFreshData}:{}},cost:g,latencyMs:{total:x,preprocessing:Math.
|
|
750
|
+
max(0,x-m),provider:m},traces:i.all()}}async failOpenDirect(e,n){let o=new rt(this.now);o.record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",{error:n instanceof Error?
|
|
751
|
+
n.message:String(n)});let r=new je,s=this.costModelFor(e.model),i;try{i=vn(e);}catch{i={schemaVersion:e.response?.version??e.response?.contractId??"none"};}let a=e.response?.schema,c=[...e.messages];e.structuredData!==
|
|
742
752
|
void 0&>(c,{role:"system",content:JSON.stringify(e.structuredData)});let l=this.now(),u=await this.config.provider.generate({model:e.model,messages:c,...e.tools?.length?{tools:e.tools}:{},...a?{schema:a}:
|
|
743
|
-
{},...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),d=this.now()-l;
|
|
744
|
-
1,
|
|
745
|
-
u.usage.cachedInputTokens);let f=u.text,m=true,h=(u.toolCalls?.length??0)>0;if(h&&(m=null),a&&!h){let g=We(u.text);m=g.ok?ae(g.value,a).valid:false,g.ok&&(f=g.value);}let p=this.buildReport(e,i,"miss",
|
|
753
|
+
{},...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),d=this.now()-l;r.baselineLlm=
|
|
754
|
+
1,r.actualLlm=1,r.actualInput=u.usage.inputTokens,r.actualOutput=u.usage.outputTokens,r.baselineInput=u.usage.inputTokens,r.baselineOutput=u.usage.outputTokens,u.usage.cachedInputTokens&&r.providerCached(
|
|
755
|
+
u.usage.cachedInputTokens);let f=u.text,m=true,h=(u.toolCalls?.length??0)>0;if(h&&(m=null),a&&!h){let g=We(u.text);m=g.ok?ae(g.value,a).valid:false,g.ok&&(f=g.value);}let p=this.buildReport(e,i,"miss",r,s,o,
|
|
746
756
|
ft(),mt(),void 0,void 0,m,"none",d,void 0,e.savings?.deferrable===true?{credited:false,creditedLedger:"none",latency:"unchanged: the fail-open path asks for no processing tier, so this request was schedule\
|
|
747
757
|
d exactly as an ordinary one.",reason:"the optimizer failed and this request went out on the direct fail-open path, which asks for no cheaper tier: that tier can be refused for lack of capacity, and t\
|
|
748
758
|
rading availability for a discount on a last-resort call is the wrong trade"}:void 0);return {requestId:p.requestId,data:f,text:u.text,...h?{toolCalls:u.toolCalls}:{},...u.finishReason!==void 0?{finishReason:u.
|
|
749
|
-
finishReason}:{},report:p}}asCoalescedFollower(e,n,r,
|
|
759
|
+
finishReason}:{},report:p}}asCoalescedFollower(e,n,o,r,s){let i=new je;i.avoidCall(n,o);let a=i.estimateCost(r),c=this.generateId(),l=this.diferidoSinLlamada(s),u=l?{deferred:l}:{},{deferred:d,...f}=e.
|
|
750
760
|
report;return {...e,requestId:c,report:{...f,requestId:c,calls:{...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:i.baselineInput,actualInput:i.actualInput,eliminatedInput:i.eliminatedInput,
|
|
751
761
|
compressedInput:i.compressedInput,baselineOutput:i.publishedBaselineOutput,actualOutput:i.actualOutput,eliminatedOutput:i.eliminatedOutput,...i.providerCachedInput?{providerCachedInput:i.providerCachedInput}:
|
|
752
|
-
{}},cache:{result:"singleflight"},...u,cost:a}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,
|
|
753
|
-
|
|
762
|
+
{}},cache:{result:"singleflight"},...u,cost:a}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,o){let r=e.map(s=>s.content);o!==void 0&&
|
|
763
|
+
r.push(JSON.stringify(o));for(let s of n??[])r.push(Oo(s));return r.join(`
|
|
754
764
|
`)}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;
|
|
755
765
|
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(
|
|
756
|
-
e)}precioConocido(e){let n=this.config.costModels;if(n){let
|
|
766
|
+
e)}precioConocido(e){let n=this.config.costModels;if(n){let o=n[e];if(o)return o;let r=e.indexOf("/");if(r>=0){let s=n[e.slice(r+1)];if(s)return s}}return bt(e)}costModelFor(e){let n=this.precioConocido(
|
|
757
767
|
e);return n||(this.config.defaultCostModel?this.config.defaultCostModel:(this.avisar(`precio-ilustrativo:${e}`,`[bv-sala] no cost model configured for "${e}"; falling back to the ILLUSTRATIVE default \
|
|
758
|
-
price. Dollar figures will not match your bill. Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),
|
|
759
|
-
return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function
|
|
760
|
-
e.push(
|
|
761
|
-
if(s){i?i=false:c==="\\"?i=true:c==='"'&&(s=false);continue}if(c==='"'){s=true;continue}if(c===n)
|
|
762
|
-
t,null,2)}function
|
|
763
|
-
not_verified"}}function pt(t){return Math.round(t*1e6)/1e6}function
|
|
764
|
-
s.inputPer1k+t.actualOutput/1e3*s.outputPer1k;return
|
|
768
|
+
price. Dollar figures will not match your bill. Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),xs))}};function We(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of Ac(t))try{
|
|
769
|
+
return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function Ac(t){let e=[],n=/```[ \t]*[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g;for(let o of t.matchAll(n)){let r=o[1]?.trim();r&&
|
|
770
|
+
e.push(r);}for(let o of ["{","["]){let r=t.indexOf(o);if(r===-1)continue;let s=Pc(t,r);s&&e.push(s);}return e}function Pc(t,e){let n=t[e],o=n==="{"?"}":"]",r=0,s=false,i=false;for(let a=e;a<t.length;a+=1){let c=t[a];
|
|
771
|
+
if(s){i?i=false:c==="\\"?i=true:c==='"'&&(s=false);continue}if(c==='"'){s=true;continue}if(c===n)r+=1;else if(c===o&&(r-=1,r===0))return t.slice(e,a+1)}}function Lc(t){return typeof t=="string"?t:JSON.stringify(
|
|
772
|
+
t,null,2)}function Mc(t,e,n=false){if(e===false)return "rejected";if(n)return "bounded_degradation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "\
|
|
773
|
+
not_verified"}}function pt(t){return Math.round(t*1e6)/1e6}function sn(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function Bc(t,e,n,o){if(e)return sn(-t.extraCostUsd);let r=s=>t.actualInput/1e3*
|
|
774
|
+
s.inputPer1k+t.actualOutput/1e3*s.outputPer1k;return sn(r(o)-r(n))}function Nc(t,e){if(!(e>0))return false;if(e>=1)return true;let n=ie(`${t}:cascade-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}
|
|
765
775
|
function ft(){return {executionClass:"NO_RETRIEVAL",confidence:1,reason:"n/a (short-circuited)",rounds:0}}function mt(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,
|
|
766
|
-
reason:"no structured payload"}}function
|
|
767
|
-
l=i("maxItems"),u=i("minItems"),d=i("maximum"),f=i("minimum");if(a!=null){let h=n!=null?Math.min(a,n):a;
|
|
768
|
-
|
|
769
|
-
h,p]of Object.entries(m)){let g=
|
|
770
|
-
contractId??e.version??JSON.stringify(e.schema??{}).slice(0,200):""}function
|
|
771
|
-
test(e.message))}function
|
|
772
|
-
for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}function
|
|
773
|
-
if(t[n].role==="user")return n;return
|
|
774
|
-
's embedded public key. Get yours at https://savings.bivelio.com/dashboard/install"),t={...t,licenseGate:void 0});let n={...t,tokenizer:t.tokenizer??
|
|
775
|
-
{isEntitled:f=>u.isEntitled(f),isActive:()=>u.isActive(),status:()=>u.status()};let d=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;
|
|
776
|
+
reason:"no structured payload"}}function _o(t,e="",n=null){if(t==null||typeof t!="object")return "";let o=t,r=[],s=e||"the value",i=h=>typeof o[h]=="number"?o[h]:null,a=i("maxLength"),c=i("minLength"),
|
|
777
|
+
l=i("maxItems"),u=i("minItems"),d=i("maximum"),f=i("minimum");if(a!=null){let h=n!=null?Math.min(a,n):a;r.push(`${s}<=${h}ch`);}c!=null&&r.push(`${s}>=${c}ch`),l!=null&&r.push(`${s}<=${l} items`),u!=null&&
|
|
778
|
+
r.push(`${s}>=${u} items`),d!=null&&r.push(`${s}<=${d}`),f!=null&&r.push(`${s}>=${f}`),typeof o.pattern=="string"&&r.push(`${s} matches /${o.pattern}/`);let m=o.properties;if(m&&typeof m=="object")for(let[
|
|
779
|
+
h,p]of Object.entries(m)){let g=_o(p,e?`${e}.${h}`:h,n);g&&r.push(g);}if(o.items!==void 0){let h=_o(o.items,`${s} entries`,n);h&&r.push(h);}return r.join("; ")}function ht(t){let e=t.response;return e?e.
|
|
780
|
+
contractId??e.version??JSON.stringify(e.schema??{}).slice(0,200):""}function jc(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.
|
|
781
|
+
test(e.message))}function Oo(t){return JSON.stringify({type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function gt(t,e){
|
|
782
|
+
for(let n=t.length-1;n>=0;n--)if(t[n].role==="user"){t.splice(n,0,e);return}t.push(e);}function Do(t,e=false){if(e){let n=0;for(;n<t.length&&t[n].role==="system";)n+=1;return n}for(let n=t.length-1;n>=0;n--)
|
|
783
|
+
if(t[n].role==="user")return n;return Do(t,true)}function $c(t,e){let n=Co(t,e);return n.cacheReadMultiplier<1?n:null}var Fc=72*3600;function ff(t){t.licenseGate&&(console.warn("[bvsala] Ignoring the injected `licenseGate`: in the published package a license is only accepted as a `licenseKey` verified against BiVelio\
|
|
784
|
+
's embedded public key. Get yours at https://savings.bivelio.com/dashboard/install"),t={...t,licenseGate:void 0});let n={...t,tokenizer:t.tokenizer??Mo},o,r;if(t.licenseKey&&!t.licenseGate){let a=ds;if(t.licenseServerUrl){let c=new qe,l=f=>Wt(f,a,{revocation:c,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??Fc}),u=l(t.licenseKey);n.licenseGate=
|
|
785
|
+
{isEntitled:f=>u.isEntitled(f),isActive:()=>u.isActive(),status:()=>u.status()};let d=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;o=new Gt({url:d,publicKeyPem:a,snapshot:c,getRefreshAfter:()=>u.
|
|
776
786
|
refreshAfter?.(),...t.now?{nowSeconds:()=>Math.floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.licensePollIntervalSeconds}:
|
|
777
|
-
{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{},...t.licenseRevocation??{}}),
|
|
787
|
+
{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{},...t.licenseRevocation??{}}),o.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(r=new Zt({url:`${t.licenseServerUrl.replace(
|
|
778
788
|
/\/+$/,"")}/api/license/current`,serviceAccountKey:t.serviceAccountKey,publicKey:a,initialToken:t.licenseKey,revocados:c,onNewToken:f=>{u=l(f);},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?
|
|
779
|
-
{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),
|
|
780
|
-
n.licenseGate=
|
|
789
|
+
{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),r.start());}else
|
|
790
|
+
n.licenseGate=gs(t.licenseKey,a,t.now);}let s=new rn(n),i;if(t.serviceAccountKey&&t.metering?.enabled!==false){let a=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/meteri\
|
|
781
791
|
ng/usage`:void 0);if(a){i=new dt({url:a,serviceAccountKey:t.serviceAccountKey,...t.metering?.orgId?{orgId:t.metering.orgId}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:
|
|
782
792
|
{},...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.
|
|
783
|
-
licenseFetch}:{},...t.now?{now:t.now}:{},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let c=t.metering?.ci??
|
|
784
|
-
i.setSeat(t.metering.seatId,c);else {let l=i;
|
|
785
|
-
return c},close:()=>{
|
|
793
|
+
licenseFetch}:{},...t.now?{now:t.now}:{},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let c=t.metering?.ci??lo();if(t.metering?.seatId)
|
|
794
|
+
i.setSeat(t.metering.seatId,c);else {let l=i;uo(t.serviceAccountKey).then(u=>l.setSeat(u,c)).catch(()=>{});}i.start();}}return {generate:async a=>{let c=await s.generate(a);if(i)try{i.record(c.report);}catch{}
|
|
795
|
+
return c},close:()=>{o?.stop(),r?.stop(),i?.stop();}}}var yf="0.4.14";/*! Bundled license information:
|
|
786
796
|
|
|
787
797
|
@noble/curves/utils.js:
|
|
788
798
|
@noble/curves/abstract/modular.js:
|
|
@@ -790,4 +800,4 @@ return c},close:()=>{r?.stop(),o?.stop(),i?.stop();}}}var af="0.4.13";/*! Bundle
|
|
|
790
800
|
@noble/curves/abstract/edwards.js:
|
|
791
801
|
@noble/curves/ed25519.js:
|
|
792
802
|
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
793
|
-
*/export{
|
|
803
|
+
*/export{gr as AnthropicProvider,yf as BV_SALA_VERSION,un as CATALOGO,$i as COMPACT_ROWS_INSTRUCTION,xs as DEFAULT_COST_MODEL,Fc as DEFAULT_MAX_STALENESS_SECONDS,ds as EMBEDDED_PUBLIC_KEY,gn as ExactTokenizer,kt as ExecutionRouter,Rt as FormatSelector,mn as HeuristicEstimator,yt as InMemoryExactCache,qo as InMemorySemanticCache,Ae as LicenseError,tl as MODELOS_POR_CODIFICACION,Bo as MODELS_BY_ENCODING,An as MockProvider,fr as OpenAICompatibleProvider,Ys as PRECIOS_AL_DIA,Hc as QUALITY_STATUSES,Tn as ResolverRegistry,Gt as RevocationPoller,qe as RevocationSnapshot,je as SavingsLedger,Ct as SchemaRegistry,vt as Singleflight,hn as TokenizerRegistry,wt as ToolSelector,rt as TraceCollector,Vo as UMBRAL_LOCAL,dt as UsageEmitter,Ii as adaptiveK,yi as arithmeticResolver,kn as buildExactKey,Fo as buildInflightKey,vn as canonicalize,Qo as compactRowsSerializer,rr as compresionFiel,$a as computeNextDelay,fi as cosine,Fi as createCompactRowsSerializer,Ho as createDefaultResolvers,Jc as createHandoff,Ou as createMockProvider,ff as createSavingsLayer,tr as csvSerializer,Go as decodeCompactRows,Ci as dedupe,Mo as defaultTokenizerRegistry,uo as deriveSeatId,co as deriveStatus,lo as detectCi,zo as embebedorLocal,Ul as emptyState,Bi as encodeCompactRows,wi as evalArithmetic,wn as evaluatePolicy,Jo as executeRetrievalPlan,gs as gateFromKey,Ne as heuristicEstimator,Ma as isKeyset,De as isStrictCompatible,Wo as jsonCompactSerializer,bi as keyTokensMatch,Wt as liveGateFromKey,ql as mergeDelta,yn as modelFamilyOf,Sn as multisetEqual,nt as negationCount,wu as noopCompressor,xt as normalizeText,et as numericTokens,bt as precioDeLista,Hl as projectContext,mu as providerNativeBackend,fn as randomId,Qs as registerExactTokenizer,nl as registrarTokenizadorExacto,_i as renderState,or as resolveConstraintBackend,ys as resolveDependencies,_d as resolveLicense,ie as sha256,Dn as shouldCompress,Se as stableStringify,Et as uniformColumns,ae as validateAgainstSchema,pi as vectorLocal,ao as verifyCompactSignature,Ue as verifyLicenseToken,hs as verifyRevocationList,ku as withProtectedSpans,tt as words};
|