@bivelio/savings-layer 0.4.25 → 0.4.26
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 +215 -11
- package/dist/adapters/anthropic-sdk.js +20 -19
- package/dist/adapters/langchain.js +54 -53
- package/dist/gateway/bin.js +892 -616
- package/dist/index.d.ts +674 -7
- package/dist/index.js +1285 -992
- package/docs/terminales/README.md +59 -11
- package/docs/terminales/aider.md +74 -0
- package/docs/terminales/continue.md +47 -0
- package/docs/terminales/copilot.md +114 -0
- package/docs/terminales/kilo.md +54 -31
- package/docs/terminales/no-soportados.md +41 -0
- package/docs/terminales/opencode.md +33 -11
- package/package.json +21 -3
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var no="2026-09-27",Wt={"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,
|
|
@@ -20,398 +20,515 @@ haiku":{inputPer1k:25e-5,outputPer1k:.00125,cachedInputPer1k:3e-5},"gemini-3.8-f
|
|
|
20
20
|
cachedInputPer1k:75e-6},"gemini-3.6-flash":{inputPer1k:75e-5,outputPer1k:.00375,cachedInputPer1k:75e-6},"gemini-3.1-flash-lite":{inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:25e-6},"gemini-3-fl\
|
|
21
21
|
ash-preview":{inputPer1k:5e-4,outputPer1k:.003,cachedInputPer1k:5e-5},"gemini-3.5-flash":{inputPer1k:.0015,outputPer1k:.009,cachedInputPer1k:15e-5},"gemini-3.5-flash-lite":{inputPer1k:3e-4,outputPer1k:.0025,
|
|
22
22
|
cachedInputPer1k:3e-5},"gemini-3.1-pro-preview":{inputPer1k:.002,outputPer1k:.012,cachedInputPer1k:2e-4},"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,cachedInputPer1k:125e-6},"gemini-2.5-flash":{
|
|
23
|
-
inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}},
|
|
24
|
-
|
|
25
|
-
cachedInputPer1k:15e-5}}],"gemini-3.6-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},
|
|
26
|
-
precio:
|
|
27
|
-
for(let n of
|
|
28
|
-
""&&
|
|
29
|
-
p-research","o4-mini-deep-research","gpt-5.5-pro","gpt-5.4-pro","gpt-5.2-pro","gpt-5-pro","gpt-5.5-cyber","gemini-3.8-flash-tts","gemini-3.8-flash-lite-tts","gemini-3.1-flash-lite-image"],
|
|
30
|
-
fromEntries(
|
|
31
|
-
return
|
|
32
|
-
1))))return
|
|
23
|
+
inputPer1k:3e-4,outputPer1k:.0025,cachedInputPer1k:3e-5}},Sl={"gemini-3.8-flash":{vigenteHasta:"2027-01-01"},"gemini-3.7-flash":{vigenteHasta:"2027-01-01"},"gemini-3.6-flash":{vigenteHasta:"2027-01-01"}},
|
|
24
|
+
Tl={"gemini-3.8-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}],"gemini-3.7-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,
|
|
25
|
+
cachedInputPer1k:15e-5}}],"gemini-3.6-flash":[{vigenteDesde:"2027-01-01",precio:{inputPer1k:.0015,outputPer1k:.0075,cachedInputPer1k:15e-5}}]},Pl=Object.fromEntries(Object.keys(Wt).map(t=>[t,[{...Sl[t],
|
|
26
|
+
precio:Wt[t]},...Tl[t]??[]]]));var Cl=864e13;function Ss(t){let e=t instanceof Date?t.getTime():t,n=typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=Cl?e:Date.now();return new Date(n).toISOString().slice(0,10)}function Ts(t,e){
|
|
27
|
+
for(let n of Pl[t]??[])if(!(n.vigenteDesde!==void 0&&e<n.vigenteDesde)&&!(n.vigenteHasta!==void 0&&e>=n.vigenteHasta))return n.precio}function ro(t,e,n){if(!n)return;let r=t[n];if(r)return r;let o=n.lastIndexOf("/"),i=o>=0?n.slice(o+1):n,s=t[i];if(s)return s;for(let a of e){if(!i.startsWith(a))continue;let c=i.charAt(a.length);if(c!==
|
|
28
|
+
""&&c!=="-"&&c!=="."&&c!=="_")continue;let u=i.slice(a.length+1);if(!(/^\d/.test(u)&&!/^\d{4}/.test(u)))return t[a]}}function oo(t){return Object.keys(t).sort((e,n)=>n.length-e.length)}var El=["o3-dee\
|
|
29
|
+
p-research","o4-mini-deep-research","gpt-5.5-pro","gpt-5.4-pro","gpt-5.2-pro","gpt-5-pro","gpt-5.5-cyber","gemini-3.8-flash-tts","gemini-3.8-flash-lite-tts","gemini-3.1-flash-lite-image"],to={...Wt,...Object.
|
|
30
|
+
fromEntries(El.map(t=>[t,null]))},Rl=oo(to);function En(t,e){let n=vt(t);return n===void 0?void 0:Ts(n,Ss(e))}var Il=Object.fromEntries(Object.keys(to).map(t=>[t,to[t]===null?null:t]));function vt(t){
|
|
31
|
+
return ro(Il,Rl,t)??void 0}var Dl=/^\d{4}-?\d{2}-?\d{2}$/;function Ve(t,e){let n=vt(t);if(n===void 0)return;let r=t.lastIndexOf("/"),o=r>=0?t.slice(r+1):t;if(!(n!==t&&n!==o&&!Dl.test(o.slice(n.length+
|
|
32
|
+
1))))return Ts(n,Ss(e))}var De="0.4.26",Rn="x-bvsala-version";var _l=0;function Jt(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else {let r=++_l,o=Date.now?Date.now():0;for(let i=0;i<
|
|
33
33
|
16;i++)e[i]=(i<6?r>>>i*8:o>>>(i-6)*8)&255;}e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=[];for(let r=0;r<16;r++)n.push(e[r].toString(16).padStart(2,"0"));return `${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}\
|
|
34
|
-
-${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var
|
|
34
|
+
-${n[8]}${n[9]}-${n[10]}${n[11]}${n[12]}${n[13]}${n[14]}${n[15]}`}var lh=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function ph(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 io=class{id;exact=false;constructor(e="heuristic"){this.id=e;}count(e){if(e.length===0)return 0;let n=e.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],r=0;for(let o of n){let i=o[0];if(/\s/.test(i)){let s=(o.
|
|
35
35
|
match(/\n/g)??[]).length;r+=s+Math.floor(Math.max(0,o.length-1)/2);}else /[A-Za-z]/.test(i)?r+=Math.max(1,Math.ceil(o.length/4)):/\d/.test(i)?r+=Math.max(1,Math.ceil(o.length/2)):r+=1;}return Math.max(r,
|
|
36
|
-
Math.ceil(e.length/4))}},
|
|
36
|
+
Math.ceil(e.length/4))}},yt=new io;var so=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=yt){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){
|
|
37
37
|
return this.modelToTokenizer.set(e,n),this}resolve(e){let n=e.tokenizer?this.estimators.get(e.tokenizer):void 0;if(n)return n;if(e.model){let r=this.modelToTokenizer.get(e.model);if(r){let o=this.estimators.
|
|
38
|
-
get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},
|
|
39
|
-
"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
|
|
40
|
-
["o200k_base","cl100k_base"],r=false;for(let o of n){let i;try{i=await import(`gpt-tokenizer/encoding/${o}`);}catch{continue}if(typeof i.encode=="function"){t.register(new
|
|
41
|
-
[])t.mapModel(s,o),t.mapModel(`openai/${s}`,o);}}return r}var
|
|
38
|
+
get(r);if(o)return o}}return this.estimators.get(this.fallbackId)}count(e,n){return this.resolve(n).count(e)}},ao=new so;var co=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}},In={o200k_base:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini",
|
|
39
|
+
"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 uo(t,e={}){let n=e.codificaciones??
|
|
40
|
+
["o200k_base","cl100k_base"],r=false;for(let o of n){let i;try{i=await import(`gpt-tokenizer/encoding/${o}`);}catch{continue}if(typeof i.encode=="function"){t.register(new co(o,i)),r=true;for(let s of In[o]??
|
|
41
|
+
[])t.mapModel(s,o),t.mapModel(`openai/${s}`,o);}}return r}var Sh=In,Th=uo;var Cs=2592e6,Es=.95,Rs=8,kt=class{avoidedLlm=0;baselineLlm=1;actualLlm=0;baselineRetrieval=0;actualRetrieval=0;baselineTools=0;actualTools=0;retries=0;baselineInput=0;actualInput=0;eliminatedInput=0;compressedInput=0;baselineOutput=0;actualOutput=0;eliminatedOutput=0;providerCachedInput=0;cacheWriteInputTokens=0;cacheWritePremiumUsd=0;providerCacheWritePremiumUsd=0;sentInputLocal=0;removedInputLocal=0;elididoLocal=0;compactedLocal=0;estimatorExact=false;repairOutput=0;repairInput=0;callsWithoutUsage=0;discoveryInput=0;discoveryOutput=0;extraCostUsd=0;cascadeInput=0;cascadeOutput=0;cascadeAttempt(e,n,r=1){
|
|
42
42
|
this.cascadeInput+=Math.max(0,e.inputTokens),this.cascadeOutput+=Math.max(0,e.outputTokens);let o=Math.max(0,e.cacheWriteInputTokens??0);this.extraCostUsd+=Math.max(0,e.inputTokens)/1e3*n.inputPer1k+Math.
|
|
43
43
|
max(0,e.outputTokens)/1e3*n.outputPer1k+o/1e3*n.inputPer1k*Math.max(0,r-1);}cacheWritePremium(e,n,r){let o=Math.max(0,e);this.cacheWriteInputTokens+=o,this.cacheWritePremiumUsd+=o/1e3*r.inputPer1k*Math.
|
|
44
44
|
max(0,n-1);}compressionReport=void 0;eliminate(e){this.eliminatedInput+=Math.max(0,e);}compress(e,n){this.compressedInput+=Math.max(0,e-n);}providerCached(e){this.providerCachedInput+=Math.max(0,e);}providerCacheWritePremium(e,n,r){
|
|
45
45
|
let o=Math.max(0,e);this.providerCacheWritePremiumUsd+=o/1e3*r.inputPer1k*Math.max(0,n-1);}reference=null;referenceRejected=null;avoidCallByReference(e){this.avoidCall(e.creditedInputTokens,e.creditedOutputTokens),
|
|
46
46
|
this.reference=e;}avoidCall(e,n){this.avoidedLlm+=1,this.actualLlm=0,this.baselineInput=e,this.baselineOutput=n;}get publishedBaselineOutput(){return this.avoidedLlm===0?Math.max(0,this.actualOutput-this.
|
|
47
47
|
repairOutput-this.discoveryOutput):this.baselineOutput}estimateCost(e){let n=this.avoidedLlm===0,r="estimated";if(n)if(this.callsWithoutUsage>0)this.baselineInput=0,r="unmeasured";else if(this.actualInput>
|
|
48
|
-
0&&this.sentInputLocal>0){let
|
|
48
|
+
0&&this.sentInputLocal>0){let f=this.actualInput/this.sentInputLocal,h=Math.max(0,this.actualInput-this.repairInput-this.discoveryInput);this.baselineInput=h+Math.round(f*this.removedInputLocal),r=this.
|
|
49
49
|
removedInputLocal===0?"measured":"estimated";}else this.actualInput>0?(this.baselineInput=this.actualInput,r="measured"):(this.baselineInput=0,r="unmeasured");let o=n?Math.max(0,this.actualOutput-this.
|
|
50
|
-
repairOutput-this.discoveryOutput):this.baselineOutput,i=e.cachedInputPer1k??e.inputPer1k,s=Math.min(this.providerCachedInput,this.actualInput),a=
|
|
51
|
-
reference,
|
|
52
|
-
0?"reference":"estimated");let d=a(this.actualInput)+this.actualOutput/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd+
|
|
53
|
-
|
|
50
|
+
repairOutput-this.discoveryOutput):this.baselineOutput,i=e.cachedInputPer1k??e.inputPer1k,s=Math.min(this.providerCachedInput,this.actualInput),a=f=>Math.max(0,f-s)/1e3*e.inputPer1k+s/1e3*i,c=n?null:this.
|
|
51
|
+
reference,u=n?this.providerCacheWritePremiumUsd:0,l=c?c.tierFactor*(this.baselineInput/1e3*c.cachedInputPer1k+this.baselineOutput/1e3*c.outputPer1k):a(this.baselineInput)+o/1e3*e.outputPer1k+u;c&&(r=l>
|
|
52
|
+
0?"reference":"estimated");let d=a(this.actualInput)+this.actualOutput/1e3*e.outputPer1k+this.extraCostUsd+this.cacheWritePremiumUsd+u,m=l===0?0:1-d/l;return {baselineEstimate:Ps(l),actual:Ps(d),netSavings:Al(
|
|
53
|
+
m),basis:r}}};function Ps(t){return Math.round(t*1e10)/1e10}function Al(t){return Math.round(t*1e6)/1e6}var Ol=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
|
|
54
54
|
4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
|
|
55
55
|
1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,
|
|
56
|
-
1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),
|
|
56
|
+
1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ml=new TextEncoder;function Te(t,e){return t>>>e|t<<32-e}function Is(t){let e=Ml.encode(t),n=e.length*
|
|
57
57
|
8,r=(e.length+8>>6)+1,o=new Uint8Array(r*64);o.set(e),o[e.length]=128;let i=new DataView(o.buffer);i.setUint32(o.length-8,Math.floor(n/4294967296)),i.setUint32(o.length-4,n>>>0);let s=new Uint32Array(
|
|
58
|
-
[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let
|
|
59
|
-
64;
|
|
60
|
-
h,6)^
|
|
61
|
-
s[4]=s[4]+h|0,s[5]=s[5]+
|
|
62
|
-
|
|
63
|
-
normalize("NFC"),e=e.replace(
|
|
64
|
-
|
|
65
|
-
return
|
|
66
|
-
return t}function
|
|
58
|
+
[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let u=0;u<o.length;u+=64){for(let b=0;b<16;b++)a[b]=i.getUint32(u+b*4);for(let b=16;b<
|
|
59
|
+
64;b++){let v=a[b-15],w=a[b-2],S=Te(v,7)^Te(v,18)^v>>>3,k=Te(w,17)^Te(w,19)^w>>>10;a[b]=a[b-16]+S+a[b-7]+k|0;}let l=s[0],d=s[1],m=s[2],f=s[3],h=s[4],g=s[5],p=s[6],y=s[7];for(let b=0;b<64;b++){let v=Te(
|
|
60
|
+
h,6)^Te(h,11)^Te(h,25),w=h&g^~h&p,S=y+v+w+Ol[b]+a[b]|0,k=Te(l,2)^Te(l,13)^Te(l,22),x=l&d^l&m^d&m,E=k+x|0;y=p,p=g,g=h,h=f+S|0,f=m,m=d,d=l,l=S+E|0;}s[0]=s[0]+l|0,s[1]=s[1]+d|0,s[2]=s[2]+m|0,s[3]=s[3]+f|0,
|
|
61
|
+
s[4]=s[4]+h|0,s[5]=s[5]+g|0,s[6]=s[6]+p|0,s[7]=s[7]+y|0;}let c="";for(let u=0;u<8;u++)c+=(s[u]>>>0).toString(16).padStart(8,"0");return c}var Ll=/\s+/g,jl=[[/′′/g,'"'],[/[‘’‚‛′´`]/g,"'"],[/[“”„‟″«»]/g,'"'],[/[‐-―−]/g,"-"],[/⁄/g,"/"],[/…/g,""]],Nl=/[¿?¡!;.,:'"·•]/g,$l=/([a-z])\p{M}+/gu,Bl=/(^|\s)\p{M}+/gu,
|
|
62
|
+
lo=/\p{L}/u;function he(t){return t>="0"&&t<="9"}function Dn(t){let e=t.normalize("NFKC").toLowerCase();for(let[n,r]of jl)e=e.replace(n,r);return e=e.normalize("NFD").replace($l,"$1").replace(Bl,"$1").
|
|
63
|
+
normalize("NFC"),e=e.replace(Nl,(n,r,o)=>{let i=o[r-1]??"",s=o[r+1]??"";switch(n){case "\xBF":case "?":case "\xA1":case ";":return he(i)&&he(s)?n:"";case "!":return he(i)?n:"";case ".":case ",":return he(i)&&
|
|
64
|
+
he(s)||he(s)&&!he(i)&&!lo.test(i)?n:"";case ":":return he(i)&&he(s)?n:"";case "'":case '"':return lo.test(i)&&lo.test(s)||he(i)||he(s)?n:"";default:return he(i)||he(s)?n:""}}),e.replace(Ll," ").trim()}function ne(t){
|
|
65
|
+
return Is(t)}function ve(t){return JSON.stringify(po(t))}function po(t){if(Array.isArray(t))return t.map(po);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=po(t[n]);return e}
|
|
66
|
+
return t}function fo(t){return t.replace(/[-_]?\d{4,}.*$/,"").replace(/[-_](mini|nano|small|large|latest)$/i,"")}function mo(t){let e=t.context??{},n=t.messages.filter(i=>i.role==="system").map(i=>i.content).
|
|
67
67
|
join(`
|
|
68
|
-
`),r=t.messages.filter(i=>i.role!=="system").map(i=>`${i.role}:${
|
|
69
|
-
`),o=(t.tools??[]).map(i=>({id:i.id,risk:i.risk,parameters:i.parameters??null})).sort((i,s)=>i.id.localeCompare(s.id));return {model:t.model,modelFamily:
|
|
70
|
-
systemPromptHash:
|
|
71
|
-
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??
|
|
72
|
-
knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var
|
|
68
|
+
`),r=t.messages.filter(i=>i.role!=="system").map(i=>`${i.role}:${Dn(i.content)}`).join(`
|
|
69
|
+
`),o=(t.tools??[]).map(i=>({id:i.id,risk:i.risk,parameters:i.parameters??null})).sort((i,s)=>i.id.localeCompare(s.id));return {model:t.model,modelFamily:fo(t.model),messages:t.messages,normalizedText:r,
|
|
70
|
+
systemPromptHash:ne(n),toolsetHash:ne(ve(o)),structuredDataHash:t.structuredData!==void 0?ne(ve(t.structuredData)):"none",schemaVersion:t.response?.version??t.response?.contractId??"none",contractId:t.
|
|
71
|
+
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??
|
|
72
|
+
"und",knowledgeEpoch:e.knowledgeEpoch??"none",freshnessBucket:e.freshnessBucket??"any",safetyPolicyVersion:e.safetyPolicyVersion??"none",tokenizer:t.tokenizer,original:t}}var Ds="n2";function ho(t,e={}){let n=e.servedModel??t.model,r=ve({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,modelFamily:n===t.model?t.modelFamily:fo(n),
|
|
73
73
|
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,
|
|
74
|
-
freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${
|
|
74
|
+
freshness:t.freshnessBucket,safety:t.safetyPolicyVersion});return `bvsala:exact:${Ds}:${ne(r)}`}function _s(t,e={}){let n=ve({tenant:t.tenantId,scope:t.authorizationScope,principal:t.principal,text:t.normalizedText,
|
|
75
75
|
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===
|
|
76
|
-
true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:inflight:${
|
|
76
|
+
true,toolDiscovery:e.toolDiscovery===true,maxOut:e.maxOutputTokens??null});return `bvsala:inflight:${Ds}:${ne(n)}`}var Fl=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\
|
|
77
77
|
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|\
|
|
78
78
|
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\
|
|
79
79
|
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\
|
|
80
80
|
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\
|
|
81
|
-
nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),
|
|
81
|
+
nhat|m\u1EDBi nh\u1EA5t|gia|gi\xE1|thoi tiet|th\u1EDDi ti\u1EBFt"].join("|")+")\\b","i"),zl=new RegExp("\\b("+["my|mine|our|ours|account|balance|subscription|invoice|order|profile","mi|mis|mio|m\xEDo|nu\
|
|
82
82
|
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\
|
|
83
83
|
|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\
|
|
84
84
|
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\
|
|
85
85
|
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\
|
|
86
|
-
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
|
|
87
|
-
r=(t.original.tools??[]).some(
|
|
88
|
-
filter(
|
|
86
|
+
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 _n(t){let e=[],n=t.normalizedText,
|
|
87
|
+
r=(t.original.tools??[]).some(b=>b.risk==="write"||b.risk==="destructive"),o=t.freshnessBucket==="live"||t.freshnessBucket==="hour"||Fl.test(n),i=zl.test(n),s=(t.temperature??0)>.3&&t.seed==null,a=t.messages.
|
|
88
|
+
filter(b=>b.role==="user").length,c=(t.original?.tools?.length??0)>0,u=t.messages.some(b=>b.role==="tool"||b.role==="assistant"&&(b.toolCalls?.length??0)>0),l=c||u||a>1,d=t.original?.savings?.semanticCache===
|
|
89
89
|
"include-agentic";r&&e.push("write/destructive tools present"),o&&e.push("freshness-sensitive request"),i&&e.push("personalized/account-scoped request"),s&&e.push("stochastic sampling (temp>0.3, no se\
|
|
90
|
-
ed)");let
|
|
91
|
-
effects must execute)"),
|
|
90
|
+
ed)");let m=o&&(t.freshnessBucket==null||t.freshnessBucket==="any"),f=t.freshnessBucket==="live",h=i&&t.principal==null,g=!s&&!m&&!f&&!h&&!r;r&&e.push("write/destructive tools \u2192 exact cache off (side \
|
|
91
|
+
effects must execute)"),f&&e.push("freshnessBucket=live \u2192 exact cache off (answer must be current)"),m&&e.push("freshness-sensitive without a freshness bucket \u2192 exact cache off"),h&&e.push("\
|
|
92
92
|
personalized request with no principal (context.sessionId) \u2192 exact cache off");let p=!r&&!o&&!i&&!s&&t.freshnessBucket!=="day"&&(!l||d);l&&!d?e.push('agentic request (tools, tool calls/results or\
|
|
93
93
|
more than one user turn) \u2192 semantic cache off by default (opt in with savings.semanticCache: "include-agentic")'):l&&d&&e.push('agentic request admitted to the semantic cache by savings.semantic\
|
|
94
|
-
Cache: "include-agentic" (write, freshness, personalization and sampling vetoes still apply)');let
|
|
95
|
-
allowSingleflight:!r&&!h,allowCompression:true,requiresFreshData:o,hasSideEffects:r,isPersonalized:i,isAgentic:l,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var
|
|
96
|
-
now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),
|
|
97
|
-
next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:
|
|
98
|
-
try{return structuredClone(t)}catch{return t}}var
|
|
94
|
+
Cache: "include-agentic" (write, freshness, personalization and sampling vetoes still apply)');let y=!r&&!o&&!i&&!s&&t.freshnessBucket!=="day";return {allowExactCache:g,allowSemanticCache:p,allowElision:y,
|
|
95
|
+
allowSingleflight:!r&&!h,allowCompression:true,requiresFreshData:o,hasSideEffects:r,isPersonalized:i,isAgentic:l,maxCacheAgeMs:t.freshnessBucket==="hour"?36e5:t.freshnessBucket==="day"?864e5:null,reasons:e}}var An=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.
|
|
96
|
+
now()>n.expiresAtMs?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),As(n.value)):null}async set(e,n,r){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let o=this.store.keys().
|
|
97
|
+
next().value;o!==void 0&&this.store.delete(o);}this.store.set(e,{value:As(n),expiresAtMs:r!=null?this.now()+r:null});}async delete(e){this.store.delete(e);}get size(){return this.store.size}};function As(t){
|
|
98
|
+
try{return structuredClone(t)}catch{return t}}var On=class{inflight=new Map;waiters=new Map;async run(e,n){let r=this.inflight.get(e);if(r)return this.waiters.set(e,(this.waiters.get(e)??1)+1),{value:await r,coalesced:true};let o=(async()=>n())();this.
|
|
99
99
|
inflight.set(e,o),this.waiters.set(e,1);try{return {value:await o,coalesced:!1}}finally{this.inflight.delete(e),this.waiters.delete(e);}}join(e){let n=this.inflight.get(e);return n&&this.waiters.set(e,(this.
|
|
100
|
-
waiters.get(e)??1)+1),n}get activeKeys(){return this.inflight.size}};function
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
100
|
+
waiters.get(e)??1)+1),n}get activeKeys(){return this.inflight.size}};function Kt(t){return !Number.isFinite(t)||t<0?-1:t>=1?1e3:Math.floor(t*1e3+1e-9)}var Gt=t=>t/1e3;function ql(t,e,n){if(e>=t)return 1;if(e<0)return 0;if(n<=0)return 1;if(n>=1)return 0;let r=Math.log(n),
|
|
101
|
+
o=Math.log1p(-n),i=t*o,s=[i],a=i;for(let u=0;u<e;u++)i+=Math.log(t-u)-Math.log(u+1)+r-o,s.push(i),i>a&&(a=i);let c=0;for(let u of s)c+=Math.exp(u-a);return Math.min(1,Math.exp(a+Math.log(c)))}function Os(t,e,n,r){
|
|
102
|
+
return t<=0||e>=t*n?false:ql(t,e,n)<=r}function Mn(t,e){return Math.ceil(Math.log(e)/Math.log1p(-t))}function go(t,e){return 6*t/(Math.PI*Math.PI*(e+1)*(e+1))}var it=class{total=new Uint32Array(1001);erroneas=new Uint32Array(
|
|
103
|
+
1001);n=0;anotar(e,n){this.total[e]++,n||this.erroneas[e]++,this.n++;}acumulados(){let e=new Uint32Array(1002),n=new Uint32Array(1002);for(let r=1e3;r>=0;r--)e[r]=e[r+1]+this.total[r],n[r]=n[r+1]+this.
|
|
104
|
+
erroneas[r];return {n:e,e:n}}};function Vl(t,e,n){let{n:r,e:o}=t.acumulados(),i=null;for(let s=1e3;s>=0;s--)Os(r[s],o[s],e,n)&&(i=s);if(i==null)return null;for(;i<1e3&&t.total[i]===0;)i++;return i}function bo(t,e,n){
|
|
105
|
+
let r=[];for(let o of [1,1/4,1/16,1/64,1/256]){let i=Vl(t,e,n*o);i!=null&&r.push(i);}return r}function vo(t,e,n,r){let{n:o,e:i}=t.acumulados(),s=[...new Set(e)].sort((c,u)=>u-c),a=null;for(let c of s){if(!Os(
|
|
106
|
+
o[c],i[c],n,r))break;a={indice:c,retenidas:o[c],erroneas:i[c]};}return a}var Ln=class{constructor(e,n){this.delta=e;this.alfa=n;this.primeraMirada=2*Mn(e,go(n,0));}delta;alfa;seleccion=new it;retenida=new it;etiquetas=0;miradas=0;candidatoPrevio=null;certificado=null;primeraMirada;etiquetasDeLaMirada(e){
|
|
107
|
+
return Math.ceil(this.primeraMirada*1.5**e)}anotar(e,n){let r=Kt(e);r<0||((this.etiquetas%2===0?this.seleccion:this.retenida).anotar(r,n),this.etiquetas++,this.etiquetas>=this.etiquetasDeLaMirada(this.
|
|
108
|
+
miradas)&&this.mirar());}mirar(){let e=go(this.alfa,this.miradas);this.miradas++;let n=bo(this.seleccion,this.delta,e),r=this.candidatoPrevio==null?n:[...n,this.candidatoPrevio],o=vo(this.retenida,r,this.
|
|
109
|
+
delta,e);this.certificado=o,this.candidatoPrevio=o?.indice??n[n.length-1]??this.candidatoPrevio;}get suelo(){return this.certificado?.indice??null}resumen(){return {suelo:this.suelo,etiquetas:this.etiquetas,
|
|
110
|
+
retenidas:this.retenida.n,retenidasEnSuelo:this.certificado?.retenidas??0,erroneasEnSuelo:this.certificado?.erroneas??0,miradas:this.miradas,minimasParaLaSiguiente:Mn(this.delta,go(this.alfa,this.miradas)),
|
|
111
|
+
etiquetasParaLaSiguiente:this.etiquetasDeLaMirada(this.miradas)}}};function jn(t){let{maxErrorRate:e}=t,n=t.confidence??.95,r=t.auditRate??.05;if(!(e>0&&e<=.5))throw new RangeError(`calibration.maxErr\
|
|
112
|
+
orRate must be in (0, 0.5]; got ${e}`);if(!(n>.5&&n<1))throw new RangeError(`calibration.confidence must be in (0.5, 1); got ${n}`);if(!(r>=0&&r<1))throw new RangeError(`calibration.auditRate must be \
|
|
113
|
+
in [0, 1); got ${r}`);return {maxErrorRate:e,confidence:n,auditRate:r}}function Ms(t){let e=t>>>0;return ()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>
|
|
114
|
+
14)>>>0)/4294967296}}function Ls(t,e){let n=o=>o!==null&&typeof o=="object";if(n(t.data)&&n(e.data))return Nn(t.data)===Nn(e.data);let r=o=>o.trim().replace(/\s+/g," ");return r(t.text)===r(e.text)}function Nn(t){if(Array.
|
|
115
|
+
isArray(t))return `[${t.map(Nn).join(",")}]`;if(t!==null&&typeof t=="object"){let e=t;return `{${Object.keys(e).sort().filter(n=>e[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Nn(e[n])}`).join(",")}}`}return JSON.
|
|
116
|
+
stringify(t)??"null"}function Jh(t,e){let{maxErrorRate:n,confidence:r}=jn(e),o=1-r,i=new it,s=new it,a=Ms(1592642065),c=0;for(let l of t){let d=Kt(l.score),m=a()<.5;d<0||((m?i:s).anotar(d,l.correct),c++);}
|
|
117
|
+
let u=vo(s,bo(i,n,o),n,o);return {maxErrorRate:n,confidence:r,floor:u?Gt(u.indice):null,labeled:c,heldOut:s.n,heldOutAtFloor:u?.retenidas??0,wrongHeldOutAtFloor:u?.erroneas??0,minHeldOutToCertify:Mn(n,
|
|
118
|
+
o)}}function Ul(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 Hl(t){return t.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).filter(
|
|
119
|
+
Boolean)}function Wl(t){let e=new Array(256).fill(0),n=Hl(t);if(n.length===0)return e;let r=new Map;for(let i=0;i<n.length;i++){let s=n[i];if(r.set(s,(r.get(s)??0)+1),i+1<n.length){let a=`${s}\0${n[i+
|
|
120
|
+
1]}`;r.set(a,(r.get(a)??0)+1);}}for(let[i,s]of r){let a=Ul(i),c=a%256,u=a>>>31===1?-1:1;e[c]+=u*(1+Math.log(s));}let o=0;for(let i of e)o+=i*i;if(o=Math.sqrt(o),o===0)return e;for(let i=0;i<e.length;i++)
|
|
121
|
+
e[i]/=o;return e}function js(t){return Wl(t)}var Ns=.72;function Jl(t,e){if(t.length!==e.length)return 0;let n=t.length,r=0,o=0,i=0;for(let s=0;s<n;s++){let a=t[s],c=e[s];r+=a*c,o+=a*a,i+=c*c;}return o===0||i===0?0:r/(Math.sqrt(o)*Math.sqrt(i))}var Kl=new Set(
|
|
104
122
|
["no","not","never","none","cannot","cant","without","nor","nt","isnt","arent","wasnt","werent","dont","doesnt","didnt","wont","shouldnt","sin","nunca","jamas","jam\xE1s","tampoco","ni","ningun","ning\
|
|
105
|
-
\xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),
|
|
123
|
+
\xFAn","ninguna","ninguno","nada","nadie","sense","mai","tampoc","cap","gens","ningu","ning\xFA","res"]),Gl=new Set(["the","a","an","of","to","in","on","for","and","or","is","are","was","were","what",
|
|
106
124
|
"whats","which","who","whom","how","when","where","me","my","i","you","please","tell","give","show","find","do","does","did","be","that","this","it","with","as","at","by","from","about","into","over",
|
|
107
125
|
"than","then","s","el","la","los","las","un","una","unos","unas","de","del","al","en","por","para","con","sin","sobre","y","o","u","es","son","era","eran","ser","estar","esta","este","esto","estos","e\
|
|
108
126
|
stas","ese","esa","eso","que","cual","cuales","quien","quienes","como","cuando","donde","dame","dime","quiero","necesito","puedes","podrias","favor","porfavor","gracias","me","mi","mis","tu","tus","su",
|
|
109
127
|
"sus","lo","le","se","hay","el","la","els","les","un","una","uns","unes","de","del","dels","al","als","en","per","amb","sense","sobre","i","o","es","son","era","eren","ser","estar","aquest","aquesta",
|
|
110
|
-
"aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function
|
|
111
|
-
match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function
|
|
112
|
-
return false;n.set(r,o-1);}return true}function
|
|
113
|
-
function $
|
|
114
|
-
`).map(e=>{let n=
|
|
115
|
-
r[o].rol||!
|
|
116
|
-
n.filter(o)),s=new Set(r.filter(o));if(i.size===0&&s.size===0)return true;let a=0;for(let
|
|
117
|
-
let n=e.embed==null;this.embebedorPropio=n,this.embed=e.embed??
|
|
118
|
-
e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now())
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
return
|
|
131
|
-
|
|
132
|
-
|
|
128
|
+
"aquests","aquestes","aquell","aquella","que","quin","quina","qui","com","quan","on","dona","vull","necessito","pots","podries","sisplau","gracies","meu","meva","seu","seva","hi"]);function Yt(t){return (t.
|
|
129
|
+
match(/\d[\d.,:/-]*/g)??[]).map(e=>e.replace(/[.,:/-]+$/,""))}function yo(t,e){if(t.length!==e.length)return false;let n=new Map;for(let r of t)n.set(r,(n.get(r)??0)+1);for(let r of e){let o=n.get(r);if(!o)
|
|
130
|
+
return false;n.set(r,o-1);}return true}function Zt(t){return t.split(/\s+/).filter(Boolean)}function Qt(t){return t.filter(e=>Kl.has(e.replace(/'/g,""))||e.endsWith("n't")).length}var Yl=/^(system|user|assistant|tool):/;
|
|
131
|
+
function $s(t){return t.split(`
|
|
132
|
+
`).map(e=>{let n=Yl.exec(e);return n?{rol:n[1],texto:e.slice(n[0].length)}:{rol:"",texto:e}})}function Zl(t,e){let n=$s(t),r=$s(e);if(n.length!==r.length)return false;for(let o=0;o<n.length;o++)if(n[o].rol!==
|
|
133
|
+
r[o].rol||!Ql(n[o].texto,r[o].texto))return false;return true}function Ql(t,e){if(!yo(Yt(t),Yt(e)))return false;let n=Zt(t),r=Zt(e);if(Qt(n)!==Qt(r))return false;let o=u=>u.length>1&&!Gl.has(u)&&!/^\d/.test(u),i=new Set(
|
|
134
|
+
n.filter(o)),s=new Set(r.filter(o));if(i.size===0&&s.size===0)return true;let a=0;for(let u of i)s.has(u)&&a++;let c=i.size+s.size-a;return c===0?true:a/c>=.75}var Bs=class{records=[];embed;verify;similarityThreshold;acceptThreshold;ttlMs;maxRecords;now;embebedorPropio;calibracion;estados=new Map;pendientes=new Set;aceptacionExplicita;constructor(e={}){
|
|
135
|
+
let n=e.embed==null;if(this.embebedorPropio=n,this.embed=e.embed??js,this.verify=e.verify,this.similarityThreshold=e.similarityThreshold??(n?Ns:.9),this.acceptThreshold=e.acceptThreshold??.85,this.aceptacionExplicita=
|
|
136
|
+
e.acceptThreshold!=null,this.ttlMs=e.ttlMs,this.maxRecords=e.maxRecords??5e3,this.now=e.now??(()=>Date.now()),e.calibration){let r=jn(e.calibration);this.calibracion={...r,judge:e.calibration.judge??Ls,
|
|
137
|
+
perRecordFloors:e.calibration.perRecordFloors??true,random:e.calibration.random??Math.random};}}get calibrated(){return this.calibracion!=null}async find(e){return this.calibracion?(await this.lookup(e)).
|
|
138
|
+
hit:this.mejorCandidata(e,true)}async mejorCandidata(e,n){if(this.records.length===0)return null;let r=await this.embed(e.normalizedText),o=null;for(let i of this.records){if(i.tenantId!==e.tenantId||i.
|
|
139
|
+
authorizationScope!==e.authorizationScope||i.principal!==e.principal||i.knowledgeEpoch!==e.knowledgeEpoch||i.contractId!==e.contractId||i.model!==e.model||i.systemPromptHash!==e.systemPromptHash||i.structuredDataHash!==
|
|
140
|
+
e.structuredDataHash||i.locale!==e.locale||i.schemaVersion!==e.schemaVersion||i.safetyPolicyVersion!==e.safetyPolicyVersion||i.toolsetHash!==e.toolsetHash||i.temperature!==e.temperature||i.seed!==e.seed||
|
|
141
|
+
this.ttlMs!=null&&this.now()-i.storedAtMs>this.ttlMs)continue;let s=Jl(r,i.embedding);if(s<this.similarityThreshold||!Zl(e.normalizedText,i.query))continue;let a=this.verify?await this.verify(e.normalizedText,
|
|
142
|
+
i.query):s,c=Math.min(s,a);n&&c<this.acceptThreshold||(!o||c>o.confidence)&&(o={record:i,similarity:s,verifierScore:a,confidence:c,ageMs:this.now()-i.storedAtMs,similarityFloor:this.similarityThreshold,
|
|
143
|
+
acceptFloor:this.acceptThreshold,embedder:this.embebedorPropio?"built_in":"custom",verifierRan:this.verify!=null});}return o}async lookup(e,n={}){let r=this.calibracion;if(!r)return {hit:await this.mejorCandidata(
|
|
144
|
+
e,true),probe:null};let o=n.agentic?"agentic":"single_shot",i=await this.mejorCandidata(e,false);if(!i)return {hit:null,probe:null};let s=this.estadoDe(o),a=s.suelo,c=i.confidence,u=m=>({hit:null,probe:{reason:m,
|
|
145
|
+
score:c,segment:o,record:i.record}});if(a==null)return u("calibrating");if(Kt(c)<a||this.aceptacionExplicita&&c<this.acceptThreshold)return u("below_floor");if(r.perRecordFloors&&i.record.failedAtScore!=
|
|
146
|
+
null&&c<=i.record.failedAtScore)return u("record_floor");if(r.auditRate>0&&r.random()<r.auditRate)return u("audit");let l=Gt(a),d=s.resumen();return {hit:{...i,acceptFloor:this.aceptacionExplicita?Math.
|
|
147
|
+
max(l,this.acceptThreshold):l,calibration:{maxErrorRate:r.maxErrorRate,confidence:r.confidence,floor:l,heldOutAtFloor:d.retenidasEnSuelo,wrongHeldOutAtFloor:d.erroneasEnSuelo,labeled:d.etiquetas,segment:o}},
|
|
148
|
+
probe:null}}observe(e,n){let r=this.etiquetar(e,n);return this.pendientes.add(r),r.finally(()=>this.pendientes.delete(r)),r}async etiquetar(e,n){let r=this.calibracion;if(!r)return null;let o;try{o=await r.
|
|
149
|
+
judge(e.record.answer,n)===!0;}catch{return null}return this.estadoDe(e.segment).anotar(e.score,o),!o&&r.perRecordFloors&&(e.record.failedAtScore=Math.max(e.record.failedAtScore??-1/0,e.score)),o}async settled(){
|
|
150
|
+
for(;this.pendientes.size>0;)await Promise.allSettled([...this.pendientes]);}calibrationStatus(e="single_shot"){let n=this.calibracion;if(!n)return null;let r=this.estadoDe(e).resumen();return {maxErrorRate:n.
|
|
151
|
+
maxErrorRate,confidence:n.confidence,floor:r.suelo==null?null:Gt(r.suelo),labeled:r.etiquetas,heldOut:r.retenidas,heldOutAtFloor:r.retenidasEnSuelo,wrongHeldOutAtFloor:r.erroneasEnSuelo,minHeldOutToCertify:r.
|
|
152
|
+
minimasParaLaSiguiente,nextTestAt:r.etiquetasParaLaSiguiente}}estadoDe(e){let n=this.estados.get(e);if(!n){let r=this.calibracion;n=new Ln(r.maxErrorRate,1-r.confidence),this.estados.set(e,n);}return n}async store(e,n){
|
|
153
|
+
let r=await this.embed(e.normalizedText);this.records.length>=this.maxRecords&&this.records.shift(),this.records.push({embedding:r,query:e.normalizedText,answer:n,tenantId:e.tenantId,authorizationScope:e.
|
|
154
|
+
authorizationScope,principal:e.principal,knowledgeEpoch:e.knowledgeEpoch,contractId:e.contractId,model:e.model,systemPromptHash:e.systemPromptHash,structuredDataHash:e.structuredDataHash,locale:e.locale,
|
|
155
|
+
schemaVersion:e.schemaVersion,safetyPolicyVersion:e.safetyPolicyVersion,toolsetHash:e.toolsetHash,temperature:e.temperature,seed:e.seed,storedAtMs:this.now()});}invalidateEpoch(e){let n=0;for(let r=this.
|
|
156
|
+
records.length-1;r>=0;r--)this.records[r].knowledgeEpoch===e&&(this.records.splice(r,1),n++);return n}get size(){return this.records.length}};var ko=class{resolvers=[];register(e){return this.resolvers.push(e),this}try(e){for(let n of this.resolvers)try{let r=n.try(e);if(r)return r}catch{}return null}get size(){return this.resolvers.length}},
|
|
157
|
+
Xl={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]??ed(t.normalizedText))?.trim();if(!n)return null;
|
|
158
|
+
let r=nd(n);return r===null||!Number.isFinite(r)?null:{text:td(r),data:{value:r},resolver:"arithmetic"}}};function ed(t){return /^[0-9+\-*/%.()\s]+$/.test(t.trim())&&/[+\-*/%]/.test(t)?t.trim():null}function td(t){
|
|
159
|
+
return Number.isInteger(t)?String(t):String(Math.round(t*1e9)/1e9)}function nd(t){let e=t.match(/\d+\.?\d*|[+\-*/%()]/g);if(!e||e.join("")!==t.replace(/\s+/g,""))return null;let n=[],r=[],o={"+":1,"-":1,
|
|
160
|
+
"*":2,"/":2,"%":2},i=a=>{let c=n.pop(),u=n.pop();if(u===void 0||c===void 0)return false;switch(a){case "+":return n.push(u+c),true;case "-":return n.push(u-c),true;case "*":return n.push(u*c),true;case "/":return c===
|
|
161
|
+
0?false:(n.push(u/c),true);case "%":return c===0?false:(n.push(u%c),true);default:return false}},s=true;for(let a of e)if(/^\d/.test(a))n.push(Number(a)),s=false;else if(a==="(")r.push(a),s=true;else if(a===")"){for(;r.length&&
|
|
133
162
|
r[r.length-1]!=="(";)if(!i(r.pop()))return null;if(r.pop()!=="(")return null;s=false;}else {if(s)return null;for(;r.length&&r[r.length-1]!=="("&&o[r[r.length-1]]>=o[a];)if(!i(r.pop()))return null;r.push(a),
|
|
134
|
-
s=true;}for(;r.length;){let a=r.pop();if(a==="("||!i(a))return null}return n.length===1?n[0]:null}function
|
|
135
|
-
|
|
163
|
+
s=true;}for(;r.length;){let a=r.pop();if(a==="("||!i(a))return null}return n.length===1?n[0]:null}function Fs(){return new ko().register(Xl)}var rd=/\b(compare|versus|\bvs\b|difference between|both|and then|after that|which is (?:better|cheaper|faster)|compar[ae]|diferencia entre)\b/i,zs=/\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,
|
|
164
|
+
od=/\b(summarize|rewrite|translate|classify|extract|reformat|fix|convert|the following|below|above|this text|resume|reescribe|traduce|clasifica)\b/i,$n=class{classifier;maxRounds;constructor(e={}){this.
|
|
136
165
|
classifier=e.classifier,this.maxRounds=e.maxRounds??2;}classify(e){let n=e.original.retrieval?.mode,r=e.normalizedText;if((e.original.tools??[]).some(s=>s.risk==="write"||s.risk==="destructive")&&/\b(create|update|delete|send|pay|book|cancel|crea|actualiza|elimina|env[ií]a|paga)\b/i.
|
|
137
|
-
test(r))return
|
|
138
|
-
.8,"self-contained transformation",0);let i=this.classifier?.classify(r);return i&&i.confidence>=.75?
|
|
139
|
-
e"?
|
|
140
|
-
d question",Math.min(this.maxRounds,2)):
|
|
141
|
-
"SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
let
|
|
153
|
-
|
|
154
|
-
|
|
166
|
+
test(r))return _e("TOOL_ACTION",.9,"imperative + write tool available",0);if(n==="off")return _e("NO_RETRIEVAL",1,"retrieval disabled by caller",0);if(od.test(r)&&!zs.test(r))return _e("NO_RETRIEVAL",
|
|
167
|
+
.8,"self-contained transformation",0);let i=this.classifier?.classify(r);return i&&i.confidence>=.75?_e(i.executionClass,i.confidence,"local classifier",id(i.executionClass,this.maxRounds)):n==="singl\
|
|
168
|
+
e"?_e("SINGLE_RETRIEVAL",.7,"caller hint: single",1):n==="multi"?_e("MULTI_HOP_RETRIEVAL",.7,"caller hint: multi",Math.min(this.maxRounds,2)):rd.test(r)?_e("MULTI_HOP_RETRIEVAL",.7,"comparison/compoun\
|
|
169
|
+
d question",Math.min(this.maxRounds,2)):zs.test(r)?_e("SINGLE_RETRIEVAL",.65,"single factual lookup",1):_e("NO_RETRIEVAL",.5,"no retrieval signal (conservative default)",0)}};function id(t,e){return t===
|
|
170
|
+
"SINGLE_RETRIEVAL"?1:t==="MULTI_HOP_RETRIEVAL"?Math.min(e,2):0}function _e(t,e,n,r){return {executionClass:t,confidence:e,reason:n,rounds:r}}var sd=["claude-fable-5-1","claude-mythos-5-1","claude-fable-5","claude-mythos-5","claude-opus-5-5","claude-opus-5","claude-opus-4-8","claude-opus-4-7","claude-opus-4-6","claude-sonnet-4-6","claude-op\
|
|
171
|
+
us-4-5-20251101","claude-sonnet-4-5-20250929","claude-haiku-4-5-20251001"],qs={herramientas:10,tokensDeEsquemas:1e4},Vs=5,ad={regex:200,bm25:500},Us=1e4,xo={bm25:{type:"tool_search_tool_bm25_20251119",
|
|
172
|
+
name:"tool_search_tool_bm25"},regex:{type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"}},cd="bvsala_contract";function Hs(t){let e=t.lastIndexOf("/");return (e>=0?t.slice(e+1):t).toLowerCase()}
|
|
173
|
+
function wo(t){let e=r=>r.replace(/-\d{8}$/,""),n=e(Hs(t));return sd.some(r=>e(r)===n)}function So(t){let e={modo:"off",siempreCargadas:[],variante:"bm25"};if(t===void 0)return e;let n=r=>r==="off"||r===
|
|
174
|
+
"auto"||r==="always";return typeof t=="string"?n(t)?{...e,modo:t}:e:typeof t!="object"||t===null||!n(t.mode)?e:{modo:t.mode,siempreCargadas:Array.isArray(t.alwaysLoaded)?[...new Set(t.alwaysLoaded.filter(
|
|
175
|
+
r=>typeof r=="string"))]:[],variante:t.variant==="regex"?"regex":"bm25"}}function Xt(t){return !t.some(e=>Array.isArray(e.intents)&&e.intents.length>0)&&!t.some(e=>typeof e.risk=="string")}function Ws(t){
|
|
176
|
+
let{opciones:e}=t,n=e.variante,r=(v,w={})=>({aplicar:false,razon:v,variante:n,siempreCargadas:[],diferidas:0,tokensDiferidos:0,...w});if(e.modo==="off")return r("toolSearch is off");if(t.herramientas.length===
|
|
177
|
+
0)return r("no tools in this request");if(t.capacidad===void 0)return r("this provider is not an adapter of this package that can send the provider's tool search; OpenAI documents tool search for its \
|
|
178
|
+
Responses and Agents APIs, not for Chat Completions, which is what the OpenAI-compatible adapter speaks");if(!wo(t.modelo))return r(`${Hs(t.modelo)} is not in the provider's tool search model compatib\
|
|
179
|
+
ility table`);if(t.hayContrato)return r("this request carries an output contract, which travels as a forced tool on this provider; combining it with deferred tools is not documented, so the selector k\
|
|
180
|
+
eeps this request");if(t.cascadaActiva)return r("the model cascade is on: the cheaper model and the escalation would both have to support tool search");let o=xo[n];if(t.herramientas.some(v=>v.id===o.name))
|
|
181
|
+
return r(`one of your tools is already named \`${o.name}\``);let i=new Set(t.herramientas.map(v=>v.id)),s=e.siempreCargadas.filter(v=>i.has(v)&&v!==cd),a=new Set(s),c=t.herramientas.filter(v=>!a.has(v.
|
|
182
|
+
id)),u=c.reduce((v,w)=>v+w.tokens,0),l={siempreCargadas:s,diferidas:c.length,tokensDiferidos:u};if(c.length===0)return r("every tool is in `alwaysLoaded`: nothing to defer",l);if(c.length>Us)return r(
|
|
183
|
+
`${c.length} tools to defer, over the provider's limit of ${Us}`,l);if(e.modo==="always")return {aplicar:true,variante:n,...l,razon:`toolSearch "always": ${c.length} tool(s) deferred behind the provider'\
|
|
184
|
+
s ${n} search, ${s.length} always loaded; no size or cost check (you chose it)`};if(t.capacidad!=="oficial")return r(`the adapter is not talking to the provider's own API host; a proxy may not forward\
|
|
185
|
+
the search blocks. Use toolSearch "always" if yours does`,l);let d=t.herramientas.reduce((v,w)=>v+w.tokens,0);if(t.herramientas.length<qs.herramientas&&d<=qs.tokensDeEsquemas)return r(`${t.herramientas.
|
|
186
|
+
length} tools and about ${d} tokens of definitions: under the provider's documented threshold (10 or more tools, or more than 10k tokens), where standard tool calling fits better`,l);let m=t.precio.inputPer1k/
|
|
187
|
+
1e3,f=t.precio.outputPer1k/1e3,h=Math.min(1,Math.max(0,t.lecturaDeCache)),g=c.map(v=>v.tokens).sort((v,w)=>w-v).slice(0,Vs).reduce((v,w)=>v+w,0),p=h*m*u,y=m*g+f*ad[n],b={ahorroDelPrefijo:p,costeDeUnaBusqueda:y};
|
|
188
|
+
return p<y?r(`deferring ${u} tokens of definitions saves ${p.toFixed(6)} per request even with a warm prompt cache, less than one worst-case search costs (${y.toFixed(6)}: the ${Vs} largest definition\
|
|
189
|
+
s uncached plus the longest query); the selector keeps this request`,{...l,...b}):{aplicar:true,variante:n,...l,...b,razon:`${c.length} tool(s) deferred behind the provider's ${n} search (${u} tokens of\
|
|
190
|
+
definitions out of the cached prefix): it pays even if every request searches once with a warm cache (${p.toFixed(6)} saved vs ${y.toFixed(6)} worst-case search). The provider's counter measures it; \
|
|
191
|
+
the layer credits nothing for it`}}function Js(t,e,n){return n||Xt(t)?[...t]:t.filter(r=>e||r.risk==="read")}var To=class{constructor(e=512){this.cap=e;}cap;map=new Map;read(e){return this.map.get(e)}record(e,n,r){this.map.size>=this.cap&&!this.map.has(e)&&this.map.clear(),this.map.set(e,{ids:n,turns:r});}},Bn=class{maxTools;scoreIntentMatch;learningTurns;freezer;constructor(e={}){
|
|
192
|
+
this.maxTools=e.maxTools??8,this.scoreIntentMatch=e.scoreIntentMatch??ud,this.learningTurns=e.learningTurns??16,this.freezer=e.freezer??new To;}passthrough(e){if(!e||e.length===0)return {tools:[],droppedIds:[],
|
|
193
|
+
reason:"no tools provided",setIsStable:true};let n=e.slice(0,this.maxTools),r=e.slice(this.maxTools).map(o=>o.id);return {tools:n,droppedIds:r,reason:`router off: caller tools passed through unfiltered (${n.
|
|
194
|
+
length}/${e.length}, capped at maxTools=${this.maxTools}; risk gating is the caller's responsibility while routing is off)`,setIsStable:true}}select(e,n,r,o){if(!n||n.length===0)return {tools:[],droppedIds:[],
|
|
195
|
+
reason:"no tools provided",setIsStable:true};if(Xt(n)){let p=this.passthrough(n);return {...p,reason:`catalogue declares no \`intents\` and no \`risk\`: nothing to select on, passed through (${p.tools.length}\
|
|
196
|
+
/${n.length}, capped at maxTools=${this.maxTools}). Declare ToolDescriptor.intents/risk to enable pruning`}}let i=r==="TOOL_ACTION",s=n.filter(p=>i||p.risk==="read"),a=p=>i&&p.risk!=="read",c=s.filter(
|
|
197
|
+
p=>!a(p)),u=s.filter(p=>a(p)),l=u.map(p=>({tool:p,score:this.scoreIntentMatch(e,p)})).sort((p,y)=>y.score-p.score).map(p=>p.tool),d=c.map(p=>({tool:p,score:this.scoreIntentMatch(e,p)})).filter(p=>p.score>
|
|
198
|
+
0).sort((p,y)=>y.score-p.score).map(p=>p.tool),f=[...l.slice(0,this.maxTools),...d.slice(0,Math.max(0,this.maxTools-u.length))].map(p=>({tool:p})).map(p=>p.tool).sort((p,y)=>p.id<y.id?-1:p.id>y.id?1:0);
|
|
199
|
+
if(o!==void 0){let p=this.freezer.read(o),y=(p?.turns??0)+1;if(p&&y>this.learningTurns){let v=new Set(p.ids),w=n.filter(k=>v.has(k.id));this.freezer.record(o,p.ids,y);let S=new Set(w.map(k=>k.id));return {
|
|
200
|
+
tools:w,droppedIds:n.filter(k=>!S.has(k.id)).map(k=>k.id),reason:`frozen tool set after ${this.learningTurns} turns (${w.length}/${n.length}): it no longer depends on this request's text, so the prefi\
|
|
201
|
+
x cache survives`,setIsStable:true}}let b=[...new Set([...p?.ids??[],...f.map(v=>v.id)])].sort().slice(0,this.maxTools);this.freezer.record(o,b,y);}let h=new Set(f.map(p=>p.id)),g=n.filter(p=>!h.has(p.id)).
|
|
202
|
+
map(p=>p.id);return {tools:f,droppedIds:g,reason:`selected ${f.length}/${n.length} by intent match (writes ${i?"allowed":"blocked"})`,setIsStable:g.length===0}}};function ud(t,e){let n=Dn(t),r=0;for(let o of Array.
|
|
203
|
+
isArray(e.intents)?e.intents:[]){let i=Dn(o);i&&(n.includes(i)?r+=2:i.split(/\s+/).some(s=>s.length>3&&n.includes(s))&&(r+=1));}return r}function ld(t){let e=new Set,n=[];for(let r of t){let o=r.hash??pd(r.text);e.has(o)||(e.add(o),n.push(r));}return n}function dd(t,e={maxDocuments:5}){let n=e.minDocuments??1,r=[...t].sort((s,a)=>(a.score??
|
|
155
204
|
0)-(s.score??0));if(r.length<=n)return r;let o=r[0]?.score??0;if(o<=0)return r.slice(0,e.maxDocuments);let i=[];for(let s of r){let a=(s.score??0)/o;if(i.length<n||a>=.4&&i.length<e.maxDocuments)i.push(
|
|
156
|
-
s);else break}return i}async function
|
|
157
|
-
let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,r=[];for(let s=0;s<n;s++){let a=await e.retriever.retrieve(t.query,t.maxDocuments*2);r.push(...a);}let o=r.length;r=
|
|
158
|
-
(r=await e.reranker.rerank(t.query,r));let i=
|
|
159
|
-
...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"
|
|
160
|
-
o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let i=
|
|
161
|
-
|
|
162
|
-
${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function
|
|
205
|
+
s);else break}return i}async function Ks(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};
|
|
206
|
+
let n=t.execution==="MULTI_HOP_RETRIEVAL"?Math.min(t.maxRounds,2):1,r=[];for(let s=0;s<n;s++){let a=await e.retriever.retrieve(t.query,t.maxDocuments*2);r.push(...a);}let o=r.length;r=ld(r),e.reranker&&
|
|
207
|
+
(r=await e.reranker.rerank(t.query,r));let i=dd(r,{maxDocuments:t.maxDocuments});return {docs:i,rounds:n,retrievedCount:o,keptCount:i.length}}function pd(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function k0(){return {goals:[],confirmedFacts:{},userPreferences:{},decisions:[],openItems:[],evidenceRefs:[]}}function x0(t,e){let n={goals:[...t.goals],confirmedFacts:{...t.confirmedFacts},userPreferences:{
|
|
208
|
+
...t.userPreferences},decisions:[...t.decisions],openItems:[...t.openItems],evidenceRefs:[...t.evidenceRefs]};for(let[r,o]of Object.entries(e.set??{}))r==="userPreferences"&&gd(o)?Object.assign(n.userPreferences,
|
|
209
|
+
o):n.confirmedFacts[r]=o;for(let[r,o]of Object.entries(e.append??{})){let i=md(n,r);i?i.push(...o.map(String)):n.confirmedFacts[r]=o;}for(let r of e.remove??[])delete n.confirmedFacts[r],delete n.userPreferences[r],
|
|
210
|
+
hd(n,r);return n}function w0(t){let e=t.rawTurns??3,n=[],r=fd(t.state);r&&n.push({role:"system",content:`Conversation state:
|
|
211
|
+
${r}`});let o=t.history.slice(-e);return n.push(...o,t.current),n}function fd(t){let e=[];return t.goals.length&&e.push(`goals: ${t.goals.join("; ")}`),Object.keys(t.confirmedFacts).length&&e.push(`fa\
|
|
163
212
|
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(
|
|
164
213
|
"; ")}`),t.openItems.length&&e.push(`open: ${t.openItems.join("; ")}`),e.join(`
|
|
165
|
-
`)}function
|
|
166
|
-
for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function
|
|
167
|
-
`).filter(
|
|
168
|
-
|
|
169
|
-
match(/^\[(\d+)\]:\s*(.*)$/);if(
|
|
170
|
-
function
|
|
171
|
-
kind:
|
|
172
|
-
i<t.length;d++,i++){let
|
|
173
|
-
i]}function
|
|
174
|
-
let i=Number(r[2]),s=r[3];return i===0||s.trim()===""?{key:
|
|
175
|
-
o[1]),s=o[2];return s===""?{key:i,kind:{type:"object"}}:{key:i,kind:{type:"scalar",value:
|
|
176
|
-
'"'?(r+='"',i++):o=false:r+=s:s==='"'?o=true:s===e?(n.push(r),r=""):r+=s;}return n.push(r),n.map(i=>i.trim())}function
|
|
177
|
-
'"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function
|
|
178
|
-
'"'):e}function
|
|
179
|
-
`)}function
|
|
180
|
-
e))
|
|
181
|
-
join(o);r.push(`${s}${a}[${e.length}]: ${d}`);return}let
|
|
182
|
-
return}r.push(`${s}${a}[${e.length}]:`);let
|
|
183
|
-
r.push(`${l}${i}${
|
|
184
|
-
o))return null;let i=Object.keys(o);if(i.slice().sort().join("\0")!==r)return null;for(let s of i)if(!
|
|
214
|
+
`)}function md(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 hd(t,e){
|
|
215
|
+
for(let n of ["goals","decisions","openItems","evidenceRefs"]){let r=t[n].indexOf(e);r>=0&&t[n].splice(r,1);}}function gd(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Gs={format:"json-compact",supports(){return true},encode(t){return JSON.stringify(t)},instruction(){return ""}};function Ys(t,e={}){let n=e.delimiter??",",r=e.indent??" ",i=t.split(`
|
|
216
|
+
`).filter(c=>c.trim().length>0).map(c=>({indent:bd(c,r),content:c.slice(Zs(c,r))}));if(i.length===0)return {};let s=i[0];if(s.indent===0){let c=s.content.match(/^\[(\d+)\]\{(.*)\}:\s*$/);if(c){let l=xt(
|
|
217
|
+
c[2],n),d=Number(c[1]),m=[];for(let f=0,h=1;f<d&&h<i.length;f++,h++){let g=i[h];if(g.indent!==1)break;let p=xt(g.content,n),y={};l.forEach((b,v)=>{y[b]=en(p[v]??"null");}),m.push(y);}return m}let u=s.content.
|
|
218
|
+
match(/^\[(\d+)\]:\s*(.*)$/);if(u){let l=u[2];return Number(u[1])===0||l.trim()===""?[]:xt(l,n).map(en)}}let[a]=Qs(i,0,0,n);return a}function Zs(t,e){let n=0;for(;t.startsWith(e,n);)n+=e.length;return n}
|
|
219
|
+
function bd(t,e){return Zs(t,e)/e.length}function Qs(t,e,n,r){let o={},i=e;for(;i<t.length;){let s=t[i];if(s.indent<n)break;if(s.indent>n){i++;continue}let a=vd(s.content,r);if(!a){i++;continue}let{key:c,
|
|
220
|
+
kind:u}=a;if(u.type==="scalar")o[c]=u.value,i++;else if(u.type==="inlineArray")o[c]=u.values,i++;else if(u.type==="emptyArray")o[c]=[],i++;else if(u.type==="table"){let l=[];i++;for(let d=0;d<u.count&&
|
|
221
|
+
i<t.length;d++,i++){let m=t[i];if(m.indent!==n+1)break;let f=xt(m.content,r),h={};u.columns.forEach((g,p)=>{h[g]=en(f[p]??"null");}),l.push(h);}o[c]=l;}else {let[l,d]=Qs(t,i+1,n+1,r);o[c]=l,i=d;}}return [o,
|
|
222
|
+
i]}function vd(t,e){let n=t.match(/^([^[:]+)\[(\d+)\]\{(.*)\}:\s*$/);if(n)return {key:Fn(n[1]),kind:{type:"table",count:Number(n[2]),columns:xt(n[3],e)}};let r=t.match(/^([^[:]+)\[(\d+)\]:\s*(.*)$/);if(r){
|
|
223
|
+
let i=Number(r[2]),s=r[3];return i===0||s.trim()===""?{key:Fn(r[1]),kind:{type:"emptyArray"}}:{key:Fn(r[1]),kind:{type:"inlineArray",values:xt(s,e).map(en)}}}let o=t.match(/^([^:]+):\s*(.*)$/);if(o){let i=Fn(
|
|
224
|
+
o[1]),s=o[2];return s===""?{key:i,kind:{type:"object"}}:{key:i,kind:{type:"scalar",value:en(s)}}}return null}function xt(t,e){let n=[],r="",o=false;for(let i=0;i<t.length;i++){let s=t[i];o?s==='"'?t[i+1]===
|
|
225
|
+
'"'?(r+='"',i++):o=false:r+=s:s==='"'?o=true:s===e?(n.push(r),r=""):r+=s;}return n.push(r),n.map(i=>i.trim())}function en(t){return t.startsWith('"')&&t.endsWith('"')&&t.length>=2?t.slice(1,-1).replace(/""/g,
|
|
226
|
+
'"'):t==="null"?null:t==="true"?true:t==="false"?false:/^-?\d+$/.test(t)||/^-?\d*\.\d+$/.test(t)?Number(t):t}function Fn(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/""/g,
|
|
227
|
+
'"'):e}function yd(t,e={}){let n=e.delimiter??",",r=e.indent??" ",o=[];return Eo(null,t,0,o,n,r),o.join(`
|
|
228
|
+
`)}function Eo(t,e,n,r,o,i){let s=i.repeat(n),a=t===null?"":`${xd(t)}`;if(Array.isArray(e)){kd(a,e,n,r,o,i);return}if(Co(e)){t!==null&&r.push(`${s}${a}:`);let c=t===null?n:n+1;for(let[u,l]of Object.entries(
|
|
229
|
+
e))Eo(u,l,c,r,o,i);return}r.push(`${s}${a}: ${zn(e,o)}`);}function kd(t,e,n,r,o,i){let s=i.repeat(n),a=t===""?"":t;if(e.length===0){r.push(`${s}${a}[0]:`);return}if(e.every(Po)){let d=e.map(m=>zn(m,o)).
|
|
230
|
+
join(o);r.push(`${s}${a}[${e.length}]: ${d}`);return}let c=qn(e);if(c){r.push(`${s}${a}[${e.length}]{${c.join(o)}}:`);let d=i.repeat(n+1);for(let m of e){let f=c.map(h=>zn(m[h],o)).join(o);r.push(`${d}${f}`);}
|
|
231
|
+
return}r.push(`${s}${a}[${e.length}]:`);let u=n+1,l=i.repeat(u);for(let d of e)if(Po(d))r.push(`${l}- ${zn(d,o)}`);else {let m=[];Eo(null,d,0,m,o,i);let[f,...h]=m;r.push(`${l}- ${f??""}`);for(let g of h)
|
|
232
|
+
r.push(`${l}${i}${g}`);}}function qn(t){if(t.length===0)return null;let e=t[0];if(!Co(e))return null;let n=Object.keys(e);if(n.length===0)return null;let r=n.slice().sort().join("\0");for(let o of t){if(!Co(
|
|
233
|
+
o))return null;let i=Object.keys(o);if(i.slice().sort().join("\0")!==r)return null;for(let s of i)if(!Po(o[s]))return null}return n}function xd(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:Xs(t)}function zn(t,e){
|
|
185
234
|
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(`
|
|
186
|
-
`)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?
|
|
187
|
-
"number"||typeof t=="boolean"}function
|
|
188
|
-
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
|
|
189
|
-
encode(e){return
|
|
190
|
-
`)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function
|
|
191
|
-
'""')}"`:e}var
|
|
192
|
-
64,this.minSavingsRatio=e.minimumSavingsRatio??.08,this.qualityPenalty=e.qualityPenalty??(()=>0);}choose(e,n){let r={model:n.model,tokenizer:n.tokenizer},o=[];for(let
|
|
193
|
-
e))continue;let l=
|
|
194
|
-
o.push({format:
|
|
195
|
-
return
|
|
196
|
-
ulted to JSON"}}let a=i,
|
|
197
|
-
d>=this.minSavingsRatio&&
|
|
198
|
-
n)}catch{return false}}function
|
|
199
|
-
length)return false;for(let s=0;s<t.length;s++)if(!
|
|
200
|
-
call(e,s)||!
|
|
201
|
-
string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function
|
|
202
|
-
e.type??
|
|
203
|
-
message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function
|
|
235
|
+
`)||n.includes('"')||n!==n.trim()||/^(true|false|null)$/.test(n)||/^-?\d/.test(n)?Xs(n):n}function Xs(t){return `"${t.replace(/"/g,'""')}"`}function Po(t){return t===null||typeof t=="string"||typeof t==
|
|
236
|
+
"number"||typeof t=="boolean"}function Co(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var wd="Data is the compact encoder: `key[N]{c1,c2}:` declares an N-row table with columns c1,c2; ea\
|
|
237
|
+
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 Sd(t={}){return {format:"compact-rows",supports(){return true},
|
|
238
|
+
encode(e){return yd(e,t)},instruction(){return wd},decode(e){return Ys(e,t)}}}var ea=Sd();var na={format:"csv",supports(t){return Array.isArray(t)&&qn(t)!==null},encode(t){let e=t,n=qn(e),r=n.map(ta).join(","),o=e.map(i=>n.map(s=>ta(i[s])).join(","));return [r,...o].join(`
|
|
239
|
+
`)},instruction(){return "Data is CSV: first line is the header row; each subsequent line is one record."}};function ta(t){if(t==null)return "";let e=String(t);return /[",\n]/.test(e)?`"${e.replace(/"/g,
|
|
240
|
+
'""')}"`:e}var Vn=class{tokenizer;serializers;minSavingsTokens;minSavingsRatio;qualityPenalty;constructor(e){this.tokenizer=e.tokenizer,this.serializers=e.serializers??[Gs,ea,na],this.minSavingsTokens=e.minimumSavingsTokens??
|
|
241
|
+
64,this.minSavingsRatio=e.minimumSavingsRatio??.08,this.qualityPenalty=e.qualityPenalty??(()=>0);}choose(e,n){let r={model:n.model,tokenizer:n.tokenizer},o=[];for(let u of this.serializers){if(!u.supports(
|
|
242
|
+
e))continue;let l=u.encode(e);if(u.format!=="json-compact"&&!Td(u,l,e))continue;let d=u.instruction(e),m=this.tokenizer.count(l,r),f=d?this.tokenizer.count(d,r):0,h=this.qualityPenalty(n.model??"",u.format);
|
|
243
|
+
o.push({format:u.format,encoded:l,instruction:d,payloadTokens:m,instructionTokens:f,penalty:h,total:m+f+h});}let i=o.find(u=>u.format==="json-compact"),s={};for(let u of o)s[u.format]=u.total;if(!i){let u=o[0];
|
|
244
|
+
return u?ra(u,s,"json baseline unavailable"):{chosen:"json-compact",encoded:JSON.stringify(e),instruction:"",candidateTokens:s,instructionOverheadTokens:0,reason:"no serializer supported payload; defa\
|
|
245
|
+
ulted to JSON"}}let a=i,c="json baseline (no challenger cleared thresholds)";for(let u of o){if(u.format==="json-compact")continue;let l=i.total-u.total,d=i.total===0?0:l/i.total;l>=this.minSavingsTokens&&
|
|
246
|
+
d>=this.minSavingsRatio&&u.total<a.total&&(a=u,c=`${u.format} saved ${l} tokens (${(d*100).toFixed(1)}%) vs json`);}return ra(a,s,c)}};function Td(t,e,n){if(!t.decode)return false;try{return Ro(t.decode(e),
|
|
247
|
+
n)}catch{return false}}function Ro(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.isArray(t),r=Array.isArray(e);if(n||r){if(!n||!r||t.length!==e.
|
|
248
|
+
length)return false;for(let s=0;s<t.length;s++)if(!Ro(t[s],e[s]))return false;return true}let o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)return false;for(let s of o)if(!Object.prototype.hasOwnProperty.
|
|
249
|
+
call(e,s)||!Ro(t[s],e[s]))return false;return true}function ra(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function le(t,e,n="$"){let r=[];return Io(t,e,n,r),{valid:r.length===0,errors:r}}function Pd(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
|
|
250
|
+
string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function Io(t,e,n,r){switch(e.enum&&!e.enum.some(i=>Dd(i,t))&&r.push({path:n,message:"value not in enum"}),
|
|
251
|
+
e.type??Pd(t)){case "object":Cd(t,e,n,r);break;case "array":Ed(t,e,n,r);break;case "string":Rd(t,e,n,r);break;case "number":case "integer":Id(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,
|
|
252
|
+
message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function Cd(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,
|
|
204
253
|
message:"expected object"});return}let o=t;for(let i of e.required??[])i in o||r.push({path:`${n}.${i}`,message:"missing required property"});if(e.additionalProperties===false&&e.properties){let i=new Set(
|
|
205
254
|
Object.keys(e.properties));for(let s of Object.keys(o))i.has(s)||r.push({path:`${n}.${s}`,message:"additional property not allowed"});}if(e.properties)for(let[i,s]of Object.entries(e.properties))i in o&&
|
|
206
|
-
|
|
207
|
-
ms ${e.maxItems}`}),e.minItems!=null&&t.length<e.minItems&&r.push({path:n,message:`array below minItems ${e.minItems}`}),e.items&&t.forEach((o,i)=>
|
|
255
|
+
Io(o[i],s,`${n}.${i}`,r);}function Ed(t,e,n,r){if(!Array.isArray(t)){r.push({path:n,message:"expected array"});return}e.maxItems!=null&&t.length>e.maxItems&&r.push({path:n,message:`array exceeds maxIte\
|
|
256
|
+
ms ${e.maxItems}`}),e.minItems!=null&&t.length<e.minItems&&r.push({path:n,message:`array below minItems ${e.minItems}`}),e.items&&t.forEach((o,i)=>Io(o,e.items,`${n}[${i}]`,r));}function Rd(t,e,n,r){if(typeof t!=
|
|
208
257
|
"string"){r.push({path:n,message:"expected string"});return}if(e.maxLength!=null&&t.length>e.maxLength&&r.push({path:n,message:`string exceeds maxLength ${e.maxLength}`}),e.minLength!=null&&t.length<e.
|
|
209
258
|
minLength&&r.push({path:n,message:`string below minLength ${e.minLength}`}),e.pattern){let o=null;try{o=new RegExp(e.pattern);}catch{r.push({path:n,message:`schema pattern is not a valid regular expres\
|
|
210
|
-
sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function
|
|
259
|
+
sion: ${e.pattern}`});}o&&!o.test(t)&&r.push({path:n,message:"string does not match pattern"});}}function Id(t,e,n,r){if(typeof t!="number"||Number.isNaN(t)){r.push({path:n,message:"expected number"});return}
|
|
211
260
|
e.type==="integer"&&!Number.isInteger(t)&&r.push({path:n,message:"expected integer"}),e.maximum!=null&&t>e.maximum&&r.push({path:n,message:`number exceeds maximum ${e.maximum}`}),e.minimum!=null&&t<e.
|
|
212
|
-
minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function
|
|
213
|
-
e,n,r),r}};function
|
|
214
|
-
.${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&
|
|
215
|
-
tring should set maxLength or use an enum`);}function
|
|
216
|
-
ate + repair"}}function
|
|
217
|
-
return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function
|
|
218
|
-
let l=`\0PROTECT_${
|
|
219
|
-
span:
|
|
220
|
-
originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var
|
|
221
|
-
compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function
|
|
222
|
-
" ").replace(/\s+/g," ").trim(),o=n((s=>{let a=new Set,
|
|
223
|
-
`)){let l=
|
|
224
|
-
`)})(t)),i=n(e);return !(!
|
|
225
|
-
|
|
226
|
-
|
|
261
|
+
minimum&&r.push({path:n,message:`number below minimum ${e.minimum}`});}function Dd(t,e){return t===e?true:typeof t!=typeof e?false:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):false}var Un=class{contracts=new Map;register(e){return this.contracts.set(e.contractId,e),this}resolve(e){return this.contracts.get(e)}has(e){return this.contracts.has(e)}static lint(e,n="$"){let r=[];return Do(
|
|
262
|
+
e,n,r),r}};function Do(t,e,n){if(t.type==="object"){t.additionalProperties!==false&&n.push(`${e}: object should set additionalProperties:false`);for(let[r,o]of Object.entries(t.properties??{}))Do(o,`${e}\
|
|
263
|
+
.${r}`,n);}t.type==="array"&&(t.maxItems==null&&n.push(`${e}: array should set maxItems to bound output`),t.items&&Do(t.items,`${e}[]`,n)),t.type==="string"&&t.maxLength==null&&!t.enum&&n.push(`${e}: s\
|
|
264
|
+
tring should set maxLength or use an enum`);}function oa(t,e,n){for(let r of n)if(r.supports(t,e))return {backend:r.id,reason:`first supporting backend: ${r.id}`};return {backend:"none",reason:"no constrained-decoding backend available; will valid\
|
|
265
|
+
ate + repair"}}function H0(t=()=>true){return {id:"provider-native",supports:t}}function _o(t){let e=t.minimumContextTokens??2e3,n=t.minimumNetTokens??200;if(t.contextTokens<e)return {compress:false,reason:`context ${t.contextTokens} < ${e} min`};let r=t.projectedEliminable-t.compressorCostTokens;
|
|
266
|
+
return r<n?{compress:false,reason:`net saving ${r} < ${n} min`}:{compress:true,reason:`net saving ${r} tokens`}}function Q0(t){return {async compress(e){let n=e.protectedSpans??[],r=e.text,o=[];n.forEach((c,u)=>{
|
|
267
|
+
let l=`\0PROTECT_${u}\0`;o.push({token:l,span:c}),r=r.split(c.text).join(l);});let i=await t.compress({text:r,...e.targetRatio!=null?{targetRatio:e.targetRatio}:{}}),s=i.compressed,a=true;for(let{token:c,
|
|
268
|
+
span:u}of o){if(!s.includes(c)){a=false;break}s=s.split(c).join(u.text);}return a?{...i,compressed:s,protectedSpans:n.length,fidelityPassed:true}:{compressed:e.text,originalTokens:i.originalTokens,compressedTokens:i.
|
|
269
|
+
originalTokens,protectedSpans:n.length,fidelityPassed:false,skipped:true,reason:"protected span lost during compression; fell back to original"}}}}var X0={async compress(t){return {compressed:t.text,originalTokens:0,
|
|
270
|
+
compressedTokens:0,protectedSpans:(t.protectedSpans??[]).length,fidelityPassed:true,skipped:true,reason:"no compressor configured (noop)"}}};function ia(t,e){let n=s=>s.toLowerCase().replace(/[.,;:!¡?¿()[\]{}"«»…]/g,
|
|
271
|
+
" ").replace(/\s+/g," ").trim(),o=n((s=>{let a=new Set,c=[];for(let u of s.split(`
|
|
272
|
+
`)){let l=u.trim();l&&a.has(l)||(l&&a.add(l),c.push(u));}return c.join(`
|
|
273
|
+
`)})(t)),i=n(e);return !(!yo(Yt(o),Yt(i))||Qt(Zt(o))!==Qt(Zt(i)))}var Ao=["ansi","carriage-return","json","repeated-lines"],_d=256,Ad=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|[ -/]+[0-~]|[@-_])/g;function Od(t){if(!t.includes("\x1B"))return null;
|
|
274
|
+
let e=t.replace(Ad,"");return e.length<t.length?e:null}function Md(t){let e="";for(let n of t.split("\r"))e=n+e.slice(n.length);return e}function Ld(t){if(!t.includes("\r")||t.includes(`\r
|
|
275
|
+
`))return null;let e=t.split(`
|
|
276
|
+
`).map(n=>n.includes("\r")?Md(n):n).join(`
|
|
277
|
+
`);return e.length<t.length?e:null}var jd=t=>t===32||t===9||t===10||t===13;function Nd(t){let e=t.trim(),n=e.charCodeAt(0);if(n!==123&&n!==91)return null;let r;try{r=JSON.parse(e);}catch{return null}let o=[],
|
|
278
|
+
i=0,s=false;for(let c=0;c<e.length;c++){let u=e.charCodeAt(c);if(s){u===92?c+=1:u===34&&(s=false);continue}if(u===34){s=true;continue}jd(u)&&(c>i&&o.push(e.slice(i,c)),i=c+1);}i<e.length&&o.push(e.slice(i));let a=o.
|
|
279
|
+
join("");if(a.length>=t.length)return null;try{if(JSON.stringify(JSON.parse(a))!==JSON.stringify(r))return null}catch{return null}return a}var ca=/^\[previous line repeated (\d+) more times\]$/,$d=t=>`\
|
|
280
|
+
[previous line repeated ${t} more times]`,sa=3;function Bd(t){let e=[];for(let n of t.split(`
|
|
281
|
+
`)){let r=ca.exec(n);if(r&&e.length>0){let o=e[e.length-1];for(let i=Number(r[1]);i>0;i--)e.push(o);}else e.push(n);}return e.join(`
|
|
282
|
+
`)}function Fd(t){let e=t.split(`
|
|
283
|
+
`);if(e.length<sa||e.some(i=>ca.test(i)))return null;let n=[],r=0;for(let i=0;i<e.length;){let s=e[i],a=i+1;for(;a<e.length&&e[a]===s;)a++;let c=a-i-1,u=$d(c);if(c+1>=sa&&c*(s.length+1)>u.length+1)n.push(
|
|
284
|
+
s,u),r+=c;else for(let l=i;l<a;l++)n.push(e[l]);i=a;}if(r===0)return null;let o=n.join(`
|
|
285
|
+
`);return Bd(o)!==t?null:o.length<t.length?o:null}var zd={ansi:Od,"carriage-return":Ld,json:Nd,"repeated-lines":Fd};function ua(t,e={}){let n=new Set(e.transforms??Ao),r=Math.max(1,e.minSavedChars??256),
|
|
286
|
+
o=t,i=[];for(let a of Ao){if(!n.has(a))continue;let c=zd[a](o);c!=null&&c.length<o.length&&(o=c,i.push(a));}let s=t.length-o.length;return i.length===0?aa(t,"nothing to compact"):s<r?aa(t,`compaction w\
|
|
287
|
+
ould save ${s} chars, below the ${r} minimum`):{text:o,changed:true,applied:i,originalChars:t.length,compactChars:o.length,reason:`${i.join(", ")}: ${s} chars removed`}}function aa(t,e){return {text:t,changed:false,
|
|
288
|
+
applied:[],originalChars:t.length,compactChars:t.length,reason:e}}var qd=new Set(["path","paths","file","files","filepath","filename","absolutepath","relativepath","targetfile","notebookpath"]);function Vd(t){
|
|
289
|
+
if(!t)return false;let e;try{e=JSON.parse(t);}catch{return false}return !e||typeof e!="object"||Array.isArray(e)?false:Object.keys(e).some(n=>qd.has(n.toLowerCase().replace(/[_-]/g,"")))}function la(t,e={}){let n=new Map,
|
|
290
|
+
r=-1;t.forEach((s,a)=>{if(s.role==="assistant"){r=a;for(let c of s.toolCalls??[])c.id&&n.set(c.id,{nombre:c.name,argumentos:c.arguments});}});let o=new Set(e.exceptTools??[]),i={compactados:[],vistasDeFichero:0,
|
|
291
|
+
exceptuados:0};return t.forEach((s,a)=>{if(s.role!=="tool")return;let c=s.toolCallId?n.get(s.toolCallId):void 0,u=c?.nombre??s.name;if(u&&o.has(u)){i.exceptuados+=1;return}if(!e.compactFileViews&&Vd(c?.
|
|
292
|
+
argumentos)){i.vistasDeFichero+=1;return}let l=ua(s.content,e);l.changed&&i.compactados.push({indice:a,texto:l.text,aplicadas:l.applied,enLaCola:a>r});}),i}var da=new WeakSet;function pa(t){da.add(t);}function Oo(t){return typeof t=="object"&&t!==null&&da.has(t)}var Mo=class{id="mock";options;constructor(e={}){this.options=e,pa(this);}async generate(e,n){let r=e.messages.map(c=>c.content).join(`
|
|
293
|
+
`),o=yt.count(r);if(e.tools&&e.tools.length>0){let c=JSON.stringify(e.tools.map(u=>({name:u.id,description:u.description,parameters:u.parameters??{}})));o+=yt.count(c);}let i,s=false;if(e.schema){let c=this.
|
|
294
|
+
options.data??Hn(e.schema);i=JSON.stringify(c),s=true;}else i=this.options.answer??`mock-response(${e.model})`;let a=Math.min(e.maxOutputTokens??Number.MAX_SAFE_INTEGER,yt.count(i));return {text:i,usage:{
|
|
227
295
|
inputTokens:o,outputTokens:a,...this.options.cachedInputTokens!=null?{cachedInputTokens:this.options.cachedInputTokens}:{}},structuredNatively:s}}async*generateStream(e){let n=await this.generate(e),r=Math.
|
|
228
|
-
max(1,this.options.streamChunkChars??8);for(let o=0;o<n.text.length;o+=r)yield {type:"text",delta:n.text.slice(o,o+r)};yield {type:"done",response:n};}};function
|
|
229
|
-
enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?
|
|
230
|
-
array":return t.items?[
|
|
231
|
-
t)}function
|
|
232
|
-
Number(e[2]);return n>5||n===5&&r>=6}function
|
|
233
|
-
return
|
|
234
|
-
|
|
235
|
-
cachedInputPer1k:
|
|
236
|
-
inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),
|
|
237
|
-
"gpt-5.4-nano"
|
|
238
|
-
outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.6-luna"
|
|
239
|
-
cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
|
|
240
|
-
|
|
241
|
-
vigenteHasta:"2026-11-21"}),"gpt-5.6-terra"
|
|
242
|
-
outputPer1k:.018},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),o3
|
|
243
|
-
cachedInputPer1k:
|
|
244
|
-
|
|
245
|
-
largo:{estandar:{inputPer1k:.004,
|
|
246
|
-
|
|
247
|
-
cachedInputPer1k:
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
{
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
296
|
+
max(1,this.options.streamChunkChars??8);for(let o=0;o<n.text.length;o+=r)yield {type:"text",delta:n.text.slice(o,o+r)};yield {type:"done",response:n};}};function Hn(t){if(t.enum&&t.enum.length>0)return t.
|
|
297
|
+
enum[0];switch(t.type){case "object":{let e={};for(let n of t.required??[]){let r=t.properties?.[n];e[n]=r?Hn(r):null;}for(let[n,r]of Object.entries(t.properties??{}))n in e||(e[n]=Hn(r));return e}case "\
|
|
298
|
+
array":return t.items?[Hn(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 cg(t){return new Mo(
|
|
299
|
+
t)}function Lo(t){let e=t.toLowerCase(),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e}function fa(t){let e=/^gpt-(\d+)(?:\.(\d+))?(?![\d.])/.exec(t);if(!e)return false;let n=Number(e[1]),r=e[2]===void 0?0:
|
|
300
|
+
Number(e[2]);return n>5||n===5&&r>=6}function Ue(t){let e=Lo(t);return e.startsWith("gpt-")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?fa(e)?1.25:1:e.startsWith("gemini")?1:1.25}function tn(t){
|
|
301
|
+
return fa(Lo(t))?1.25:1}function jo(t){let e=t.toLowerCase();return e.startsWith("claude")||e.startsWith("anthropic/")||Lo(e).startsWith("claude")?2:Ue(t)}var Ud="https://developers.openai.com/api/docs/pricing",Hd="https://ai.google.dev/gemini-api/docs/pricing",No="2026-09-27",$=t=>({...t,fuente:Ud,consultado:No}),Pe=t=>({...t,fuente:Hd,consultado:No}),
|
|
302
|
+
Wd="https://platform.claude.com/docs/en/about-claude/pricing",re=t=>({...t,fuente:Wd,consultado:No}),Jd={openai:{flex:{"gpt-5":$({inputPer1k:625e-6,cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mi\
|
|
303
|
+
ni":$({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":$({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-5.2":$({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),
|
|
304
|
+
"gpt-5.4":$({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),
|
|
305
|
+
"gpt-5.4-mini":$({inputPer1k:375e-6,cachedInputPer1k:375e-7,outputPer1k:.00225}),"gpt-5.4-nano":$({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.5":$({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
306
|
+
outputPer1k:.015,largo:{estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.6-luna":$({inputPer1k:1e-4,cachedInputPer1k:1e-5,
|
|
307
|
+
cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
|
|
308
|
+
outputPer1k:9e-4}}}),"gpt-5.6-sol":$({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},
|
|
309
|
+
tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),"gpt-5.6-terra":$({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,
|
|
310
|
+
largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),o3:$({inputPer1k:.001,
|
|
311
|
+
cachedInputPer1k:25e-5,outputPer1k:.004}),"o4-mini":$({inputPer1k:55e-5,cachedInputPer1k:138e-6,outputPer1k:.0022}),"gpt-6-astra":$({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
|
|
312
|
+
largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":$({inputPer1k:.001,
|
|
313
|
+
cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,
|
|
314
|
+
cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":$({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
|
|
315
|
+
outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}})},batch:{"gpt-6-astra":$({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025,
|
|
316
|
+
largo:{estandar:{inputPer1k:.02,cachedInputPer1k:.002,cacheWritePer1k:.025,outputPer1k:.075},tier:{inputPer1k:.01,cachedInputPer1k:.001,cacheWritePer1k:.0125,outputPer1k:.0375}}}),"gpt-6-sol":$({inputPer1k:.001,
|
|
317
|
+
cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.005,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015},tier:{inputPer1k:.002,cachedInputPer1k:2e-4,
|
|
318
|
+
cacheWritePer1k:.0025,outputPer1k:.0075}}}),"gpt-6-luna":$({inputPer1k:5e-5,cachedInputPer1k:5e-6,cacheWritePer1k:625e-7,outputPer1k:25e-5,largo:{estandar:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,
|
|
319
|
+
outputPer1k:75e-5},tier:{inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:375e-6}}}),"gpt-5.6-sol":$({inputPer1k:.002,cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.01,
|
|
320
|
+
largo:{estandar:{inputPer1k:.008,cachedInputPer1k:8e-4,cacheWritePer1k:.01,outputPer1k:.03},tier:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.015}},vigenteHasta:"2026-11-21"}),
|
|
321
|
+
"gpt-5.6-terra":$({inputPer1k:.001,cachedInputPer1k:1e-4,cacheWritePer1k:.00125,outputPer1k:.006,largo:{estandar:{inputPer1k:.004,cachedInputPer1k:4e-4,cacheWritePer1k:.005,outputPer1k:.018},tier:{inputPer1k:.002,
|
|
322
|
+
cachedInputPer1k:2e-4,cacheWritePer1k:.0025,outputPer1k:.009}}}),"gpt-5.6-luna":$({inputPer1k:1e-4,cachedInputPer1k:1e-5,cacheWritePer1k:125e-6,outputPer1k:6e-4,largo:{estandar:{inputPer1k:4e-4,cachedInputPer1k:4e-5,
|
|
323
|
+
cacheWritePer1k:5e-4,outputPer1k:.0018},tier:{inputPer1k:2e-4,cachedInputPer1k:2e-5,cacheWritePer1k:25e-5,outputPer1k:9e-4}}}),"gpt-5.5":$({inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.015,largo:{
|
|
324
|
+
estandar:{inputPer1k:.01,cachedInputPer1k:.001,outputPer1k:.045},tier:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225}}}),"gpt-5.4":$({inputPer1k:.00125,cachedInputPer1k:13e-5,outputPer1k:.0075,
|
|
325
|
+
largo:{estandar:{inputPer1k:.005,cachedInputPer1k:5e-4,outputPer1k:.0225},tier:{inputPer1k:.0025,cachedInputPer1k:25e-5,outputPer1k:.01125}}}),"gpt-5.4-mini":$({inputPer1k:375e-6,cachedInputPer1k:375e-7,
|
|
326
|
+
outputPer1k:.00225}),"gpt-5.4-nano":$({inputPer1k:1e-4,cachedInputPer1k:1e-5,outputPer1k:625e-6}),"gpt-5.2":$({inputPer1k:875e-6,cachedInputPer1k:875e-7,outputPer1k:.007}),"gpt-5":$({inputPer1k:625e-6,
|
|
327
|
+
cachedInputPer1k:625e-7,outputPer1k:.005}),"gpt-5-mini":$({inputPer1k:125e-6,cachedInputPer1k:125e-7,outputPer1k:.001}),"gpt-5-nano":$({inputPer1k:25e-6,cachedInputPer1k:25e-7,outputPer1k:2e-4}),"gpt-\
|
|
328
|
+
4.1":$({inputPer1k:.001,outputPer1k:.004}),"gpt-4.1-mini":$({inputPer1k:2e-4,outputPer1k:8e-4}),"gpt-4.1-nano":$({inputPer1k:5e-5,outputPer1k:2e-4}),"gpt-4o":$({inputPer1k:.00125,outputPer1k:.005}),"g\
|
|
329
|
+
pt-4o-mini":$({inputPer1k:75e-6,outputPer1k:3e-4}),o3:$({inputPer1k:.001,outputPer1k:.004}),"o4-mini":$({inputPer1k:55e-5,outputPer1k:.0022}),"o3-mini":$({inputPer1k:55e-5,outputPer1k:.0022}),"o3-pro":$(
|
|
330
|
+
{inputPer1k:.01,outputPer1k:.04})}},anthropic:{batch:{"claude-fable-5-1":re({inputPer1k:.005,cachedInputPer1k:125e-6,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5-1":re({inputPer1k:.005,cachedInputPer1k:125e-6,
|
|
331
|
+
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-fable-5":re({inputPer1k:.005,cachedInputPer1k:5e-4,cacheWritePer1k:.00625,outputPer1k:.025}),"claude-mythos-5":re({inputPer1k:.005,cachedInputPer1k:5e-4,
|
|
332
|
+
cacheWritePer1k:.00625,outputPer1k:.025}),"claude-opus-5-5":re({inputPer1k:.002,cachedInputPer1k:1e-4,cacheWritePer1k:.0025,outputPer1k:.01}),"claude-opus-5":re({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
333
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-8":re({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-7":re({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
334
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-6":re({inputPer1k:.0025,cachedInputPer1k:25e-5,cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4-5":re({inputPer1k:.0025,cachedInputPer1k:25e-5,
|
|
335
|
+
cacheWritePer1k:.003125,outputPer1k:.0125}),"claude-opus-4":re({inputPer1k:.0075,cachedInputPer1k:75e-5,cacheWritePer1k:.009375,outputPer1k:.0375}),"claude-sonnet-5":re({inputPer1k:.001,cachedInputPer1k:1e-4,
|
|
336
|
+
cacheWritePer1k:.00125,outputPer1k:.005}),"claude-sonnet-4-6":re({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4-5":re({inputPer1k:.0015,cachedInputPer1k:15e-5,
|
|
337
|
+
cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-sonnet-4":re({inputPer1k:.0015,cachedInputPer1k:15e-5,cacheWritePer1k:.001875,outputPer1k:.0075}),"claude-haiku-4-5":re({inputPer1k:5e-4,cachedInputPer1k:5e-5,
|
|
338
|
+
cacheWritePer1k:625e-6,outputPer1k:.0025}),"claude-3-5-haiku":re({inputPer1k:4e-4,cachedInputPer1k:4e-5,cacheWritePer1k:5e-4,outputPer1k:.002})}},google:{flex:{"gemini-3.7-flash":Pe({inputPer1k:375e-6,
|
|
339
|
+
outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.5-flash":Pe({inputPer1k:75e-5,outputPer1k:.0045,cachedInputPer1k:8e-5}),"gemini-3.5-flash-lite":Pe({inputPer1k:15e-5,outputPer1k:.00125,
|
|
340
|
+
cachedInputPer1k:2e-5}),"gemini-3.1-pro-preview":Pe({inputPer1k:.001,outputPer1k:.006,cachedInputPer1k:2e-4,largo:{estandar:{inputPer1k:.004,outputPer1k:.018,cachedInputPer1k:4e-4},tier:{inputPer1k:.002,
|
|
341
|
+
outputPer1k:.009,cachedInputPer1k:4e-4}}}),"gemini-2.5-pro":Pe({inputPer1k:625e-6,outputPer1k:.005,cachedInputPer1k:125e-6,largo:{estandar:{inputPer1k:.0025,outputPer1k:.015,cachedInputPer1k:25e-5},tier:{
|
|
342
|
+
inputPer1k:.00125,outputPer1k:.0075,cachedInputPer1k:25e-5}}}),"gemini-2.5-flash":Pe({inputPer1k:15e-5,outputPer1k:.00125,cachedInputPer1k:3e-5}),"gemini-3.8-flash":Pe({inputPer1k:375e-6,outputPer1k:.001875,
|
|
343
|
+
cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.6-flash":Pe({inputPer1k:375e-6,outputPer1k:.001875,cachedInputPer1k:375e-7,vigenteHasta:"2026-12-31"}),"gemini-3.1-flash-lite":Pe({inputPer1k:125e-6,
|
|
344
|
+
outputPer1k:75e-5,cachedInputPer1k:125e-7}),"gemini-3-flash-preview":Pe({inputPer1k:25e-5,outputPer1k:.0015,cachedInputPer1k:5e-5})}}};function He(t){let e=t.lastIndexOf("/");return e>=0?t.slice(e+1):
|
|
345
|
+
t}function nn(t){let e=t.toLowerCase(),n=e.indexOf("/"),r=n>0?e.slice(0,n):"",o=He(e);return r==="openai"||r==="azure-openai"?"openai":r==="google"||r==="google-vertex"?"google":r==="anthropic"?"anthr\
|
|
346
|
+
opic":/^(gpt-|o[1-9](-|$))/.test(o)?"openai":o.startsWith("gemini")?"google":o.startsWith("claude-")?"anthropic":null}function Kd(t){return Date.parse(`${t}T23:59:59.999Z`)}function rn(t,e,n,r=Date.now()){
|
|
347
|
+
if(Ve(n)===void 0)return;let o=vt(n);if(o===void 0)return;let i=Jd[t]?.[e],s=i?i[o]:void 0;if(s&&!(s.vigenteHasta&&r>Kd(s.vigenteHasta)))return s}function Wn(t){let e=Ve(t);if(e)return {...e,cacheWritePer1k:e.
|
|
348
|
+
inputPer1k*Ue(He(t))}}var ma={flex:.5,default:1,auto:1,priority:1,fast:1,scale:1,standard:1,batch:.5},ha=Math.min(...Object.values(ma).filter(t=>t<1)),wt="flex";function $o(t){if(t==null||t==="")return null;let e=ma[t];return e==
|
|
349
|
+
null?{servido:t,factor:null,conDescuento:false}:{servido:t,factor:e,conDescuento:e<1}}var Jn=1e10;function Bo(t){let e=Math.floor(t*Jn)/Jn;return e>t&&(e=(Math.floor(t*Jn)-1)/Jn),e<=0?0:e}var Kn=t=>typeof t==
|
|
350
|
+
"number"&&Number.isFinite(t);function Gn(t){let e=$o(t.tierServido);if(!e)return {ok:false,motivo:"no-served-tier"};if(e.factor==null)return {ok:false,motivo:"unknown-tier"};if(!e.conDescuento)return {ok:false,motivo:"\
|
|
351
|
+
standard-rate-tier"};let n=t.uso;if(n.complete===false||!Kn(n.inputTokens)||!Kn(n.outputTokens)||n.cachedInputTokens!=null&&!Kn(n.cachedInputTokens)||n.cacheWriteInputTokens!=null&&!Kn(n.cacheWriteInputTokens))
|
|
352
|
+
return {ok:false,motivo:"incomplete-usage"};let r=Wn(t.modelo);if(!r)return {ok:false,motivo:"no-standard-price"};let o=t.origen??nn(t.modelo),i=o?rn(o,e.servido,t.modelo,t.ahoraMs):void 0;if(!i)return {ok:false,
|
|
353
|
+
motivo:"no-tier-price"};let s=Math.max(0,n.inputTokens),a=Ue(He(t.modelo)),c=n.cachedInputTokens!=null,u=a<=1||n.cacheWriteInputTokens!=null,l=c?Math.min(Math.max(0,n.cachedInputTokens??0),s):0,d=a>1&&
|
|
354
|
+
u?Math.min(Math.max(0,n.cacheWriteInputTokens??0),s-l):0,m=s-l-d,f=Math.max(0,n.outputTokens),h={input:r.inputPer1k,"cached input":r.cachedInputPer1k??r.inputPer1k,"cache write":r.cacheWritePer1k,output:r.
|
|
355
|
+
outputPer1k},g={input:i.inputPer1k,"cached input":i.cachedInputPer1k,"cache write":i.cacheWritePer1k,output:i.outputPer1k},p=[{tokens:m,posibles:["input",...c?[]:["cached input"],...u?[]:["cache write"]]},
|
|
356
|
+
{tokens:l,posibles:["cached input"]},{tokens:d,posibles:["cache write"]},{tokens:f,posibles:["output"]}],y=m>0&&p[0].posibles.length>1,b=t.precioDelCliente,v=b?{input:b.inputPer1k,"cached input":b.cachedInputPer1k??
|
|
357
|
+
b.inputPer1k,"cache write":b.inputPer1k*a,output:b.outputPer1k}:void 0,w=(j,B)=>{let L=B?v[j]:h[j],F=g[j];return F===void 0?{std:L,aplicado:L}:B?{std:L,aplicado:h[j]>0?L*(F/h[j]):L}:{std:L,aplicado:F}},
|
|
358
|
+
S=new Set,k=j=>{let B=0,L=0;for(let F of p){if(F.tokens<=0)continue;let U=F.posibles[0],V=w(U,j);for(let X of F.posibles.slice(1)){let de=w(X,j);de.std-de.aplicado<V.std-V.aplicado&&(U=X,V=de);}g[U]===
|
|
359
|
+
void 0&&F.posibles.length===1&&S.add(U),B+=F.tokens/1e3*V.std,L+=F.tokens/1e3*V.aplicado;}return {std:B,aplicado:L}},x=k(false),E=x.std-x.aplicado,C=x.std,M=x.aplicado,O=E,T=false;if(b){let j=k(true);C=j.std;let B=j.
|
|
360
|
+
std-j.aplicado;T=B>E,O=Math.min(B,E),M=T?j.std-O:j.aplicado;}if(!(O>0))return {ok:false,motivo:"no-difference"};let R=Bo(O);if(R<=0)return {ok:false,motivo:"no-difference"};let I=[];if(t.origen===null?I.push("\
|
|
361
|
+
the endpoint is not the provider's own API as attested by this package's adapter, so the rate cards it bills cannot be confirmed"):t.tierLeidoDe!=="cuerpo"&&t.tierLeidoDe!=="lote"&&I.push("the served \
|
|
362
|
+
tier was read from a response header whose values the provider does not document"),b&&I.push("priced from your costModels: your standard rate times the published tier-to-standard ratio"+(T?", capped a\
|
|
363
|
+
t the difference between the two published rate cards":"")),y){let j=[...c?[]:["read from"],...u?[]:["written to"]].join(" or ");I.push(`the provider's usage did not say how many input tokens were ${j}\
|
|
364
|
+
its prompt cache, so those tokens are priced at the smallest per-token difference they could have had`);}S.size>0&&I.push(`the provider publishes no ${[...S].join(" or ")} price for this tier, so thos\
|
|
365
|
+
e tokens add nothing`);let A=I.length===0;return {ok:true,importe:R,basis:A?"measured":"estimated",costeEstandar:C,costeAplicado:M,factorEfectivo:M/C,motivoBasis:A?`the provider's own usage for this call\
|
|
366
|
+
at two published rate cards (${i.fuente}, checked ${i.consultado}), with the served tier read back from the provider's official API`+(t.tierLeidoDe==="lote"?" (its batch record: a batch result is bil\
|
|
367
|
+
led at the batch rate card)":""):`estimated: ${I.join("; ")}`,consultado:i.consultado}}function ga(t,e,n){let r=e??nn(t);return r!==null&&rn(r,"batch",t,n)!==void 0}var Gd="slower and variable: OpenAI\
|
|
269
368
|
publishes no latency commitment for the flex tier. What IS documented is the failure shape \u2014 the default SDK timeout is 10 minutes and a request that exceeds it returns 408, and when flex capacity is\
|
|
270
|
-
short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",
|
|
369
|
+
short the request returns 429 and is not charged. Do not put a deferrable request on a user-facing path.",Yd='slower and variable: Google targets minutes for the Flex tier ("Minutes (1\u201315 min target)\
|
|
271
370
|
", https://ai.google.dev/gemini-api/docs/flex-inference) and treats it as sheddable. When Flex capacity is unavailable the request fails with 503 or 429 and is never upgraded to the Standard tier on t\
|
|
272
|
-
he server side. Do not put a deferrable request on a user-facing path.',
|
|
371
|
+
he server side. Do not put a deferrable request on a user-facing path.',Zd="slower and variable, and unknown here: this endpoint is not attested as OpenAI's or Google's own API, so this layer has no p\
|
|
273
372
|
ublished latency statement for it. On those two providers a flex request without capacity fails (429, or 503 on Google) instead of waiting; expect that failure shape. Do not put a deferrable request o\
|
|
274
|
-
n a user-facing path.",
|
|
373
|
+
n a user-facing path.",Qd="unchanged: this provider has no cheaper synchronous processing tier, so nothing was asked for and the request was scheduled exactly as it would have been.",ba="this provider\
|
|
275
374
|
has no cheaper synchronous processing tier, so the request was sent unchanged and nothing is credited; on this provider the deferred discount lives only in the asynchronous batch API, which is not a \
|
|
276
|
-
request/response call";function
|
|
277
|
-
tier without capacity usually fails (429 or 503) rather than waiting; do not put a deferrable
|
|
278
|
-
return
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
function
|
|
282
|
-
|
|
375
|
+
request/response call (with the built-in Anthropic and OpenAI providers, layer.batches.submit() sends such requests there)";function va(t,e=null){return t==null||t===""?Qd:t===wt?e==="openai"?Gd:e==="\
|
|
376
|
+
google"?Yd:Zd:`unknown: this layer has no published latency statement for the "${t}" tier. A cheaper tier without capacity usually fails (429 or 503) rather than waiting; do not put a deferrable reque\
|
|
377
|
+
st on a user-facing path.`}var ya=1024;function St(t,e){return e==="openai"&&nn(He(t))==="openai"&&Ue(He(t))>1}function Fo(t){let e=Ve(t);if(!e||!(e.inputPer1k>0))return null;let n=(e.cachedInputPer1k??e.inputPer1k)/e.inputPer1k;
|
|
378
|
+
return {minimumCacheTokens:ya,cacheReadMultiplier:n,cacheWriteMultiplier:Ue(He(t))}}function ka(t){let e=t.consultado??no,n=Math.max(0,t.uso.inputTokens),r=Math.min(Math.max(0,t.uso.cachedInputTokens??
|
|
379
|
+
0),n),o=Math.min(Math.max(0,t.uso.cacheWriteInputTokens??0),n-r),i=n-r-o;if(n<ya||i<=0)return {importe:0,costeEstandar:0,costeAplicado:0,tokensOrdinarios:Math.max(0,i),consultado:e};let s=i/1e3*t.fila.
|
|
380
|
+
cacheWritePer1k,a=i/1e3*t.fila.inputPer1k;return {importe:Bo(s-a),costeEstandar:s,costeAplicado:a,tokensOrdinarios:i,consultado:e}}var xa=new Set;function W(t,e){xa.has(t)||(xa.add(t),console.warn(e));}function on(t){return {esquemaEnFormatoNativo:false,esquemaEstricto:false,esquemaPorPrompt:false,piezasDelAdaptador:t}}var Xd=2;function Tt(t){return Xd*(t??[]).filter(e=>e.parameters==null).length}var Yn=new WeakMap;
|
|
381
|
+
function Pt(t,e){return Yn.set(t,e),t}function Zn(t){return typeof t=="object"&&t!==null?Yn.get(t):void 0}var wa=new WeakMap;function Sa(t,e){wa.set(t,e);}function Ct(t){return typeof t=="object"&&t!==
|
|
382
|
+
null?wa.get(t):void 0}function Ta(t,e){let n=Yn.get(t);return n&&Yn.set(e,n),e}var Pa=new WeakMap;function Ca(t,e){Pa.set(t,e);}function zo(t){return typeof t=="object"&&t!==null?Pa.get(t):void 0}var Ea=new WeakMap;function Qn(t,e){Ea.set(t,e);}function Ra(t){return typeof t=="object"&&t!==null?Ea.get(t):void 0}function Xn(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.
|
|
383
|
+
hash="",e.toString().replace(/\/+$/,"")}catch{return t.replace(/\/+$/,"")}}function er(t){if(!t.startsWith("/")||t.startsWith("//")||/^\/*[a-z][a-z0-9+.-]*:/i.test(t))throw new Error(`[bvsala] interna\
|
|
384
|
+
l: a batch request path must be relative to the provider base (got "${t}")`);return t}var qo=class{decoder;resto="";crPendiente=false;alPrincipio=true;datos="";evento="";ultimoId;push(e){let n=typeof e=="string"?e:(this.decoder??=new TextDecoder("utf-8")).decode(e,{stream:true});return this.procesar(
|
|
283
385
|
n)}end(){let e=[];if(this.decoder){let n=this.decoder.decode();n!==""&&e.push(...this.procesar(n));}return this.resto!==""&&(this.linea(this.resto,e),this.resto=""),this.despachar(e),this.crPendiente=false,
|
|
284
386
|
e}procesar(e){let n=[];if(e==="")return n;let r=e;if(this.alPrincipio&&(this.alPrincipio=false,r.charCodeAt(0)===65279&&(r=r.slice(1)),r===""))return n;let o=0;this.crPendiente&&(this.crPendiente=false,r.charCodeAt(
|
|
285
387
|
0)===10&&(o=1));let i=o;for(;o<r.length;){let s=r.charCodeAt(o);if(s!==10&&s!==13){o++;continue}this.linea(this.resto+r.slice(i,o),n),this.resto="",s===13&&(o+1<r.length?r.charCodeAt(o+1)===10&&o++:this.
|
|
286
388
|
crPendiente=true),o++,i=o;}return this.resto+=r.slice(i),n}linea(e,n){if(e===""){this.despachar(n);return}if(e.charCodeAt(0)===58)return;let r=e.indexOf(":"),o,i;switch(r===-1?(o=e,i=""):(o=e.slice(0,r),
|
|
287
389
|
i=e.slice(r+1),i.charCodeAt(0)===32&&(i=i.slice(1))),o){case "data":this.datos+=i+`
|
|
288
390
|
`;break;case "event":this.evento=i;break;case "id":i.includes("\0")||(this.ultimoId=i);break;}}despachar(e){if(this.datos===""){this.evento="";return}e.push({event:this.evento===""?"message":
|
|
289
|
-
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};async function*
|
|
290
|
-
end();return}let n=t.getReader();try{for(;;){let{done:r,value:o}=await n.read();if(r)break;o!==void 0&&(yield*e.push(o));}yield*e.end();}finally{try{await n.cancel();}catch{}}}function
|
|
291
|
-
map(String):[];if(o.some(s=>!i.includes(s)))return false;for(let s of Object.values(n))if(!
|
|
292
|
-
isArray(i)&&i.some(s=>!
|
|
293
|
-
test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.test(t)}function
|
|
391
|
+
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};async function*tr(t){let e=new qo;if(typeof t=="string"){yield*e.push(t),yield*e.
|
|
392
|
+
end();return}let n=t.getReader();try{for(;;){let{done:r,value:o}=await n.read();if(r)break;o!==void 0&&(yield*e.push(o));}yield*e.end();}finally{try{await n.cancel();}catch{}}}function We(t){if(t==null||typeof t!="object")return true;let e=t,n=e.properties;if(n&&typeof n=="object"){if(e.additionalProperties!==false)return false;let o=Object.keys(n),i=Array.isArray(e.required)?e.required.
|
|
393
|
+
map(String):[];if(o.some(s=>!i.includes(s)))return false;for(let s of Object.values(n))if(!We(s))return false}if(e.items!==void 0&&!We(e.items))return false;for(let o of ["anyOf","oneOf","allOf"]){let i=e[o];if(Array.
|
|
394
|
+
isArray(i)&&i.some(s=>!We(s)))return false}let r=e.$defs??e.definitions;return !(r&&typeof r=="object"&&Object.values(r).some(o=>!We(o)))}function ep(t){return !/response_format/i.test(t)||/invalid schema/i.
|
|
395
|
+
test(t)?false:/invalid parameter|not supported|unsupported|unrecognized request argument|unknown parameter/i.test(t)}function tp(t){return `Respond with a single JSON object and nothing else: no prose, no\
|
|
294
396
|
explanation, no markdown code fences. The object must validate against this JSON Schema:
|
|
295
|
-
`+JSON.stringify(t)}var
|
|
296
|
-
is.com":"google"};function
|
|
297
|
-
headers?.get?.(e);return typeof n=="string"&&n.trim()!==""?n.trim():void 0}catch{return}}function
|
|
397
|
+
`+JSON.stringify(t)}var np=/(^|\.)api\.openai\.com$|\.openai\.azure\.com$/i;function Vo(t,e,n){return e??ip(n)?t.replace(/^[^/]+\//,""):t}var rp={"api.openai.com":"openai","generativelanguage.googleap\
|
|
398
|
+
is.com":"google"};function op(t){try{let e=new URL(t);return e.protocol!=="https:"?null:rp[e.hostname.toLowerCase()]??null}catch{return null}}var Ia="x-gemini-service-tier";function Da(t,e){try{let n=t.
|
|
399
|
+
headers?.get?.(e);return typeof n=="string"&&n.trim()!==""?n.trim():void 0}catch{return}}function Uo(t,e,n){if(e.explicitCacheWrites!==true||!St(t,n))return null;let r=e.stablePrefixMessages;if(r==null||
|
|
298
400
|
!Number.isInteger(r)||r<=0||r>e.messages.length)return {puntos:0,indice:-1};let o=e.messages[r-1];return (o.role==="system"||o.role==="user"||o.role==="tool")&&typeof o.content=="string"&&o.content!==""?
|
|
299
|
-
{puntos:1,indice:r-1}:{puntos:0,indice:-1}}function
|
|
300
|
-
this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch,this.origen=
|
|
301
|
-
this.opts.
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
if(!s.ok){let a=await
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
status}: ${
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
"
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
r){let
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
"
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
).
|
|
380
|
-
|
|
381
|
-
this.
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
(
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
401
|
+
{puntos:1,indice:r-1}:{puntos:0,indice:-1}}function ip(t){try{return np.test(new URL(t).hostname)}catch{return false}}var _a=class{id;opts;fetchImpl;sinResponseFormat=new Set;streamOptionsRejected=false;origen;constructor(e){
|
|
402
|
+
this.opts=e,this.id=`openai-compatible:${e.baseUrl}`,this.fetchImpl=e.fetchImpl??fetch,this.origen=op(e.baseUrl),Sa(this,this.origen);let n=(o,i)=>o.schema!=null&&!this.sinResponseFormat.has(i),r=o=>Vo(
|
|
403
|
+
o,this.opts.stripProviderPrefix,this.opts.baseUrl);Qn(this,{protocolo:"openai",origen:this.origen,endpoint:Xn(e.baseUrl),cuerpo:o=>{let i=r(o.model);return this.construirCuerpo(i,o,n(o,i))},leer:(o,i)=>{
|
|
404
|
+
let s=r(i.model);return this.leerJson(o,void 0,i,n(i,s),s,false)},solicitar:(o,i)=>this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}${er(o)}`,{method:i.method,headers:{...i.json!==void 0?{"content-t\
|
|
405
|
+
ype":"application/json"}:{},...this.opts.apiKey?{authorization:`Bearer ${this.opts.apiKey}`}:{},...this.opts.headers},...i.json!==void 0?{body:JSON.stringify(i.json)}:i.form?{body:i.form}:{},...i.signal?
|
|
406
|
+
{signal:i.signal}:{}})});}async generate(e,n){let r=Vo(e.model,this.opts.stripProviderPrefix,this.opts.baseUrl),o=n?.signal,i=e.schema!=null&&!this.sinResponseFormat.has(r),s=await this.enviar(r,e,i,void 0,
|
|
407
|
+
o);if(!s.ok&&s.status===400&&i){let a=await rr(s);if(!ep(a))throw new Error(`provider ${s.status}: ${a}`);this.sinResponseFormat.add(r),W(`sin-response-format:${r}`,`[bvsala] Model "${r}" rejects \`res\
|
|
408
|
+
ponse_format\` with a 400: it has no structured outputs. The request is repeated asking for the JSON via prompt (once only: the model is noted and the following requests go straight there). The schema \
|
|
409
|
+
still travels and the layer still validates, but the guarantee comes from the layer, not the provider, and the report says so: \`constraints.backend: "none"\`. To recover the native guarantee, use a mod\
|
|
410
|
+
el with structured outputs (gpt-4o or later).`),i=false,s=await this.enviar(r,e,false,void 0,o);}if(!s.ok){let a=await rr(s);throw new Error(`provider ${s.status}: ${a}`)}return this.leer(s,e,i,r)}async*generateStream(e,n={}){
|
|
411
|
+
if(e.schema!=null||e.deferrable===true){let x=await this.generate(e);x.text!==""&&(yield {type:"text",delta:x.text}),yield {type:"done",response:x};return}let r=Vo(e.model,this.opts.stripProviderPrefix,this.
|
|
412
|
+
opts.baseUrl),o=n.signal,i=!this.streamOptionsRejected,s=await this.enviar(r,e,false,{includeUsage:i,...o?{signal:o}:{}});if(!s.ok&&i&&(s.status===400||s.status===422)){let x=await rr(s);if(s.status!==422&&
|
|
413
|
+
!/stream_options|include_usage/i.test(x))throw new Error(`provider ${s.status}: ${x}`);if(this.opts.requireUsage)throw new Error(`provider ${s.status}: this endpoint rejects stream_options, so a strea\
|
|
414
|
+
med answer would carry no usage and requireUsage is set. ${x}`);s=await this.enviar(r,e,false,{includeUsage:false,...o?{signal:o}:{}}),s.ok&&(this.streamOptionsRejected=true,W(`sin-stream-options:${this.opts.
|
|
415
|
+
baseUrl}`,"[bvsala] This endpoint rejects `stream_options`, so streamed answers from it carry no usage: they are reported as `unmeasured` and never billed. Use `generate()` for a measured figure, or a\
|
|
416
|
+
n endpoint that reports usage when streaming."));}if(!s.ok)throw new Error(`provider ${s.status}: ${await rr(s)}`);if((s.headers.get("content-type")??"").includes("application/json")){let x=await this.
|
|
417
|
+
leer(s,e,false,r);x.text!==""&&(yield {type:"text",delta:x.text}),yield {type:"done",response:x};return}let a=s.body,c=a&&typeof a.getReader=="function"?a:await s.text(),u="",l=new Map,d,m,f,h=false;for await(let x of tr(
|
|
418
|
+
c)){if(x.data==="[DONE]")break;let E;try{E=JSON.parse(x.data);}catch{continue}if(E===null||typeof E!="object")continue;if(E.error!=null){let O=E.error,T=typeof O.message=="string"?O.message:JSON.stringify(
|
|
419
|
+
E.error);throw new Error(`provider stream error: ${T}`)}let C=E.choices?.[0],M=C?.delta;(nr(M?.reasoning_content)||nr(M?.reasoning))&&(h=true),typeof M?.content=="string"&&M.content!==""&&(u+=M.content,
|
|
420
|
+
yield {type:"text",delta:M.content});for(let O of M?.tool_calls??[]){let T=typeof O.index=="number"?O.index:0,R=l.get(T)??{args:""};!R.id&&typeof O.id=="string"&&O.id!==""&&(R.id=O.id);let I=O.function?.
|
|
421
|
+
name;!R.name&&typeof I=="string"&&I!==""&&(R.name=I),typeof O.function?.arguments=="string"&&(R.args+=O.function.arguments),l.set(T,R);}C?.finish_reason!=null&&(d=C.finish_reason),E.usage!=null&&typeof E.
|
|
422
|
+
usage=="object"&&(m=E.usage),typeof E.service_tier=="string"&&E.service_tier!==""&&(f=E.service_tier);}if(d===void 0)throw new Error("provider stream ended before completion (no finish_reason)");let g=typeof m?.
|
|
423
|
+
prompt_tokens!="number",p=typeof m?.completion_tokens!="number";if(this.opts.requireUsage&&(g||p))throw new Error(Ma(m?.prompt_tokens,m?.completion_tokens));let y=Aa(m,h),b=Oa(m),v={inputTokens:m?.prompt_tokens??
|
|
424
|
+
0,outputTokens:m?.completion_tokens??0,...m?.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:m.prompt_tokens_details.cached_tokens}:{},...b!==void 0?{cacheWriteInputTokens:b}:{},...y!==void 0?
|
|
425
|
+
{reasoningTokens:y}:{},...g||p?{complete:false}:{}},w=[...l.entries()].sort((x,E)=>x[0]-E[0]).map(([,x])=>({...x.id?{id:x.id}:{},name:x.name??"",arguments:x.args})).filter(x=>x.name!==""),S=f?"cuerpo":void 0;
|
|
426
|
+
!f&&this.origen==="google"&&(f=Da(s,Ia),f&&(S="cabecera"));let k=Uo(r,e,this.origen);yield {type:"done",response:Pt({text:u,...w.length>0?{toolCalls:w}:{},finishReason:d,...f?{servedServiceTier:f}:{},usage:v,
|
|
427
|
+
structuredNatively:false,raw:m??null},{...on(Tt(e.tools)),origen:this.origen,...S?{tierLeidoDe:S}:{},...k?{cacheExplicita:{puntos:k.puntos}}:{}})};}async enviar(e,n,r,o,i){let s=this.construirCuerpo(e,n,r,
|
|
428
|
+
o);return await this.fetchImpl(`${this.opts.baseUrl.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",...this.opts.apiKey?{authorization:`Bearer ${this.opts.
|
|
429
|
+
apiKey}`}:{},...this.opts.headers},body:JSON.stringify(s),...o?.signal?{signal:o.signal}:!o&&i?{signal:i}:{}})}construirCuerpo(e,n,r,o){let i=n.messages.map(c=>c.role==="tool"?{role:"tool",content:c.content,
|
|
430
|
+
tool_call_id:c.toolCallId??c.metadata?.tool_call_id,...c.name?{name:c.name}:{}}:c.role==="assistant"&&c.toolCalls&&c.toolCalls.length>0?{role:"assistant",content:c.content||null,tool_calls:c.toolCalls.
|
|
431
|
+
map((u,l)=>({id:u.id??`call_${l}`,type:"function",function:{name:u.name,arguments:u.arguments}}))}:{role:c.role,content:c.content}),s=Uo(e,n,this.origen);if(s?.puntos===1){let c=i[s.indice];c.content=
|
|
432
|
+
[{type:"text",text:c.content,prompt_cache_breakpoint:{mode:"explicit"}}];}n.schema&&!r&&i.push({role:"system",content:tp(n.schema)});let a={model:e,messages:i};if(n.maxOutputTokens!=null&&(a.max_tokens=
|
|
433
|
+
n.maxOutputTokens),n.temperature!=null&&(a.temperature=n.temperature),n.seed!=null&&(a.seed=n.seed),n.promptCacheKey!=null&&(a.prompt_cache_key=n.promptCacheKey),n.deferrable===true&&(a.service_tier=wt),
|
|
434
|
+
s&&(a.prompt_cache_options={mode:"explicit"}),n.schema&&r){let c=We(n.schema);c||W("strict-incompatible","[bvsala] The response contract does not meet OpenAI's `strict` mode (in strict, `required` mus\
|
|
435
|
+
t list ALL the keys in `properties`, and every object needs `additionalProperties: false`). The schema is sent with `strict: false`: the model is still guided and the layer still validates, but the gu\
|
|
436
|
+
arantee comes from the layer, not the provider. To recover it, make every key in the contract required."),a.response_format={type:"json_schema",json_schema:{name:"bvsala_contract",schema:n.schema,strict:c}};}
|
|
437
|
+
return n.tools&&n.tools.length>0&&(a.tools=n.tools.map(c=>({type:"function",function:{name:c.id,...c.description?{description:c.description}:{},parameters:c.parameters??{type:"object",properties:{}}}}))),
|
|
438
|
+
o&&(a.stream=true,o.includeUsage&&(a.stream_options={include_usage:true})),a}async leer(e,n,r,o){let i=await e.json();return this.leerJson(i,e,n,r,o,this.opts.requireUsage===true)}leerJson(e,n,r,o,i,s){let a=e.
|
|
439
|
+
choices?.[0]?.message,c=a?.content??"",u=(a?.tool_calls??[]).map(S=>({...S.id?{id:S.id}:{},name:S.function?.name??"",arguments:S.function?.arguments??""})).filter(S=>S.name!==""),l=e.usage??{},d=l.prompt_tokens??
|
|
440
|
+
0,m=l.completion_tokens??0,f=typeof l.prompt_tokens!="number",h=typeof l.completion_tokens!="number";if(s&&(f||h))throw new Error(Ma(l.prompt_tokens,l.completion_tokens));let g=e.choices?.[0]?.finish_reason,
|
|
441
|
+
p=typeof e.service_tier=="string"&&e.service_tier!==""?e.service_tier:void 0,y=p?"cuerpo":void 0;!p&&this.origen==="google"&&n&&(p=Da(n,Ia),p&&(y="cabecera"));let b=Oa(l),v=Uo(i,r,this.origen),w=Aa(l,
|
|
442
|
+
nr(a?.reasoning_content)||nr(a?.reasoning));return Pt({text:c,...u.length>0?{toolCalls:u}:{},...g?{finishReason:g}:{},...p?{servedServiceTier:p}:{},...r.deferrable===true?{requestedServiceTier:wt}:{},usage:{
|
|
443
|
+
inputTokens:d,outputTokens:m,...l.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:l.prompt_tokens_details.cached_tokens}:{},...b!==void 0?{cacheWriteInputTokens:b}:{},...w!==void 0?{reasoningTokens:w}:
|
|
444
|
+
{},...f||h?{complete:false}:{}},structuredNatively:r.schema!=null&&o,raw:e},{esquemaEnFormatoNativo:r.schema!=null&&o,esquemaEstricto:r.schema!=null&&o&&We(r.schema),esquemaPorPrompt:r.schema!=null&&!o,piezasDelAdaptador:Tt(
|
|
445
|
+
r.tools),origen:this.origen,...y?{tierLeidoDe:y}:{},...v?{cacheExplicita:{puntos:v.puntos}}:{}})}};function Aa(t,e){let n=t?.completion_tokens_details?.reasoning_tokens;if(!(typeof n!="number"||!Number.
|
|
446
|
+
isInteger(n)||n<0)&&!(n===0&&e))return n}function Oa(t){let e=t?.prompt_tokens_details?.cache_write_tokens;return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:void 0}function nr(t){return typeof t==
|
|
447
|
+
"string"&&t!==""}function Ma(t,e){return `provider returned incomplete usage (prompt=${t??"absent"}, completion=${e??"absent"}); cannot measure cost. For gateways/streaming, ensure usage reporting is e\
|
|
448
|
+
nabled.`}async function rr(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function La(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:
|
|
449
|
+
`+JSON.stringify(t)}var Et=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:0;function ja(t){if(!Array.isArray(t))return null;let e={input:0,output:0,cacheRead:0,cacheWrite:0,cacheWrite1h:0,iteraciones:0};for(let n of t){
|
|
450
|
+
if(n===null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;e.iteraciones++,e.input+=Et(r.input_tokens),e.output+=Et(r.output_tokens),e.cacheRead+=Et(r.cache_read_input_tokens);
|
|
451
|
+
let o=r.cache_creation,i=Et(o?.ephemeral_5m_input_tokens),s=Et(o?.ephemeral_1h_input_tokens),a=typeof r.cache_creation_input_tokens=="number"?Et(r.cache_creation_input_tokens):i+s;e.cacheWrite+=a,e.cacheWrite1h+=
|
|
452
|
+
Math.min(s,a);}return e.iteraciones>0?e:null}function Ho(t,e,n){let r=t??{},o=ja(r.iterations),i=Na(r.cache_read_input_tokens,o?.cacheRead),s=Na(r.cache_creation_input_tokens,o?.cacheWrite),a=r.cache_creation?.ephemeral_1h_input_tokens,c=typeof a==
|
|
453
|
+
"number"||(o?.cacheWrite1h??0)>0?Math.min(Math.max(0,(typeof a=="number"?a:0)+(o?.cacheWrite1h??0)),s??0):void 0,u=(r.input_tokens??0)+(o?.input??0)+(s??0)+(i??0),l=(e??0)+(o?.output??0),d=typeof r.input_tokens!=
|
|
454
|
+
"number",m=typeof e!="number";return {usage:{inputTokens:u,outputTokens:l,...i!=null?{cachedInputTokens:i}:{},...s!=null?{cacheWriteInputTokens:s}:{},...c!==void 0?{cacheWrite1hInputTokens:c}:{},...n||
|
|
455
|
+
m||o?{}:{reasoningTokens:0},...d||m?{complete:false}:{}},entradaAusente:d,salidaAusente:m}}function Na(t,e){return e?(t??0)+e:t}function Wo(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
|
|
456
|
+
function Jo(t,e){let n=Object.fromEntries(Object.entries(e??{}).filter(([,o])=>o!=null)),r=t?.cache_creation||e?.cache_creation?{...t?.cache_creation??{},...e?.cache_creation??{}}:void 0;return {...t??
|
|
457
|
+
{},...n,...r?{cache_creation:r}:{}}}function Ko(t){return t==="thinking"||t==="redacted_thinking"}function Go(t){switch(t){case "end_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "\
|
|
458
|
+
tool_calls";case "refusal":return "content_filter";default:return t}}var or=4,st="bvsala_contract",$a=class{id;opts;fetchImpl;constructor(e={}){this.opts=e,this.id=`anthropic:${e.baseUrl??"https://api.anthropic.com/v1"}`,this.fetchImpl=e.fetchImpl??fetch,Ca(this,Ba(e.baseUrl)?
|
|
459
|
+
"oficial":"compatible");let n=this.opts.baseUrl??"https://api.anthropic.com/v1";Qn(this,{protocolo:"anthropic",origen:cp(n),endpoint:Xn(n),cuerpo:r=>this.construirCuerpo(r).body,leer:(r,o)=>this.leerMensaje(
|
|
460
|
+
r,o,false,false,false,false),solicitar:(r,o)=>{let i=`${n.replace(/\/$/,"")}${er(r)}`;return this.fetchImpl(i,{method:o.method,headers:{...o.json!==void 0?{"content-type":"application/json"}:{},"anthropic-version":this.
|
|
461
|
+
opts.apiVersion??"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},...o.json!==void 0?{body:JSON.stringify(o.json)}:{},...o.signal?{signal:o.signal}:{}})}});}modeloEnElCable(e){
|
|
462
|
+
return this.opts.stripProviderPrefix??Ba(this.opts.baseUrl)?e.replace(/^[^/]+\//,""):e}async generate(e,n){let r=this.construirCuerpo(e),o=await this.enviar(r.body,n?.signal);if(!o.ok)throw new Error(
|
|
463
|
+
`provider ${o.status}: ${await qa(o)}`);return this.leer(o,e,r.contratoNativo,r.turnoAnadido,r.esquemaPorPrompt)}async*generateStream(e,n={}){if(e.schema!=null||e.deferrable===true){let k=await this.generate(
|
|
464
|
+
e);k.text!==""&&(yield {type:"text",delta:k.text}),yield {type:"done",response:k};return}let r=this.construirCuerpo(e),o=r.body;o.stream=true;let i=await this.enviar(o,n.signal);if(!i.ok)throw new Error(`\
|
|
465
|
+
provider ${i.status}: ${await qa(i)}`);if((i.headers.get("content-type")??"").includes("application/json")){let k=await this.leer(i,e,r.contratoNativo,r.turnoAnadido,r.esquemaPorPrompt);k.text!==""&&(yield {
|
|
466
|
+
type:"text",delta:k.text}),yield {type:"done",response:k};return}let s=i.body,a=s&&typeof s.getReader=="function"?s:await i.text(),c="",u=new Map,l,d,m=false,f=false,h,g=false;for await(let k of tr(a)){let x;try{
|
|
467
|
+
x=JSON.parse(k.data);}catch{continue}if(x===null||typeof x!="object")continue;let E=k.event!=="message"?k.event:x.type??k.event;if(E==="message_start")l=x.message?.usage??l;else if(E==="content_block_s\
|
|
468
|
+
tart"){let C=x.content_block;Ko(C?.type)&&(g=true),typeof x.index=="number"&&C&&u.set(x.index,{tipo:C.type??"",...typeof C.id=="string"?{id:C.id}:{},...typeof C.name=="string"?{name:C.name}:{},json:"",...C.
|
|
469
|
+
content!==void 0?{content:C.content}:{}});}else if(E==="content_block_delta"){let C=x.delta;if(C?.type==="text_delta"&&typeof C.text=="string"&&C.text!=="")c+=C.text,yield {type:"text",delta:C.text};else if(C?.
|
|
470
|
+
type==="input_json_delta"&&typeof C.partial_json=="string"){let M=typeof x.index=="number"?u.get(x.index):void 0;M&&(M.json+=C.partial_json);}}else if(E==="message_delta")m=true,h=x.delta?.stop_reason??h,
|
|
471
|
+
x.usage&&(d=Jo(d,x.usage));else if(E==="message_stop"){f=true;break}else if(E==="error")throw new Error(`provider stream error: ${x.error?.type}: ${x.error?.message}`)}if(!f&&!m)throw new Error("provide\
|
|
472
|
+
r stream ended before completion (no message_delta)");let p=Jo(l,d),b=(m?Ho(p,d?.output_tokens,g):void 0)?.usage??{inputTokens:0,outputTokens:0,complete:false};if(this.opts.requireUsage&&b.complete===false)
|
|
473
|
+
throw new Error(za(m?p.input_tokens:void 0,m?d?.output_tokens:void 0));let v=[...u.entries()].sort((k,x)=>k[0]-x[0]).map(([,k])=>k).filter(k=>k.tipo==="tool_use"&&k.name!==st).map(k=>({...k.id?{id:k.id}:
|
|
474
|
+
{},name:k.name??"",arguments:ap(k.json)})).filter(k=>k.name!==""),w=Wo(p),S=e.toolSearch?Fa([...u.entries()].sort((k,x)=>k[0]-x[0]).map(([,k])=>({type:k.tipo,name:k.name,content:k.content}))):void 0;yield {
|
|
475
|
+
type:"done",response:Pt({text:c,...v.length>0?{toolCalls:v}:{},...h?{finishReason:Go(h)}:{},...w?{servedServiceTier:w}:{},...S?{toolSearch:S}:{},usage:b,structuredNatively:false,raw:{usage:p,stop_reason:h}},
|
|
476
|
+
on((r.turnoAnadido?1:0)+Tt(e.tools)))};}async enviar(e,n){let r=(this.opts.baseUrl??"https://api.anthropic.com/v1").replace(/\/$/,"");return await this.fetchImpl(`${r}/messages`,{method:"POST",headers:{
|
|
477
|
+
"content-type":"application/json","anthropic-version":this.opts.apiVersion??"2023-06-01",...this.opts.apiKey?{"x-api-key":this.opts.apiKey}:{},...this.opts.headers},body:JSON.stringify(e),...n?{signal:n}:
|
|
478
|
+
{}})}construirCuerpo(e){let{system:n,messages:r,prefijoEnMensajes:o,prefijoEnSystem:i,turnoAnadido:s}=sp(e);if(r.length===0)throw new Error("anthropic: the request has no user/assistant message. The M\
|
|
479
|
+
essages API needs at least one, and system prompts travel in the `system` field \u2014 they do not count.");let a=(e.tools??[]).map(f=>({name:f.id,...f.description?{description:f.description}:{},input_schema:f.
|
|
480
|
+
parameters??{type:"object",properties:{}}}));if(e.toolSearch&&a.length>0){let f=new Set(e.toolSearch.alwaysLoaded);for(let h of a)f.has(h.name)||(h.defer_loading=true);a.unshift({...xo[e.toolSearch.variant]});}
|
|
481
|
+
let c=false,u=false,l=false;if(e.schema){let f=a.length>0,h=a.some(p=>p.name===st),g=We(e.schema);h?(n.push({type:"text",text:La(e.schema)}),u=true,W("anthropic-contrato-nombre-ocupado",`[bvsala] One of your too\
|
|
482
|
+
ls is already named \`${st}\`, so the output contract cannot travel as a tool without colliding with it (duplicate tool names are a provider error). The schema is sent as prompt text instead, which is \
|
|
483
|
+
measurably more expensive on this API. Rename that tool to get the cheaper path.`)):(!g&&!f&&W("anthropic-strict-incompatible","[bvsala] The response contract does not meet `strict` mode (in strict, `\
|
|
484
|
+
required` must list ALL the keys in `properties`, and every object needs `additionalProperties: false`). The schema is sent without `strict`: the model is still guided and the layer still validates, b\
|
|
485
|
+
ut the guarantee comes from the layer, not the provider."),c=g&&!f,a.push({name:st,description:f?"Return the final answer in the required shape. Use the other tools first if you need data; call this o\
|
|
486
|
+
ne instead of writing the answer as text.":"Return the final answer in the required shape.",input_schema:e.schema,...c?{strict:true}:{}}),f&&(l=this.opts.forceAnswerThroughTool!==false,W("anthropic-contrat\
|
|
487
|
+
o-con-herramientas","[bvsala] This request carries BOTH your tools and an output contract. On Anthropic's Messages API a specific shape is only GUARANTEED by forcing that exact tool, and forcing ours \
|
|
488
|
+
would leave the model unable to call yours. The contract travels as one extra tool"+(l?' and the request is sent with `tool_choice: {type: "any"}`, so the model must answer through SOME tool \u2014 yours o\
|
|
489
|
+
r the contract \u2014 and can no longer reply in prose. Your tool turn is untouched. The guarantee is still the layer\'s, not the provider\'s (`constraints.backend: "none"`), because the model may pick one o\
|
|
490
|
+
f your tools and defer the final answer to the next turn.':", not forced (`forceAnswerThroughTool: false`). The guarantee is the layer's, not the provider's (`constraints.backend: \"none\"`), and if the\
|
|
491
|
+
model answers in prose the layer pays a second full call to repair it \u2014 on this API that second call re-pays the whole tool-use overhead.")+" Dropping either the tools or the contract from this \
|
|
492
|
+
request is what makes the guarantee free.")));}let d={model:this.modeloEnElCable(e.model),max_tokens:e.maxOutputTokens??this.opts.defaultMaxOutputTokens??4096,messages:r};n.length>0&&(d.system=n),e.temperature!=
|
|
493
|
+
null&&(d.temperature=e.temperature),a.length>0&&(d.tools=a),c?d.tool_choice={type:"tool",name:st}:l&&(d.tool_choice={type:"any"}),e.deferrable===true&&W("anthropic-sin-tier-diferible","[bvsala] This req\
|
|
494
|
+
uest was declared deferrable, but the Anthropic Messages API has NO cheaper synchronous tier: its `service_tier` chooses between priority capacity (more expensive) and standard, not a flex. The reques\
|
|
495
|
+
t goes out unchanged and the report credits no discount. The 50% for deferring exists in the Message Batches API, which is asynchronous and does not fit a request/response call: send such requests wit\
|
|
496
|
+
h layer.batches.submit() instead.");let m=this.marcarCache(e,n,r,o,i);return this.opts.automaticCache===true&&e.cachePlacement==null&&e.stablePrefixMessages!=null&&m<Math.min(this.opts.maxCacheBreakpoints??
|
|
497
|
+
or,or)&&(d.cache_control={type:"ephemeral"}),{body:d,contratoNativo:c,turnoAnadido:s,esquemaPorPrompt:u}}marcarCache(e,n,r,o,i){if(e.promptCacheKey!=null,e.stablePrefixMessages==null)return 0;let s=Math.
|
|
498
|
+
min(this.opts.maxCacheBreakpoints??or,or);if(s<=0)return 0;let a=s,c=()=>e.cachePlacement?.ttl==="1h"?{type:"ephemeral",ttl:"1h"}:{type:"ephemeral"},u=i>0?n[i-1]:void 0;u&&(u.cache_control=c(),s-=1);let l=r[r.
|
|
499
|
+
length-1],d=l?.content[l.content.length-1];if(e.cachePlacement?.tail===true&&s>0&&d&&(d.cache_control=c(),s-=1),s>0&&o>0){let m=r[Math.min(o,r.length)-1],f=m?.content[m.content.length-1];f&&f.cache_control==
|
|
500
|
+
null&&(f.cache_control=c(),s-=1);}return a-s}async leer(e,n,r,o,i){let s=await e.json();return this.leerMensaje(s,n,r,o,i,this.opts.requireUsage===true)}leerMensaje(e,n,r,o,i,s){let a=e.content??[],c=a.some(
|
|
501
|
+
v=>Ko(v.type)),u=a.filter(v=>v.type==="text").map(v=>v.text??"").join(""),l=a.filter(v=>v.type==="tool_use"&&v.name!==st).map(v=>({...v.id?{id:v.id}:{},name:v.name??"",arguments:JSON.stringify(v.input??
|
|
502
|
+
{})})).filter(v=>v.name!==""),d=a.find(v=>v.type==="tool_use"&&v.name===st),m=d?JSON.stringify(d.input??{}):u,f=e.usage,{usage:h,entradaAusente:g,salidaAusente:p}=Ho(f,f?.output_tokens,c);if(s&&(g||p))
|
|
503
|
+
throw new Error(za(f?.input_tokens,f?.output_tokens));let y=Wo(f),b=n.toolSearch?Fa(a):void 0;return Pt({text:m,...l.length>0?{toolCalls:l}:{},...e.stop_reason?{finishReason:Go(e.stop_reason)}:{},...y?
|
|
504
|
+
{servedServiceTier:y}:{},usage:h,structuredNatively:n.schema!=null&&r,...b?{toolSearch:b}:{},raw:e},{...on((o?1:0)+Tt(n.tools)),esquemaPorPrompt:i})}};function sp(t){let e=[],n=[],r=t.stablePrefixMessages??
|
|
505
|
+
0,o=0,i=0,s=true;t.messages.forEach((c,u)=>{if(c.role==="system"&&s){e.push({type:"text",text:c.content}),u<r&&(i=e.length);return}s=false,n.push({role:c.role==="assistant"?"assistant":"user",content:[{type:"\
|
|
506
|
+
text",text:c.content}]}),u<r&&(o=n.length);});let a=false;return n.length>0&&n[0].role==="assistant"&&(n.unshift({role:"user",content:[{type:"text",text:"(continue)"}]}),o>0&&(o+=1),a=true),{system:e,messages:n,
|
|
507
|
+
prefijoEnMensajes:o,prefijoEnSystem:i,turnoAnadido:a}}function Ba(t){try{return /(^|\.)api\.anthropic\.com$/i.test(new URL(t??"https://api.anthropic.com/v1").hostname)}catch{return false}}function Fa(t){let e=0,
|
|
508
|
+
n=0,r=[];for(let o of t)if(o.type==="server_tool_use"&&typeof o.name=="string"&&o.name.startsWith("tool_search_tool"))e+=1;else if(o.type==="tool_search_tool_result"){let i=o.content;if(i&&i.type==="t\
|
|
509
|
+
ool_search_tool_result_error")n+=1;else if(i&&Array.isArray(i.tool_references))for(let s of i.tool_references)typeof s?.tool_name=="string"&&!r.includes(s.tool_name)&&r.push(s.tool_name);}return {searches:e,
|
|
510
|
+
loaded:r,errors:n}}function ap(t){try{return JSON.stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function za(t,e){return `provider returned incomplete usage (input=${t??"absent"}, output=${e??"ab\
|
|
511
|
+
sent"}); cannot measure cost.`}async function qa(t){try{return (await t.text()).slice(0,500)}catch{return "<no body>"}}function cp(t){try{let e=new URL(t);return e.protocol==="https:"&&e.hostname.toLowerCase()===
|
|
512
|
+
"api.anthropic.com"?"anthropic":null}catch{return null}}var sn=class{events=[];start;now;constructor(e=()=>Date.now()){this.now=e,this.start=e();}record(e,n,r){this.events.push({stage:e,outcome:n,...r?{detail:r}:{},atMs:this.now()-this.start});}elapsed(){return this.
|
|
513
|
+
now()-this.start}all(){return this.events}};var Je=class extends Error{status;constructor(e,n){super(e),this.name="LicenseError",n&&(this.status=n);}};function Yo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function ir(t,e=""){if(typeof t!="number"){let n=e&&
|
|
514
|
+
`"${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 we(t,e,n=""){
|
|
515
|
+
let r=Yo(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`,u=s+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(u):
|
|
516
|
+
new TypeError(u)}return t}function Zo(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 Ua(t,e){we(t,void 0,"digestInt\
|
|
517
|
+
o() output");let n=e.outputLen;if(t.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function an(...t){for(let e=0;e<t.length;e++)t[e].fill(0);}function sr(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Ha=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",up=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ar(t){if(we(t),Ha)return t.toHex();
|
|
518
|
+
let e="";for(let n=0;n<t.length;n++)e+=up[t[n]];return e}var Ae={_0:48,_9:57,A:65,F:70,a:97,f:102};function Va(t){if(t>=Ae._0&&t<=Ae._9)return t-Ae._0;if(t>=Ae.A&&t<=Ae.F)return t-(Ae.A-10);if(t>=Ae.a&&
|
|
519
|
+
t<=Ae.f)return t-(Ae.a-10)}function cn(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Ha)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?
|
|
520
|
+
new RangeError(o.message):o}let e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=Va(t.charCodeAt(
|
|
521
|
+
i)),a=Va(t.charCodeAt(i+1));if(s===void 0||a===void 0){let c=t[i]+t[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a;}return r}function Qo(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];we(o),e+=o.length;}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let i=t[r];n.set(i,o),o+=i.length;}return n}function Wa(t,e={}){let n=(o,i)=>t(i).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function Ja(t=32){
|
|
522
|
+
ir(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(
|
|
523
|
+
`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var Ka=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var cr=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(e,n,r,o){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=
|
|
524
|
+
new Uint8Array(e),this.view=sr(this.buffer);}update(e){Zo(this),we(e);let{view:n,buffer:r,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=sr(e);for(;o<=i-s;s+=
|
|
525
|
+
o)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0);}return this.length+=e.length,this.roundClean(),this}digestInto(e){Zo(this),
|
|
526
|
+
Ua(e,this),this.finished=true;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,an(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let d=s;d<o;d++)n[d]=0;r.setBigUint64(
|
|
527
|
+
o-8,BigInt(this.length*8),i),this.process(r,0);let a=sr(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_s\
|
|
528
|
+
ha2: outputLen bigger than state");for(let d=0;d<u;d++)a.setUint32(4*d,l[d],i);}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||=new this.
|
|
529
|
+
constructor,e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};var oe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var ur=BigInt(4294967295),Ga=BigInt(32);function lp(t,e=false){return e?{h:Number(t&ur),l:Number(t>>Ga&ur)}:{h:Number(t>>Ga&ur)|0,l:Number(t&ur)|0}}function Ya(t,e=false){let n=t.length,r=new Uint32Array(n),
|
|
530
|
+
o=new Uint32Array(n);for(let i=0;i<n;i++){let{h:s,l:a}=lp(t[i],e);[r[i],o[i]]=[s,a];}return [r,o]}var Xo=(t,e,n)=>t>>>n,ei=(t,e,n)=>t<<32-n|e>>>n,at=(t,e,n)=>t>>>n|e<<32-n,ct=(t,e,n)=>t<<32-n|e>>>n,un=(t,e,n)=>t<<64-n|e>>>n-32,ln=(t,e,n)=>t>>>n-32|e<<64-n;function Ce(t,e,n,r){let o=(e>>>0)+(r>>>0);return {h:t+n+(o/2**32|0)|0,l:o|0}}var Za=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Qa=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Xa=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),ec=(t,e,n,r,o)=>e+
|
|
531
|
+
n+r+o+(t/2**32|0)|0,tc=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),nc=(t,e,n,r,o,i)=>e+n+r+o+i+(t/2**32|0)|0;var rc=Ya(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242",
|
|
415
532
|
"0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc6\
|
|
416
533
|
8b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","\
|
|
417
534
|
0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3\
|
|
@@ -419,158 +536,158 @@ c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a6
|
|
|
419
536
|
x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5d\
|
|
420
537
|
efb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0x\
|
|
421
538
|
eada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c1\
|
|
422
|
-
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),
|
|
423
|
-
super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:
|
|
424
|
-
e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=
|
|
425
|
-
16;
|
|
426
|
-
|
|
427
|
-
Gh:
|
|
428
|
-
|
|
429
|
-
let A
|
|
430
|
-
0),{h:d,l:
|
|
431
|
-
|
|
432
|
-
0;Dh=
|
|
433
|
-
xpected boolean, got type="+typeof t)}return t}function
|
|
434
|
-
"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
|
|
435
|
-
function
|
|
436
|
-
return
|
|
437
|
-
"expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function
|
|
438
|
-
`param "${i}" is invalid: expected own property`);let
|
|
439
|
-
entries(i).forEach(([a,
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
"invert: does not exist");return
|
|
443
|
-
e),o}function
|
|
444
|
-
e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+
|
|
445
|
-
eql(
|
|
446
|
-
1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return
|
|
447
|
-
"Cannot find square root");let d=n,
|
|
448
|
-
"Cannot find square root");let
|
|
449
|
-
t,e)&
|
|
450
|
-
reduce((r,o)=>(r[o]="function",r),e);if(
|
|
451
|
-
id field: expected ORDER > 1, got "+t.ORDER);return t}function
|
|
452
|
-
for(;n>
|
|
453
|
-
reduceRight((a,u
|
|
454
|
-
let n=
|
|
455
|
-
|
|
539
|
+
00d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),pp=rc[0],fp=rc[1],Ke=new Uint32Array(80),Ge=new Uint32Array(80),ti=class extends cr{constructor(e){
|
|
540
|
+
super(128,e,16,false);}get(){let{Ah:e,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:u,El:l,Fh:d,Fl:m,Gh:f,Gl:h,Hh:g,Hl:p}=this;return [e,n,r,o,i,s,a,c,u,l,d,m,f,h,g,p]}set(e,n,r,o,i,s,a,c,u,l,d,m,f,h,g,p){this.Ah=
|
|
541
|
+
e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=d|0,this.Fl=m|0,this.Gh=f|0,this.Gl=h|0,this.Hh=g|0,this.Hl=p|0;}process(e,n){for(let v=0;v<
|
|
542
|
+
16;v++,n+=4)Ke[v]=e.getUint32(n),Ge[v]=e.getUint32(n+=4);for(let v=16;v<80;v++){let w=Ke[v-15]|0,S=Ge[v-15]|0,k=at(w,S,1)^at(w,S,8)^Xo(w,S,7),x=ct(w,S,1)^ct(w,S,8)^ei(w,S,7),E=Ke[v-2]|0,C=Ge[v-2]|0,M=at(
|
|
543
|
+
E,C,19)^un(E,C,61)^Xo(E,C,6),O=ct(E,C,19)^ln(E,C,61)^ei(E,C,6),T=Xa(x,O,Ge[v-7],Ge[v-16]),R=ec(T,k,M,Ke[v-7],Ke[v-16]);Ke[v]=R|0,Ge[v]=T|0;}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:u,Dl:l,Eh:d,El:m,Fh:f,Fl:h,
|
|
544
|
+
Gh:g,Gl:p,Hh:y,Hl:b}=this;for(let v=0;v<80;v++){let w=at(d,m,14)^at(d,m,18)^un(d,m,41),S=ct(d,m,14)^ct(d,m,18)^ln(d,m,41),k=d&f^~d&g,x=m&h^~m&p,E=tc(b,S,x,fp[v],Ge[v]),C=nc(E,y,w,k,pp[v],Ke[v]),M=E|0,
|
|
545
|
+
O=at(r,o,28)^un(r,o,34)^un(r,o,39),T=ct(r,o,28)^ln(r,o,34)^ln(r,o,39),R=r&i^r&a^i&a,I=o&s^o&c^s&c;y=g|0,b=p|0,g=f|0,p=h|0,f=d|0,h=m|0,{h:d,l:m}=Ce(u|0,l|0,C|0,M|0),u=a|0,l=c|0,a=i|0,c=s|0,i=r|0,s=o|0;
|
|
546
|
+
let A=Za(M,T,I);r=Qa(A,C,O,R),o=A|0;}(({h:r,l:o}=Ce(this.Ah|0,this.Al|0,r|0,o|0))),{h:i,l:s}=Ce(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Ce(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Ce(this.Dh|0,this.Dl|0,u|0,l|
|
|
547
|
+
0),{h:d,l:m}=Ce(this.Eh|0,this.El|0,d|0,m|0),{h:f,l:h}=Ce(this.Fh|0,this.Fl|0,f|0,h|0),{h:g,l:p}=Ce(this.Gh|0,this.Gl|0,g|0,p|0),{h:y,l:b}=Ce(this.Hh|0,this.Hl|0,y|0,b|0),this.set(r,o,i,s,a,c,u,l,d,m,
|
|
548
|
+
f,h,g,p,y,b);}roundClean(){an(Ke,Ge);}destroy(){this.destroyed=true,an(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);}},ni=class extends ti{Ah=oe[0]|0;Al=oe[1]|0;Bh=oe[2]|0;Bl=oe[3]|0;Ch=oe[4]|0;Cl=oe[5]|
|
|
549
|
+
0;Dh=oe[6]|0;Dl=oe[7]|0;Eh=oe[8]|0;El=oe[9]|0;Fh=oe[10]|0;Fl=oe[11]|0;Gh=oe[12]|0;Gl=oe[13]|0;Hh=oe[14]|0;Hl=oe[15]|0;constructor(){super(64);}};var lr=Wa(()=>new ni,Ka(3));var K=(t,e,n)=>we(t,e,n),oi=ir,ii=ar,Ee=(...t)=>Qo(...t),oc=t=>cn(t),fr=Yo,ic=t=>Ja(t),pr=BigInt(0),ri=BigInt(1);function Rt(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new TypeError(n+"e\
|
|
550
|
+
xpected boolean, got type="+typeof t)}return t}function mp(t){if(typeof t=="bigint"){if(!dr(t))throw new RangeError("positive bigint expected, got "+t)}else oi(t);return t}function Oe(t,e=""){if(typeof t!=
|
|
551
|
+
"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 sc(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?pr:BigInt("0x"+t)}function si(t){return sc(ar(t))}function Me(t){return sc(ar(dn(we(t)).reverse()))}
|
|
552
|
+
function ai(t,e){if(ir(e),e===0)throw new RangeError("zero length");t=mp(t);let n=t.toString(16);if(n.length>e*2)throw new RangeError("number too large");return cn(n.padStart(e*2,"0"))}function ac(t,e){
|
|
553
|
+
return ai(t,e).reverse()}function cc(t,e){if(t=K(t),e=K(e),t.length!==e.length)return false;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function dn(t){return Uint8Array.from(K(t))}var dr=t=>typeof t=="bigint"&&pr<=t;function hp(t,e,n){return dr(t)&&dr(e)&&dr(n)&&e<=t&&t<n}function ci(t,e,n,r){if(!hp(e,n,r))throw new RangeError(
|
|
554
|
+
"expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function ui(t){if(t<pr)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>pr;t>>=ri,e+=1);return e}var uc=t=>(ri<<BigInt(t))-ri;function ut(t,e={},n={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function r(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(t,i))throw new TypeError(
|
|
555
|
+
`param "${i}" is invalid: expected own property`);let c=t[i];if(a&&c===void 0)return;let u=typeof c;if(u!==s||c===null)throw new TypeError(`param "${i}" is invalid: expected ${s}, got ${u}`)}let o=(i,s)=>Object.
|
|
556
|
+
entries(i).forEach(([a,c])=>r(a,c,s));o(e,false),o(n,true);}var li=()=>{throw new Error("not implemented")};var ie=BigInt(0),Z=BigInt(1),lt=BigInt(2),fc=BigInt(3),mc=BigInt(4),hc=BigInt(5),gp=BigInt(7),gc=BigInt(8),bp=BigInt(9),bc=BigInt(16);function J(t,e){if(e<=ie)throw new Error("mod: expected positive m\
|
|
557
|
+
odulus, got "+e);let n=t%e;return n>=ie?n:e+n}function Se(t,e,n){if(e<ie)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >ie;)r*=r,r%=n;return r}function lc(t,e){if(t===ie)throw new Error("invert: expected non-zer\
|
|
558
|
+
o number");if(e<=ie)throw new Error("invert: expected positive modulus, got "+e);let n=J(t,e),r=e,o=ie,s=Z;for(;n!==ie;){let u=r/n,l=r-n*u,d=o-s*u;r=n,n=l,o=s,s=d;}if(r!==Z)throw new Error(
|
|
559
|
+
"invert: does not exist");return J(o,e)}function di(t,e,n){let r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function vc(t,e){let n=t,r=(n.ORDER+Z)/mc,o=n.pow(e,r);return di(n,o,
|
|
560
|
+
e),o}function vp(t,e){let n=t,r=(n.ORDER-hc)/gc,o=n.mul(e,lt),i=n.pow(o,r),s=n.mul(e,i),a=n.mul(n.mul(s,lt),i),c=n.mul(s,n.sub(a,n.ONE));return di(n,c,e),c}function yp(t){let e=br(t),n=yc(t),r=n(e,e.neg(
|
|
561
|
+
e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+gp)/bc;return((a,c)=>{let u=a,l=u.pow(c,s),d=u.mul(l,r),m=u.mul(l,o),f=u.mul(l,i),h=u.eql(u.sqr(d),c),g=u.eql(u.sqr(m),c);l=u.cmov(l,d,h),d=u.cmov(f,m,g);let p=u.
|
|
562
|
+
eql(u.sqr(d),c),y=u.cmov(l,d,p);return di(u,y,c),y})}function yc(t){if(t<fc)throw new Error("sqrt is not defined for small field");let e=t-Z,n=0;for(;e%lt===ie;)e/=lt,n++;let r=lt,o=br(t);for(;dc(o,r)===
|
|
563
|
+
1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return vc;let i=o.pow(r,e),s=(e+Z)/lt;return function(c,u){let l=c;if(l.is0(u))return u;if(dc(l,u)!==1)throw new Error(
|
|
564
|
+
"Cannot find square root");let d=n,m=l.mul(l.ONE,i),f=l.pow(u,e),h=l.pow(u,s);for(;!l.eql(f,l.ONE);){if(l.is0(f))return l.ZERO;let g=1,p=l.sqr(f);for(;!l.eql(p,l.ONE);)if(g++,p=l.sqr(p),g===d)throw new Error(
|
|
565
|
+
"Cannot find square root");let y=Z<<BigInt(d-g-1),b=l.pow(m,y);d=g,m=l.sqr(b),f=l.mul(f,m),h=l.mul(h,b);}return h}}function kp(t){return t%mc===fc?vc:t%gc===hc?vp:t%bc===bp?yp(t):yc(t)}var Le=(t,e)=>(J(
|
|
566
|
+
t,e)&Z)===Z,xp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function kc(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=xp.
|
|
567
|
+
reduce((r,o)=>(r[o]="function",r),e);if(ut(t,n),Oe(t.BYTES,"BYTES"),Oe(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=Z)throw new Error("inval\
|
|
568
|
+
id field: expected ORDER > 1, got "+t.ORDER);return t}function wp(t,e,n){let r=t;if(n<ie)throw new Error("invalid exponent, negatives unsupported");if(n===ie)return r.ONE;if(n===Z)return e;let o=r.ONE,
|
|
569
|
+
i=e;for(;n>ie;)n&Z&&(o=r.mul(o,i)),i=r.sqr(i),n>>=Z;return o}function gr(t,e,n=false){let r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),i=e.reduce((a,c,u)=>r.is0(c)?a:(o[u]=a,r.mul(a,c)),r.ONE),s=r.inv(
|
|
570
|
+
i);return e.reduceRight((a,c,u)=>r.is0(c)?a:(o[u]=r.mul(a,o[u]),r.mul(a,c)),s),o}function dc(t,e){let n=t,r=(n.ORDER-Z)/lt,o=n.pow(e,r),i=n.eql(o,n.ONE),s=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Sp(t,e){if(e!==void 0&&oi(e),t<=ie)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);
|
|
571
|
+
let n=ui(t);if(e!==void 0&&e<n)throw new Error(`invalid n length: expected bit length (${n}) >= n.length (${e})`);let r=e!==void 0?e:n,o=Math.ceil(r/8);return {nBitLength:r,nByteLength:o}}var pc=new WeakMap,
|
|
572
|
+
hr=class{ORDER;BITS;BYTES;isLE;ZERO=ie;ONE=Z;_lengths;_mod;constructor(e,n={}){if(e<=Z)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=false,n!=null&&typeof n=="object"&&(typeof n.
|
|
456
573
|
BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:true}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.
|
|
457
|
-
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=
|
|
458
|
-
048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,Object.freeze(this);}create(e){return
|
|
459
|
-
"+typeof e);return
|
|
460
|
-
e*e,this.ORDER)}add(e,n){return
|
|
461
|
-
return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return
|
|
462
|
-
isLE?
|
|
463
|
-
: expected "+r+" bytes, got "+e.length);let
|
|
464
|
-
|
|
465
|
-
freeze(
|
|
466
|
-
throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function
|
|
467
|
-
shiftBy:s}}function
|
|
468
|
-
isNeg:
|
|
469
|
-
e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>
|
|
470
|
-
s=e,a=s;for(let
|
|
471
|
-
s=
|
|
472
|
-
ZERO){let i=
|
|
473
|
-
get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),
|
|
474
|
-
e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){
|
|
475
|
-
ds"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let
|
|
476
|
-
let o=
|
|
477
|
-
freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function
|
|
478
|
-
let n=e,r=
|
|
479
|
-
sqrt(o.div(
|
|
480
|
-
|
|
481
|
-
this.X=d("x",p),this.Y=d("y",
|
|
482
|
-
x:
|
|
483
|
-
o.ORDER;
|
|
484
|
-
"bad point: x=0 and x_0=1");return A!==
|
|
485
|
-
return h.createCache(this,p),
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
let{a:p}=s,{X:
|
|
489
|
-
Y:
|
|
490
|
-
this.add(p.negate())}multiply(p){if(!i.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:
|
|
491
|
-
if(!i.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===
|
|
492
|
-
return h.unsafe(this,s.n).is0()}toAffine(p){let
|
|
493
|
-
was invalid");return {x
|
|
494
|
-
return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let h=new
|
|
495
|
-
this.ep=e;}static fromBytes(e){
|
|
496
|
-
return this.ep.toAffine(e)}toHex(){return
|
|
574
|
+
freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=Sp(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2\
|
|
575
|
+
048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,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\
|
|
576
|
+
"+typeof e);return ie<=e&&e<this.ORDER}is0(e){return e===ie}isValidNot0(e){return !this.is0(e)&&this.isValid(e)}isOdd(e){return (e&Z)===Z}neg(e){return J(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return J(
|
|
577
|
+
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 wp(this,e,n)}div(e,n){return J(e*lc(n,this.ORDER),this.ORDER)}sqrN(e){
|
|
578
|
+
return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return lc(e,this.ORDER)}sqrt(e){let n=pc.get(this);return n||pc.set(this,n=kp(this.ORDER)),n(this,e)}toBytes(e){return this.
|
|
579
|
+
isLE?ac(e,this.BYTES):ai(e,this.BYTES)}fromBytes(e,n=false){K(e);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes\
|
|
580
|
+
: expected "+r+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,i?0:u.length-e.length),e=u;}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?Me(e):
|
|
581
|
+
si(e);if(a&&(c=J(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return gr(this,e)}cmov(e,n,r){return Rt(r,"condition"),r?n:e}};Object.
|
|
582
|
+
freeze(hr.prototype);function br(t,e={}){return new hr(t,e)}var vr=BigInt(0),hi=BigInt(1);function xc(t,e){let n=e.negate();return t?n:e}function kr(t,e){let n=gr(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function Pc(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)
|
|
583
|
+
throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function pi(t,e){Pc(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=uc(t),s=BigInt(t);return {windows:n,windowSize:r,mask:i,maxNumber:o,
|
|
584
|
+
shiftBy:s}}function wc(t,e,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(t&o),c=t>>s;a>r&&(a-=i,c+=hi);let u=e*r,l=u+Math.abs(a)-1,d=a===0,m=a<0,f=e%2!==0;return {nextN:c,offset:l,isZero:d,
|
|
585
|
+
isNeg:m,isNegF:f,offsetF:u}}var fi=new WeakMap,Cc=new WeakMap;function mi(t){return Cc.get(t)||1}function Sc(t){if(t!==vr)throw new Error("invalid wNAF")}var yr=class{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=
|
|
586
|
+
e.ZERO,this.Fn=e.Fn,this.bits=n;}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>vr;)n&hi&&(r=r.add(o)),o=o.double(),n>>=hi;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=pi(n,this.bits),i=[],
|
|
587
|
+
s=e,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let u=1;u<o;u++)a=a.add(s),i.push(a);s=a.double();}return i}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,
|
|
588
|
+
s=pi(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:m,offsetF:f}=wc(r,a,s);r=c,l?i=i.add(xc(m,n[f])):o=o.add(xc(d,n[u]));}return Sc(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.
|
|
589
|
+
ZERO){let i=pi(e,this.bits);for(let s=0;s<i.windows&&r!==vr;s++){let{nextN:a,offset:c,isZero:u,isNeg:l}=wc(r,s,i);if(r=a,!u){let d=n[c];o=o.add(l?d.negate():d);}}return Sc(r),o}getPrecomputes(e,n,r){let o=fi.
|
|
590
|
+
get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),fi.set(n,o))),o}cached(e,n,r){let o=mi(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=mi(
|
|
591
|
+
e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){Pc(n,this.bits),Cc.set(e,n),fi.delete(e);}hasCache(e){return mi(e)!==1}};function Tc(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return kc(e),e}else return br(t,{isLE:n})}function Ec(t,e,n={},r){if(r===void 0&&(r=t==="edwar\
|
|
592
|
+
ds"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of ["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>vr))throw new Error(`CURVE.${c} must be positive bigint`)}
|
|
593
|
+
let o=Tc(e.p,n.Fp,r),i=Tc(e.n,n.Fn,r),a=["Gx","Gy","a","d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.
|
|
594
|
+
freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function Rc(t,e){return function(r){let o=t(r);return {secretKey:o,publicKey:e(o)}}}var Ye=BigInt(0),Q=BigInt(1),gi=BigInt(2),Tp=BigInt(8);function Pp(t,e,n,r){let o=t.sqr(n),i=t.sqr(r),s=t.add(t.mul(e.a,o),i),a=t.add(t.ONE,t.mul(e.d,t.mul(o,i)));return t.eql(s,a)}function Ic(t,e={}){
|
|
595
|
+
let n=e,r=Ec("edwards",t,n,n.FpFnLE),{Fp:o,Fn:i}=r,s=r.CURVE,{h:a}=s;ut(n,{},{uvRatio:"function"});let c=gi<<BigInt(i.BYTES*8)-Q,u=g=>o.create(g),l=n.uvRatio===void 0?(g,p)=>{try{return {isValid:!0,value:o.
|
|
596
|
+
sqrt(o.div(g,p))}}catch{return {isValid:false,value:Ye}}}:n.uvRatio;if(!Pp(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(g,p,y=false){let b=y?Q:Ye;return ci("coordinate "+g,p,
|
|
597
|
+
b,c),p}function m(g){if(!(g instanceof f))throw new Error("EdwardsPoint expected")}class f{static BASE=new f(s.Gx,s.Gy,Q,u(s.Gx*s.Gy));static ZERO=new f(Ye,Q,Q,Ye);static Fp=o;static Fn=i;X;Y;Z;T;constructor(p,y,b,v){
|
|
598
|
+
this.X=d("x",p),this.Y=d("y",y),this.Z=d("z",b,true),this.T=d("t",v),Object.freeze(this);}static CURVE(){return s}static fromAffine(p){if(p instanceof f)throw new Error("extended point not allowed");let{
|
|
599
|
+
x:y,y:b}=p||{};return d("x",y),d("y",b),new f(y,b,Q,u(y*b))}static fromBytes(p,y=false){let b=o.BYTES,{a:v,d:w}=s;p=dn(K(p,b,"point")),Rt(y,"zip215");let S=dn(p),k=p[b-1];S[b-1]=k&-129;let x=Me(S),E=y?c:
|
|
600
|
+
o.ORDER;ci("point.y",x,Ye,E);let C=u(x*x),M=u(C-Q),O=u(w*C-v),{isValid:T,value:R}=l(M,O);if(!T)throw new Error("bad point: invalid y coordinate");let I=(R&Q)===Q,A=(k&128)!==0;if(!y&&R===Ye&&A)throw new Error(
|
|
601
|
+
"bad point: x=0 and x_0=1");return A!==I&&(R=u(-R)),f.fromAffine({x:R,y:x})}static fromHex(p,y=false){return f.fromBytes(oc(p),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,y=true){
|
|
602
|
+
return h.createCache(this,p),y||this.multiply(gi),this}assertValidity(){let p=this,{a:y,d:b}=s;if(p.is0())throw new Error("bad point: ZERO");let{X:v,Y:w,Z:S,T:k}=p,x=u(v*v),E=u(w*w),C=u(S*S),M=u(C*C),
|
|
603
|
+
O=u(x*y),T=u(C*u(O+E)),R=u(M+u(b*u(x*E)));if(T!==R)throw new Error("bad point: equation left != right (1)");let I=u(v*w),A=u(S*k);if(I!==A)throw new Error("bad point: equation left != right (2)")}equals(p){
|
|
604
|
+
m(p);let{X:y,Y:b,Z:v}=this,{X:w,Y:S,Z:k}=p,x=u(y*k),E=u(w*v),C=u(b*k),M=u(S*v);return x===E&&C===M}is0(){return this.equals(f.ZERO)}negate(){return new f(u(-this.X),this.Y,this.Z,u(-this.T))}double(){
|
|
605
|
+
let{a:p}=s,{X:y,Y:b,Z:v}=this,w=u(y*y),S=u(b*b),k=u(gi*u(v*v)),x=u(p*w),E=y+b,C=u(u(E*E)-w-S),M=x+S,O=M-k,T=x-S,R=u(C*O),I=u(M*T),A=u(C*T),j=u(O*M);return new f(R,I,j,A)}add(p){m(p);let{a:y,d:b}=s,{X:v,
|
|
606
|
+
Y:w,Z:S,T:k}=this,{X:x,Y:E,Z:C,T:M}=p,O=u(v*x),T=u(w*E),R=u(k*b*M),I=u(S*C),A=u((v+w)*(x+E)-O-T),j=I-R,B=I+R,L=u(T-y*O),F=u(A*j),U=u(B*L),V=u(A*L),X=u(j*B);return new f(F,U,X,V)}subtract(p){return m(p),
|
|
607
|
+
this.add(p.negate())}multiply(p){if(!i.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:b}=h.cached(this,p,v=>kr(f,v));return kr(f,[y,b])[0]}multiplyUnsafe(p){
|
|
608
|
+
if(!i.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===Ye?f.ZERO:this.is0()||p===Q?this:h.unsafe(this,p,y=>kr(f,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){
|
|
609
|
+
return h.unsafe(this,s.n).is0()}toAffine(p){let y=this,b=p,{X:v,Y:w,Z:S}=y,k=y.is0();b==null&&(b=k?Tp:o.inv(S));let x=u(v*b),E=u(w*b),C=o.mul(S,b);if(k)return {x:Ye,y:Q};if(C!==Q)throw new Error("invZ \
|
|
610
|
+
was invalid");return {x,y:E}}clearCofactor(){return a===Q?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y}=this.toAffine(),b=o.toBytes(y);return b[b.length-1]|=p&Q?128:0,b}toHex(){return ii(this.toBytes())}toString(){
|
|
611
|
+
return `<Point ${this.is0()?"ZERO":this.toHex()}>`}}let h=new yr(f,i.BITS);return i.BITS>=8&&f.BASE.precompute(8),Object.freeze(f.prototype),Object.freeze(f),f}var xr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){
|
|
612
|
+
this.ep=e;}static fromBytes(e){li();}static fromHex(e){li();}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity();}toAffine(e){
|
|
613
|
+
return this.ep.toAffine(e)}toHex(){return ii(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){
|
|
497
614
|
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.
|
|
498
|
-
ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function
|
|
499
|
-
equired');let r=e,o=n;
|
|
500
|
-
outputLen,l=2*a.BYTES;if(
|
|
501
|
-
|
|
502
|
-
let
|
|
503
|
-
|
|
504
|
-
"context"),!!i)))}function
|
|
505
|
-
if(!
|
|
506
|
-
!!
|
|
507
|
-
|
|
508
|
-
is0()}let
|
|
509
|
-
try{return !!t.fromBytes(
|
|
510
|
-
A=
|
|
511
|
-
|
|
615
|
+
ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,n){return this.ep.precompute(e,n),this}};function Dc(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is r\
|
|
616
|
+
equired');let r=e,o=n;ut(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=t,u=r.
|
|
617
|
+
outputLen,l=2*a.BYTES;if(u!==void 0&&(Oe(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let d=o.randomBytes===void 0?ic:o.randomBytes,m=o.adjustScalarBytes===void 0?
|
|
618
|
+
T=>T:o.adjustScalarBytes,f=o.domain===void 0?(T,R,I)=>{if(Rt(I,"phflag"),R.length||I)throw new Error("Contexts/pre-hash are not supported");return T}:o.domain;function h(T){return c.create(Me(T))}function g(T){
|
|
619
|
+
let R=x.secretKey;K(T,x.secretKey,"secretKey");let I=K(r(T),2*R,"hashedSecretKey"),A=m(I.slice(0,R)),j=I.slice(R,2*R),B=h(A);return {head:A,prefix:j,scalar:B}}function p(T){let{head:R,prefix:I,scalar:A}=g(
|
|
620
|
+
T),j=s.multiply(A),B=j.toBytes();return {head:R,prefix:I,scalar:A,point:j,pointBytes:B}}function y(T){return p(T).pointBytes}function b(T=Uint8Array.of(),...R){let I=Ee(...R);return h(r(f(I,K(T,void 0,
|
|
621
|
+
"context"),!!i)))}function v(T,R,I={}){T=K(T,void 0,"message"),i&&(T=i(T));let{prefix:A,scalar:j,pointBytes:B}=p(R),L=b(I.context,A,T),F=s.multiply(L).toBytes(),U=b(I.context,F,B,T),V=c.create(L+U*j);
|
|
622
|
+
if(!c.isValid(V))throw new Error("sign failed: invalid s");let X=Ee(F,c.toBytes(V));return K(X,x.signature,"result")}let w={zip215:o.zip215};function S(T,R,I,A=w){let{context:j}=A,B=A.zip215===void 0?
|
|
623
|
+
!!w.zip215:A.zip215,L=x.signature;T=K(T,L,"signature"),R=K(R,void 0,"message"),I=K(I,x.publicKey,"publicKey"),B!==void 0&&Rt(B,"zip215"),i&&(R=i(R));let F=L/2,U=T.subarray(0,F),V=Me(T.subarray(F,L)),X,
|
|
624
|
+
de,D;try{X=t.fromBytes(I,B),de=t.fromBytes(U,B),D=s.multiplyUnsafe(V);}catch{return false}if(!B&&X.isSmallOrder())return false;let Tn=b(j,U,I,R);return de.add(X.multiplyUnsafe(Tn)).subtract(D).clearCofactor().
|
|
625
|
+
is0()}let k=a.BYTES,x={secretKey:k,publicKey:k,signature:2*k,seed:k};function E(T){return T=T===void 0?d(x.seed):T,K(T,x.seed,"seed")}function C(T){return fr(T)&&T.length===x.secretKey}function M(T,R){
|
|
626
|
+
try{return !!t.fromBytes(T,R===void 0?w.zip215:R)}catch{return false}}let O={getExtendedPublicKey:p,randomSecretKey:E,isValidSecretKey:C,isValidPublicKey:M,toMontgomery(T){let{y:R}=t.fromBytes(T),I=x.publicKey,
|
|
627
|
+
A=I===32;if(!A&&I!==57)throw new Error("only defined for 25519 and 448");let j=A?a.div(Q+R,Q-R):a.div(R-Q,R+Q);return a.toBytes(j)},toMontgomerySecret(T){let R=x.secretKey;K(T,R);let I=r(T.subarray(0,
|
|
628
|
+
R));return m(I).subarray(0,R)}};return Object.freeze(x),Object.freeze(O),Object.freeze({keygen:Rc(E,y),getPublicKey:y,sign:v,verify:S,utils:O,Point:t,lengths:x})}var Rp=BigInt(0),je=BigInt(1),Ac=BigInt(2);var Ip=BigInt(5),Dp=BigInt(8),It=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),xi={p:It,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Dp,
|
|
512
629
|
a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6d\
|
|
513
|
-
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function
|
|
514
|
-
i*t%i,
|
|
515
|
-
return t[0]&=248,t[31]&=127,t[31]|=64,t}var
|
|
516
|
-
s=
|
|
517
|
-
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var
|
|
518
|
-
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
|
|
519
|
-
|
|
520
|
-
oint expected")}init(e){return new t(e)}static fromBytes(e){
|
|
521
|
-
let a=i(s*s),
|
|
522
|
-
"invalid ristretto255 encoding 2");return new t(new
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
630
|
+
c5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function _p(t){let e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=It,a=t*t%
|
|
631
|
+
i*t%i,c=Se(a,Ac,i)*a%i,u=Se(c,je,i)*t%i,l=Se(u,Ip,i)*u%i,d=Se(l,e,i)*l%i,m=Se(d,n,i)*d%i,f=Se(m,r,i)*m%i,h=Se(f,o,i)*f%i,g=Se(h,o,i)*f%i,p=Se(g,e,i)*l%i;return {pow_p_5_8:Se(p,Ac,i)*t%i,b2:a}}function Ap(t){
|
|
632
|
+
return t[0]&=248,t[31]&=127,t[31]|=64,t}var vi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function wi(t,e){let n=It,r=J(e*e*e,n),o=J(r*r*e,n),i=_p(t*o).pow_p_5_8,
|
|
633
|
+
s=J(t*r*i,n),a=J(e*s*s,n),c=s,u=J(s*vi,n),l=a===t,d=a===J(-t,n),m=a===J(-t*vi,n);return l&&(s=c),(d||m)&&(s=u),Le(s,n)&&(s=J(-s,n)),{isValid:l||d,value:s}}var Qe=Ic(xi,{uvRatio:wi}),Ze=Qe.Fp,Lc=Qe.Fn;function Op(t){return Dc(Qe,lr,Object.assign({adjustScalarBytes:Ap,zip215:true},t))}var jc=Op({});var yi=vi;BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235");var Lp=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578");BigInt(
|
|
634
|
+
"1159843021668779879193775521855586647937357759715417654439879720876111806838");BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var Oc=t=>wi(je,t),$p=BigInt("0x7\
|
|
635
|
+
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),ki=t=>Ze.create(Me(t)&$p);var Xe=class t extends xr{static BASE=new t(
|
|
636
|
+
Qe.BASE);static ZERO=new t(Qe.ZERO);static Fp=Ze;static Fn=Lc;constructor(e){super(e);}static fromAffine(e){return new t(Qe.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoP\
|
|
637
|
+
oint expected")}init(e){return new t(e)}static fromBytes(e){we(e,32);let{a:n,d:r}=xi,o=It,i=w=>Ze.create(w),s=ki(e);if(!cc(Ze.toBytes(s),e)||Le(s,o))throw new Error("invalid ristretto255 encoding 1");
|
|
638
|
+
let a=i(s*s),c=i(je+n*a),u=i(je-n*a),l=i(c*c),d=i(u*u),m=i(n*r*l-d),{isValid:f,value:h}=Oc(i(m*d)),g=i(h*u),p=i(h*g*m),y=i((s+s)*g);Le(y,o)&&(y=i(-y));let b=i(c*p),v=i(y*b);if(!f||Le(v,o)||b===Rp)throw new Error(
|
|
639
|
+
"invalid ristretto255 encoding 2");return new t(new Qe(y,b,je,v))}static fromHex(e){return t.fromBytes(cn(e))}toBytes(){let{X:e,Y:n,Z:r,T:o}=this.ep,i=It,s=p=>Ze.create(p),a=s(s(r+n)*s(r-n)),c=s(e*n),
|
|
640
|
+
u=s(c*c),{value:l}=Oc(s(a*u)),d=s(l*a),m=s(l*c),f=s(d*m*o),h;if(Le(o*f,i)){let p=s(n*yi),y=s(e*yi);e=p,n=y,h=s(d*Lp);}else h=m;Le(e*f,i)&&(n=s(-n));let g=s((r-n)*h);return Le(g,i)&&(g=s(-g)),Ze.toBytes(
|
|
641
|
+
g)}equals(e){this.assertSame(e);let{X:n,Y:r}=this.ep,{X:o,Y:i}=e.ep,s=u=>Ze.create(u),a=s(n*i)===s(r*o),c=s(r*i)===s(n*o);return a||c}is0(){return this.equals(t.ZERO)}};Object.freeze(Xe.BASE);Object.freeze(
|
|
642
|
+
Xe.ZERO);Object.freeze(Xe.prototype);Object.freeze(Xe);var Nc=`-----BEGIN PUBLIC KEY-----
|
|
526
643
|
MCowBQYDK2VwAyEAWBiklf0kmDIVmM7nMiCxwiEAkwQIiqWGuRiRDJonsFY=
|
|
527
|
-
-----END PUBLIC KEY-----`;function
|
|
528
|
-
length%4?"=".repeat(4-e.length%4):"";return
|
|
529
|
-
function
|
|
530
|
-
function
|
|
531
|
-
oken"};let n=t.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(
|
|
532
|
-
d=e.keys[l];if(!d)return {ok:false,reason:`unknown key id "${l}"`};a=d;}else {if(!e)return {ok:false,reason:"no verification key"};a=e;}let
|
|
533
|
-
return {ok:false,reason:"invalid public key"}}let
|
|
534
|
-
{ok:false,reason:"bad signature"}}function
|
|
535
|
-
n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function
|
|
536
|
-
active":e<=r?"grace":"expired"}function
|
|
537
|
-
{reason:i.reason}:{}};let s=i.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),
|
|
538
|
-
if(o.header?.typ!==
|
|
644
|
+
-----END PUBLIC KEY-----`;function $c(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Si(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.
|
|
645
|
+
length%4?"=".repeat(4-e.length%4):"";return $c(e+n)}function Fp(t){let e=t.replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=$c(e);return n.subarray(n.length-32)}var zp=new TextEncoder,Bc=new TextDecoder;
|
|
646
|
+
function qp(t){return typeof t=="object"&&t!==null&&"keys"in t}function Dt(t){let e=t.trim(),n=/^(["'])([\s\S]*)\1$/.exec(e);return n&&(e=n[2].trim()),e=e.replace(/^bearer\s+/i,""),e.trim()}var Vp=/^[A-Za-z0-9_-]+$/;
|
|
647
|
+
function Fc(t){let e=t.split(".");return e.length===3&&e.every(n=>Vp.test(n))}function Ti(t){return t===""?"empty":Fc(t)?"token":"malformed"}function Pi(t,e){if(!Fc(t))return {ok:false,reason:"malformed t\
|
|
648
|
+
oken"};let n=t.split("."),r=n[0],o=n[1],i=n[2],s;try{s=JSON.parse(Bc.decode(Si(r)));}catch{return {ok:false,reason:"header is not valid JSON"}}let a;if(qp(e)){let l=typeof s.kid=="string"?s.kid:e.defaultKid,
|
|
649
|
+
d=e.keys[l];if(!d)return {ok:false,reason:`unknown key id "${l}"`};a=d;}else {if(!e)return {ok:false,reason:"no verification key"};a=e;}let c;try{if(c=Fp(a),c.length!==32)return {ok:!1,reason:"invalid public key"}}catch{
|
|
650
|
+
return {ok:false,reason:"invalid public key"}}let u=false;try{u=jc.verify(Si(i),zp.encode(`${r}.${o}`),c);}catch{return {ok:false,reason:"signature verification error"}}return u?{ok:true,header:s,payloadBytes:Si(o)}:
|
|
651
|
+
{ok:false,reason:"bad signature"}}function _t(t,e){let n=Pi(t,e);if(!n.ok||!n.payloadBytes)return {signatureValid:false,...n.reason?{reason:n.reason}:{}};try{return {signatureValid:!0,payload:JSON.parse(Bc.decode(
|
|
652
|
+
n.payloadBytes))}}catch{return {signatureValid:false,reason:"payload is not valid JSON"}}}function Ci(t,e,n){if(n?.has(t.jti))return "revoked";let r=t.expires_at+t.grace_days*86400;return e<=t.expires_at?"\
|
|
653
|
+
active":e<=r?"grace":"expired"}function Lb(t,e,n={}){let r=Dt(t);if(Ti(r)==="empty")return {status:"none",reason:"empty"};let i=_t(r,e);if(!i.signatureValid||!i.payload)return {status:"invalid",...i.reason?
|
|
654
|
+
{reason:i.reason}:{}};let s=i.payload,a=n.nowSeconds??Math.floor(Date.now()/1e3),c=Ci(s,a,n.revoked);return c==="revoked"?{status:c,payload:s,reason:"license revoked"}:{status:c,payload:s}}var zc="BVSALA-REVOC",Up=300,Hp=new TextDecoder;function qc(t,e,n={}){let r=u=>({ok:false,seq:-1,asOf:0,revoked:new Set,reason:u}),o=Pi(t,e);if(!o.ok||!o.payloadBytes)return r(o.reason??"bad signature");
|
|
655
|
+
if(o.header?.typ!==zc)return r(`unexpected token type "${String(o.header?.typ??"")}" (want ${zc})`);let i;try{i=JSON.parse(Hp.decode(o.payloadBytes));}catch{return r("payload is not valid JSON")}if(typeof i.
|
|
539
656
|
seq!="number"||typeof i.asOf!="number"||!Array.isArray(i.revoked))return r("malformed revocation payload");let s=n.minSeq??0;if(i.seq<s)return r(`stale/rolled-back list (seq ${i.seq} < ${s})`);let a=n.
|
|
540
|
-
nowSeconds??Math.floor(Date.now()/1e3),
|
|
657
|
+
nowSeconds??Math.floor(Date.now()/1e3),c=n.maxSkewSeconds??Up;return i.asOf>a+c?r(`asOf too far in the future (${i.asOf} > ${a+c})`):{ok:true,seq:i.seq,asOf:i.asOf,revoked:new Set(i.revoked)}}var At=class{_seq=-1;_asOf=0;_lastContactAt=0;set=new Set;get seq(){
|
|
541
658
|
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.
|
|
542
659
|
set}apply(e){if(e.seq<this._seq)return false;let n=this.set.size;for(let i of e.revoked)this.set.add(i);let r=this.set.size>n,o=e.seq>this._seq;return e.seq>this._seq&&(this._seq=e.seq),e.asOf>this._asOf&&
|
|
543
|
-
(this._asOf=e.asOf),r||o}};function
|
|
544
|
-
|
|
545
|
-
86400,h=Math.min(o,
|
|
546
|
-
|
|
660
|
+
(this._asOf=e.asOf),r||o}};function wr(t,e,n){let r=()=>Math.floor((n.now?n.now():Date.now())/1e3),o=n.startedAt??r(),i=Dt(t),s=Ti(i),a=s==="token"?_t(i,e):{signatureValid:false,reason:s},c=a.signatureValid?a.payload:void 0,u=new Set(
|
|
661
|
+
c?.features??[]),l=()=>{if(s==="empty")return "none";if(!c)return "invalid";let m=Ci(c,r(),n.revocation.snapshot());if(n.maxStalenessSeconds!=null&&(m==="active"||m==="grace")){let f=c.expires_at+c.grace_days*
|
|
662
|
+
86400,h=Math.min(o,f),g=Math.max(n.revocation.lastContactAt,h);if(r()-g>n.maxStalenessSeconds)return "stale"}return m},d=()=>{let m=l();return m==="active"||m==="grace"};return {isEntitled:m=>d()&&u.has(
|
|
663
|
+
m),isActive:()=>d(),status:l,reason:()=>c?void 0:a.reason,refreshAfter:()=>{if(c)return Math.min(c.expires_at,r()+86400)}}}function Vc(t,e,n){return wr(t,e,{revocation:new At,...n?{now:n}:{}})}var Ot={pollIntervalSeconds:900,floorSeconds:300,maxIntervalSeconds:3600,jitterRatio:.1,maxSkewSeconds:300,requestTimeoutMs:3e4},Uc=3,Wp=12;function Jp(t){let e=t.random??Math.random,n;if(t.consecutiveFailures>
|
|
547
664
|
0){let o=Math.pow(2,Math.min(t.consecutiveFailures,4));n=Math.min(t.maxIntervalSeconds,t.floorSeconds*o);}else {let o=t.refreshAfter!=null?t.refreshAfter-t.nowSeconds:t.pollIntervalSeconds,i=o<0?t.pollIntervalSeconds:
|
|
548
|
-
o;n=Math.min(t.pollIntervalSeconds,Math.max(t.floorSeconds,i));}let r=1+(e()*2-1)*t.jitterRatio;return Math.max(t.floorSeconds,n*r)}var
|
|
665
|
+
o;n=Math.min(t.pollIntervalSeconds,Math.max(t.floorSeconds,i));}let r=1+(e()*2-1)*t.jitterRatio;return Math.max(t.floorSeconds,n*r)}var Kp=10,Sr=class{constructor(e){this.opts=e;}opts;timer=null;controller=null;consecutiveFailures=0;stopped=false;started=false;warnedNoFetch=false;lastEtag=null;consecutive304=0;now(){
|
|
549
666
|
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();
|
|
550
667
|
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.
|
|
551
|
-
onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??
|
|
668
|
+
onEvent?.({type:"no-fetch"});return}let n=new AbortController;this.controller=n;let r=this.opts.requestTimeoutMs??Ot.requestTimeoutMs,o=setTimeout(()=>n.abort(),r);o.unref?.();let i={accept:"applicati\
|
|
552
669
|
on/json"};this.lastEtag&&(i["if-none-match"]=this.lastEtag);try{let s=await e(this.opts.url,{signal:n.signal,headers:i});if(s.status===304){this.consecutiveFailures=0,this.opts.snapshot.markContact(this.
|
|
553
|
-
now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=
|
|
554
|
-
ok)throw new Error(`revocations HTTP ${s.status}`);let a=s.headers.get("etag"),
|
|
555
|
-
publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??
|
|
670
|
+
now()),this.opts.onEvent?.({type:"unchanged",seq:this.opts.snapshot.seq}),this.consecutive304+=1,this.consecutive304>=Kp&&(this.consecutive304=0,this.lastEtag=null);return}if(this.consecutive304=0,!s.
|
|
671
|
+
ok)throw new Error(`revocations HTTP ${s.status}`);let a=s.headers.get("etag"),c=await s.json();if(!c.list)throw new Error("response missing `list`");this.consecutiveFailures=0;let u=qc(c.list,this.opts.
|
|
672
|
+
publicKeyPem,{minSeq:this.opts.snapshot.seq,nowSeconds:this.now(),maxSkewSeconds:this.opts.maxSkewSeconds??Ot.maxSkewSeconds});if(!u.ok){let d=u.reason??"rejected";this.opts.onEvent?.({type:"rejected",
|
|
556
673
|
reason:d}),this.avisar(`rechazada:${d}`,`[bv-sala] the revocation list does NOT verify (${d}). The last known-good list is kept, so revocations ALREADY known still apply, but new ones are not arriving\
|
|
557
|
-
. Check ${this.opts.url}.`);return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let l=this.opts.snapshot.apply(
|
|
558
|
-
snapshot().size}:{type:"unchanged",seq:
|
|
559
|
-
return !!(this.opts.silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||
|
|
560
|
-
if(n<
|
|
674
|
+
. Check ${this.opts.url}.`);return}a&&(this.lastEtag=a),this.opts.snapshot.markContact(this.now());let l=this.opts.snapshot.apply(u);this.opts.onEvent?.(l?{type:"applied",seq:u.seq,size:this.opts.snapshot.
|
|
675
|
+
snapshot().size}:{type:"unchanged",seq:u.seq});}catch(s){this.consecutiveFailures++,this.opts.onEvent?.({type:"error",error:s}),this.avisarFalloDeRed(s);}finally{clearTimeout(o),this.controller=null;}}callado(){
|
|
676
|
+
return !!(this.opts.silenceWarnings??this.opts.silenciarAvisos)}avisar(e,n){this.callado()||W(`poller:${this.opts.url}:${e}`,n);}avisarFalloDeRed(e){if(this.callado())return;let n=this.consecutiveFailures;
|
|
677
|
+
if(n<Uc||(n-Uc)%Wp!==0)return;let r=e instanceof Error?e.message:String(e);console.warn(`[bv-sala] could not reach the revocation server ${n} times in a row (${r}). The license KEEPS working and known\
|
|
561
678
|
revocations still apply, but NEW ones are not arriving. Check egress to ${this.opts.url}.`);}start(){this.started||this.stopped||(this.started=true,this.pollOnce().finally(()=>this.schedule()));}schedule(){
|
|
562
|
-
if(this.stopped)return;let e=
|
|
563
|
-
opts.pollIntervalSeconds??
|
|
679
|
+
if(this.stopped)return;let e=Jp({refreshAfter:this.opts.getRefreshAfter?.(),nowSeconds:this.now(),consecutiveFailures:this.consecutiveFailures,floorSeconds:this.opts.floorSeconds??Ot.floorSeconds,pollIntervalSeconds:this.
|
|
680
|
+
opts.pollIntervalSeconds??Ot.pollIntervalSeconds,maxIntervalSeconds:this.opts.maxIntervalSeconds??Ot.maxIntervalSeconds,jitterRatio:this.opts.jitterRatio??Ot.jitterRatio,...this.opts.random?{random:this.
|
|
564
681
|
opts.random}:{}});this.timer=setTimeout(()=>{this.pollOnce().finally(()=>this.schedule());},e*1e3),this.timer.unref?.();}stop(){this.stopped=true,this.timer&&(clearTimeout(this.timer),this.timer=null),this.
|
|
565
|
-
controller?.abort();}};var
|
|
682
|
+
controller?.abort();}};var fn=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=
|
|
566
683
|
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.
|
|
567
684
|
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.
|
|
568
685
|
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??
|
|
569
686
|
Math.ceil(this.maxBuffer/this.maxBatch)+4,r=0;for(let o=0;o<n&&this.buffer.length>0;o++){let i=this.buffer.length;if(await this.flush(),r=this.buffer.length>=i?r+1:0,r>=2)break}}async flush(){if(this.
|
|
570
687
|
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.
|
|
571
688
|
fetch;if(!e)return;let n=this.buffer.splice(0,this.maxBatch);try{let r=n.map(i=>this.toWire(i)),o=await e(this.options.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bear\
|
|
572
|
-
er ${this.options.serviceAccountKey}`,[
|
|
573
|
-
`the server responded ${o.status}`)):o.status===401||o.status===403?(
|
|
689
|
+
er ${this.options.serviceAccountKey}`,[Rn]:`${this.options.surface??"sdk"}/${De}`},body:JSON.stringify(r)});o.ok?this.fallosSeguidos=0:o.status>=500?(this.fallosSeguidos++,this.requeue(n),this.avisarDeFallo(
|
|
690
|
+
`the server responded ${o.status}`)):o.status===401||o.status===403?(W(`metering-auth-${o.status}`,`[bv-sala] usage reporting is being rejected with HTTP ${o.status} at ${this.options.url}. Check 'ser\
|
|
574
691
|
viceAccountKey' (rotated? revoked? from another organization?). Until it works, no usage is reported: the dashboard will say it sees no traffic and billable seats will show zero.`),this.options.onAuthError?.(
|
|
575
692
|
o.status)):(this.fallosSeguidos++,this.avisarDeFallo(o.status===404||o.status===405?`HTTP ${o.status}: the reporting URL looks wrong`:`the server rejected the batch with HTTP ${o.status}`));}catch(r){this.
|
|
576
693
|
fallosSeguidos++,this.requeue(n),this.avisarDeFallo(r instanceof Error?r.message:"network error");}}avisarDeFallo(e){if(this.options.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||
|
|
@@ -582,161 +699,194 @@ tokens.compressedInput,baselineOutputTokens:n.tokens.baselineOutput,actualOutput
|
|
|
582
699
|
eliminatedInputFloorCost!==void 0&&Number.isFinite(n.cost.eliminatedInputFloorCost)&&n.cost.eliminatedInputFloorCost>0&&n.tokens.eliminatedInput>0?{eliminatedInputFloorCost:n.cost.eliminatedInputFloorCost}:
|
|
583
700
|
{},baselineCost:n.cost.baselineEstimate,actualCost:n.cost.actual,netSavings:n.cost.netSavings,...n.cost.basis?{basis:n.cost.basis}:{},...n.cost.basis==="reference"&&n.cache.reference&&/^[A-Za-z0-9._:/-]{1,128}$/.
|
|
584
701
|
test(n.cache.reference.requestId)&&Number.isInteger(n.cache.reference.at)?{referenceRequestId:n.cache.reference.requestId,referenceAt:n.cache.reference.at}:{},...n.attribution?.sessionId?{sessionId:n.
|
|
585
|
-
attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function
|
|
586
|
-
]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function
|
|
587
|
-
t.NETLIFY)}async function
|
|
588
|
-
if(t.KUBERNETES_SERVICE_HOST||
|
|
589
|
-
t.arch,t.execPath,n,e.USER??e.USERNAME??e.LOGNAME,e.HOME??e.USERPROFILE].filter(o=>typeof o=="string"&&o.length>0);return r.length?r.join("|"):void 0}var
|
|
590
|
-
ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function
|
|
591
|
-
return false;for(let e of
|
|
592
|
-
r.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",s,r.encode(e));return [...new Uint8Array(a)].map(
|
|
593
|
-
|${e}`;for(let s=0;s<i.length;s++)o^=i.charCodeAt(s),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function
|
|
594
|
-
if(!r)return;let o=await
|
|
595
|
-
new
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
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.
|
|
599
|
-
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??
|
|
600
|
-
pd);n.unref?.();try{let o=await(this.opts.fetchImpl??globalThis.fetch.bind(globalThis))(this.opts.url,{signal:e.signal,headers:{authorization:`Bearer ${this.opts.serviceAccountKey}`,accept:"applicatio\
|
|
601
|
-
n/json"}});if(!o.ok)return (o.status===401||o.status===403||o.status===404)&&!this.avisadoDeCredencial&&(this.avisadoDeCredencial=!0,console.warn(`[bv-sala] automatic pickup of the renewed license is f\
|
|
602
|
-
ailing with HTTP ${o.status} at ${this.opts.url}. Check 'serviceAccountKey' (rotated? from another organization?) and 'licenseServerUrl': until this works, the token will NOT renew itself and the SDK \
|
|
603
|
-
will stop operating when the grace period ends.`)),!1;let i=await o.json();if(typeof i.token!="string")return !1;let s=kt(i.token),a=xt(s,this.opts.publicKey);return !a.signatureValid||!a.payload||a.payload.
|
|
604
|
-
expires_at<=this.currentExpiresAt||this.currentOrg&&a.payload.org_id!==this.currentOrg||this.opts.revocados?.snapshot().has(a.payload.jti)||this.parado?!1:(this.currentExpiresAt=a.payload.expires_at,this.
|
|
605
|
-
currentOrg=a.payload.org_id,this.opts.onNewToken(s),!0)}catch{return false}finally{clearTimeout(n),this.controller===e&&(this.controller=null),this.enVuelo=false;}}};var fd={"gpt-4.1":false,"gpt-4.1-mini":false,"gpt-4.1-nano":false,"gpt-4o":false,"gpt-4o-mini":false,"gpt-4-turbo":false,"gpt-4":false,"gpt-3.5-turbo":false,"gpt-5":true,"gpt-5-codex":true,"gpt-5-mini":true,"gpt-5-nano":true,"gpt-5.\
|
|
702
|
+
attribution.sessionId}:{},...n.attribution?.agentId?{agentId:n.attribution.agentId}:{}}}};function Tr(){return globalThis.process}function Gp(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\
|
|
703
|
+
]";return new RegExp(`-${e}{8,10}-${e}{5}$`).test(t)}function Yp(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??
|
|
704
|
+
t.NETLIFY)}async function Zp(){if(Tr()?.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 Qp(t,e=Zp){
|
|
705
|
+
if(t.KUBERNETES_SERVICE_HOST||Yp(t))return;let n=t.HOSTNAME??t.COMPUTERNAME??await e();if(!(!n||Gp(n)))return n}async function Xp(){let t=Tr();if(!t||!t.env)return;let e=t.env,n=await Qp(e),r=[t.platform,
|
|
706
|
+
t.arch,t.execPath,n,e.USER??e.USERNAME??e.LOGNAME,e.HOME??e.USERPROFILE].filter(o=>typeof o=="string"&&o.length>0);return r.length?r.join("|"):void 0}var ef=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTI\
|
|
707
|
+
ONS","GITLAB_CI","CIRCLECI","TRAVIS","JENKINS_URL","BUILDKITE","TF_BUILD","TEAMCITY_VERSION","BITBUCKET_BUILD_NUMBER","CODEBUILD_BUILD_ID","HEROKU_TEST_RUN_ID","DRONE"];function Ei(){let t=Tr()?.env;if(!t)
|
|
708
|
+
return false;for(let e of ef){let n=t[e];if(n&&n!=="false"&&n!=="0")return true}return false}async function tf(t,e){let n=globalThis.crypto,r=new TextEncoder;if(n?.subtle)try{let s=await n.subtle.importKey("raw",
|
|
709
|
+
r.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await n.subtle.sign("HMAC",s,r.encode(e));return [...new Uint8Array(a)].map(c=>c.toString(16).padStart(2,"0")).join("")}catch{}let o=2166136261,i=`${t}\
|
|
710
|
+
|${e}`;for(let s=0;s<i.length;s++)o^=i.charCodeAt(s),o=Math.imul(o,16777619);return (o>>>0).toString(16).padStart(8,"0")}async function Ri(t){let n=Tr()?.env?.BVSALA_SEAT_ID;if(n&&nf.test(n))return n;let r=await Xp();
|
|
711
|
+
if(!r)return;let o=await tf(t,r);if(o)return `m-${o.slice(0,32)}`}var nf=/^[A-Za-z0-9._:/-]{1,128}$/;var Hc={inputPer1k:5e-4,outputPer1k:.0015,cachedInputPer1k:5e-5};function Wc(t){return {exactCache:t.exactCache??new An,semanticCache:t.semanticCache,singleflight:t.singleflight??new On,resolvers:t.resolvers??Fs(),router:t.router??new $n,toolSelector:t.toolSelector??
|
|
712
|
+
new Bn,formatSelector:t.formatSelector??new Vn({tokenizer:t.tokenizer}),schemaRegistry:t.schemaRegistry??new Un,constraintBackends:t.constraintBackends??[]}}var ye=class extends Error{requestSent;constructor(e){super(e?"[bvsala] stream aborted: the provider request was cancelled before its final usage; nothing was cached or recorded":"[bvsala] stream abor\
|
|
713
|
+
ted before any provider request was sent"),this.name="StreamAbortedError",this.requestSent=e;}},Pr=class extends Error{job;notSubmitted;constructor(e,n,r,o){super(e,o),this.name="BatchSubmitError",this.
|
|
714
|
+
job=n,this.notSubmitted=r;}};var rf={"gpt-4.1":false,"gpt-4.1-mini":false,"gpt-4.1-nano":false,"gpt-4o":false,"gpt-4o-mini":false,"gpt-4-turbo":false,"gpt-4":false,"gpt-3.5-turbo":false,"gpt-5":true,"gpt-5-codex":true,"gpt-5-mini":true,"gpt-5-nano":true,"gpt-5.\
|
|
606
715
|
1-codex":true,"gpt-5.1-codex-max":true,"gpt-5.1-codex-mini":true,"gpt-5.1-thinking":true,"gpt-5.2":true,"gpt-5.2-codex":true,"gpt-5.3-codex":true,"gpt-5.4":true,"gpt-5.4-mini":true,"gpt-5.4-nano":true,"gpt-5.5":true,"gpt-5\
|
|
607
716
|
.6-luna":true,"gpt-5.6-sol":true,"gpt-5.6-terra":true,"gpt-6-astra":true,"gpt-6-sol":true,"gpt-6-luna":true,o3:true,"o3-mini":true,"o3-pro":true,"o4-mini":true,"claude-opus-4-5":false,"claude-opus-4-6":false,"claude-opus-4-7":false,
|
|
608
717
|
"claude-opus-4-8":false,"claude-opus-5":true,"claude-opus-5-5":true,"claude-opus-4":false,"claude-sonnet-4-5":false,"claude-sonnet-4-6":false,"claude-sonnet-5":true,"claude-fable-5":true,"claude-fable-5-1":true,"claude-myt\
|
|
609
718
|
hos-5-1":true,"claude-mythos-5":true,"claude-sonnet-4":false,"claude-haiku-4-5":false,"claude-3-5-sonnet":false,"claude-3-5-haiku":false,"claude-3-opus":false,"claude-3-haiku":false,"gemini-3.8-flash":true,"gemini-3.7-flash":true,
|
|
610
|
-
"gemini-3.6-flash":true,"gemini-3.1-flash-lite":true,"gemini-3-flash-preview":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini-2.5-pro":true,"gemini-2.5-flash":true},
|
|
611
|
-
["claude-opus-4-7","claude-opus-4-8"]),
|
|
612
|
-
/^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function
|
|
613
|
-
return "unclassified-model";let o=
|
|
719
|
+
"gemini-3.6-flash":true,"gemini-3.1-flash-lite":true,"gemini-3-flash-preview":true,"gemini-3.5-flash":true,"gemini-3.5-flash-lite":true,"gemini-3.1-pro-preview":true,"gemini-2.5-pro":true,"gemini-2.5-flash":true},of=new Set(
|
|
720
|
+
["claude-opus-4-7","claude-opus-4-8"]),sf=[/^o\d/,/^gpt-5/,/^gpt-([6-9]|\d{2})/,/^gpt-oss/,/^gemini-(2\.5|[3-9])/,/^claude-[a-z]+-([5-9]|\d{2})/,/^grok-(3-mini|[4-9])/,/reason/,/think/,/(^|[-_.])r\d($|[-_.])/,
|
|
721
|
+
/^qwq/,/^qwen3/,/^glm-(4\.[5-9]|[5-9])/,/magistral/];function Jc(t){let e=t.lastIndexOf("/"),n=(e>=0?t.slice(e+1):t).toLowerCase();if(sf.some(i=>i.test(n)))return "reasoning-model";let r=vt(t);if(r===void 0)
|
|
722
|
+
return "unclassified-model";let o=rf[r];if(o===true)return "reasoning-model";if(o!==false)return "unclassified-model";if(of.has(r))return "temperature-ignored"}var Ii={minimumCacheTokens:1024,cacheReadMultiplier:.5,cacheWriteMultiplier:1},Kc={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1.25},af=[["claude-fable-5-1",512],["claude-mytho\
|
|
614
723
|
s-5-1",512],["claude-fable-5",512],["claude-mythos-5",512],["claude-opus-5-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",
|
|
615
|
-
4096],["claude-3-5-haiku",2048]];function
|
|
616
|
-
n)),
|
|
617
|
-
0),r=e-n,o=t.tier.minimumCacheTokens,s=o!=null&&t.originalTokens>=o&&t.compressedTokens<o,a;if(r<=0){let
|
|
618
|
-
< ${o}) and costs more than it saves`:
|
|
724
|
+
4096],["claude-3-5-haiku",2048]];function Di(t){for(let[e,n]of af)if(t===e||t.startsWith(`${e}-`))return {...Kc,minimumCacheTokens:n};return Kc}var _i={minimumCacheTokens:1024,cacheReadMultiplier:.1,cacheWriteMultiplier:1};var Gc={minimumCacheTokens:1024,cacheReadMultiplier:1,cacheWriteMultiplier:1};function Cr(t,e,n,r){let o=r.minimumCacheTokens;if(o==null||t<o)return t;let i=Math.min(e,t),s=t-i,a=Math.min(1,Math.max(0,
|
|
725
|
+
n)),c=a*i*r.cacheReadMultiplier+(1-a)*i*r.cacheWriteMultiplier;return s+c}function Ai(t){let e=Cr(t.originalTokens,t.stablePrefixTokens,t.prefixHitRate,t.tier),n=Cr(t.compressedTokens,0,0,t.tier)+(t.compressorCostTokens??
|
|
726
|
+
0),r=e-n,o=t.tier.minimumCacheTokens,s=o!=null&&t.originalTokens>=o&&t.compressedTokens<o,a;if(r<=0){let c=e<t.originalTokens;a=s?`compressing drops the prompt out of the cacheable tier (${t.compressedTokens}\
|
|
727
|
+
< ${o}) and costs more than it saves`:c?`not compressing is cheaper: the provider's prefix cache already discounts this prompt (${e.toFixed(0)} vs ${n.toFixed(0)} equivalent tokens, at a ${(t.prefixHitRate*
|
|
619
728
|
100).toFixed(0)}% hit rate)`:"the saving does not cover the compressor's cost";}else s?a=`pays off even after losing the prefix cache (${(t.prefixHitRate*100).toFixed(0)}% hit rate)`:a="pays off and do\
|
|
620
|
-
es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function
|
|
621
|
-
r=1;for(let o=0;o<40;o++){let i=(n+r)/2;e(i)>0?n=i:r=i;}return (n+r)/2}function
|
|
622
|
-
totalTokens?null:1)}var
|
|
623
|
-
1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=
|
|
624
|
-
{marcar:true,razon:"marking cannot lose money at this tier (no write premium)",umbral:r,observada:i}:o?.apagada?{marcar:false,razon:`prefix-cache marking OFF: measured hit rate ${
|
|
729
|
+
es not touch the cache tier";return {comprimir:r>0,costeComprimido:n,costeSinComprimir:e,ganancia:r,razon:a}}function Yc(t){let e=o=>Ai({...t,prefixHitRate:o}).ganancia;if(e(0)<=0||e(1)>0)return null;let n=0,
|
|
730
|
+
r=1;for(let o=0;o<40;o++){let i=(n+r)/2;e(i)>0?n=i:r=i;}return (n+r)/2}function cf(t){let e=Yc({originalTokens:t.totalTokens,compressedTokens:t.totalTokens,stablePrefixTokens:t.stablePrefixTokens,tier:t.tier});return e??(Cr(t.totalTokens,t.stablePrefixTokens,0,t.tier)<=t.
|
|
731
|
+
totalTokens?null:1)}var Er=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-
|
|
732
|
+
1)*e}estado(e){return this.estados.get(e)}decidir(e,n){let r=cf(n),o=this.estados.get(e),i=uf(o);return n.stablePrefixTokens<=0?{marcar:false,razon:"no stable prefix to cache",umbral:r,observada:i}:r==null?
|
|
733
|
+
{marcar:true,razon:"marking cannot lose money at this tier (no write premium)",umbral:r,observada:i}:o?.apagada?{marcar:false,razon:`prefix-cache marking OFF: measured hit rate ${Mt(i)} did not reach the ${Mt(
|
|
625
734
|
r)} break-even, so marking was costing money`,umbral:r,observada:i}:o==null||o.marcadas<this.exploracion?{marcar:true,razon:`exploring the prefix cache (${o?.marcadas??0}/${this.exploracion}); hit rate \
|
|
626
|
-
is only observable on requests that were marked`,umbral:r,observada:i}:i!=null&&i>r?{marcar:true,razon:`measured hit rate ${
|
|
627
|
-
razon:`prefix-cache marking OFF: measured hit rate ${
|
|
628
|
-
tokensLeidos:0,tokensEscritos:0,apagada:false};r.marcadas+=1,r.tokensLeidos+=Math.max(0,n.cachedInputTokens??0),r.tokensEscritos+=Math.max(0,n.cacheWriteInputTokens??0),this.estados.set(e,r);}};function
|
|
629
|
-
if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function
|
|
630
|
-
|
|
735
|
+
is only observable on requests that were marked`,umbral:r,observada:i}:i!=null&&i>r?{marcar:true,razon:`measured hit rate ${Mt(i)} beats the ${Mt(r)} break-even`,umbral:r,observada:i}:(o.apagada=true,{marcar:false,
|
|
736
|
+
razon:`prefix-cache marking OFF: measured hit rate ${Mt(i)} did not reach the ${Mt(r)} break-even, so marking was costing money`,umbral:r,observada:i})}registrar(e,n){let r=this.estados.get(e)??{marcadas:0,
|
|
737
|
+
tokensLeidos:0,tokensEscritos:0,apagada:false};r.marcadas+=1,r.tokensLeidos+=Math.max(0,n.cachedInputTokens??0),r.tokensEscritos+=Math.max(0,n.cacheWriteInputTokens??0),this.estados.set(e,r);}};function uf(t){
|
|
738
|
+
if(!t)return null;let e=t.tokensLeidos+t.tokensEscritos;return e<=0?t.marcadas>0?0:null:t.tokensLeidos/e}function Mt(t){return t==null?"n/a":`${(t*100).toFixed(1)}%`}var Lt={"5m":3e5,"30m":18e5,"1h":36e5},jt=["5m","30m","1h"],Xc=20;function Zc(t,e){let n=3735928559^e,r=1103547991^e;for(let o=0;o<t.length;o++){let i=t.charCodeAt(o);n=Math.imul(n^i,2654435761),r=Math.
|
|
739
|
+
imul(r^i,1597334677);}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Qc(t){
|
|
740
|
+
return Zc(t,0).toString(36)+"."+Zc(t,2654435769).toString(36)}function lf(t){let e=t.toolCalls?.length?t.toolCalls.map(n=>`${n.id??""}${n.name}${n.arguments}`).join(""):"";return `${t.role}${t.name??
|
|
741
|
+
""}${t.toolCallId??""}${e}${t.content}`}function eu(t,e){let n=[Qc(`bvsala-prefijo\0${t}`)];for(let r of e)n.push(Qc(`${n[n.length-1]}${lf(r)}`));return n}function tu(t){let e=0;for(;e<t.length&&t[e].
|
|
742
|
+
role==="system";)e+=1;return e}function Oi(){return {"5m":0,"30m":0,"1h":0}}function Mi(){return {"5m":{resueltas:0,reutilizadas:0,tardias:0},"30m":{resueltas:0,reutilizadas:0,tardias:0},"1h":{resueltas:0,
|
|
743
|
+
reutilizadas:0,tardias:0}}}var Rr=class{clases=new Map;porHuella=new Map;maxPorClase;maxClases;prediccionesMinimas;confirmacionMinima;memoria;constructor(e={}){this.maxPorClase=Math.max(16,e.maxPorClase??
|
|
744
|
+
2048),this.maxClases=Math.max(1,e.maxClases??256),this.prediccionesMinimas=Math.max(1,e.prediccionesMinimas??8),this.confirmacionMinima=e.confirmacionMinima??.5,this.memoria=Math.max(32,e.memoria??512);}observar(e,n,r){
|
|
745
|
+
let o=this.estadoDe(e);this.vencer(o,r);let i=null;for(let s=1;s<n.length;s++){let a=this.porHuella.get(n[s]);if(!a||a.descartada||a.clase!==e||a.indice!==s)continue;let c=Math.max(0,r-a.escrita);c>Lt["\
|
|
746
|
+
1h"]||(this.resolverReutilizada(o,a,c),i={tipo:a.tipo,indice:s,huecoMs:c,...a.posicionDelProveedor!==void 0?{posicionDelProveedor:a.posicionDelProveedor}:{},...a.ttl?{ttl:a.ttl}:{}});}return i}registrar(e){
|
|
747
|
+
let n=this.estadoDe(e.clase);this.vencer(n,e.enviada);let r=e.enviada;for(let o of ["S","H","T"]){let i=e.tramos[o];if(i===void 0||i<=0||i>=e.huellas.length)continue;if(n.cola.length-n.cabeza>=this.maxPorClase)
|
|
748
|
+
break;let s=e.huellas[i],a=e.ultimoMarcado===o,c={clase:e.clase,tipo:o,huella:s,indice:i,escrita:r,contadas:0,descartada:false,...a&&e.posicionDelProveedor!=null&&e.posicionDelProveedor>0?{posicionDelProveedor:e.
|
|
749
|
+
posicionDelProveedor}:{},...a&&e.ttl?{ttl:e.ttl}:{}},u=this.porHuella.get(s);u&&u.contadas!==7&&this.descartar(u),this.porHuella.set(s,c),n.cola.push(c);for(let l of jt)n.pendientes[o][l]+=1;}}verificar(e,n,r){
|
|
750
|
+
if(n.posicionDelProveedor===void 0)return;let o=n.ttl??"5m";if(n.huecoMs>Lt[o])return;let i=this.estadoDe(e);i.predichas+=1,r>=n.posicionDelProveedor*.98&&(i.confirmadas+=1),i.predichas>=this.prediccionesMinimas&&
|
|
751
|
+
i.confirmadas/i.predichas<this.confirmacionMinima&&(i.apagada=true);}estadistica(e,n){let r=this.estadoDe(e);this.vencer(r,n);let o=(i,s)=>({pendientes5m:s["5m"],pendientes30m:s["30m"],pendientes1h:s["1h"],
|
|
752
|
+
muestras5m:i["5m"].resueltas,muestras30m:i["30m"].resueltas,muestras1h:i["1h"].resueltas,k5m:i["5m"].reutilizadas,k30m:i["30m"].reutilizadas,k1h:i["1h"].reutilizadas,kTardias:i["1h"].tardias,en5m:Li(i["\
|
|
753
|
+
5m"]),en30m:Li(i["30m"]),en1h:Li(i["1h"])});return {S:o(r.contadores.S,r.pendientes.S),H:o(r.contadores.H,r.pendientes.H),T:o(r.contadores.T,r.pendientes.T),predichas:r.predichas,confirmadas:r.confirmadas,
|
|
754
|
+
apagada:r.apagada}}get vivas(){return this.porHuella.size}estadoDe(e){let n=this.clases.get(e);if(n)return this.clases.delete(e),this.clases.set(e,n),n;for(n={contadores:{S:Mi(),H:Mi(),T:Mi()},pendientes:{
|
|
755
|
+
S:Oi(),H:Oi(),T:Oi()},cola:[],cabeza:0,cursores:{"5m":0,"30m":0,"1h":0},predichas:0,confirmadas:0,apagada:false},this.clases.set(e,n);this.clases.size>this.maxClases;){let[r,o]=this.clases.entries().next().
|
|
756
|
+
value;for(let i=o.cabeza;i<o.cola.length;i++){let s=o.cola[i];this.porHuella.get(s.huella)===s&&this.porHuella.delete(s.huella);}this.clases.delete(r);}return n}descartar(e){let n=this.clases.get(e.clase);
|
|
757
|
+
jt.forEach((r,o)=>{e.contadas&1<<o||(n&&(n.pendientes[e.tipo][r]=Math.max(0,n.pendientes[e.tipo][r]-1)),e.contadas|=1<<o);}),e.descartada=true;}resolverReutilizada(e,n,r){jt.forEach((o,i)=>{if(n.contadas&
|
|
758
|
+
1<<i)return;e.pendientes[n.tipo][o]=Math.max(0,e.pendientes[n.tipo][o]-1);let s=e.contadores[n.tipo][o];s.resueltas+=1,r<=Lt[o]&&(s.reutilizadas+=1),o==="1h"&&r<=Lt["1h"]&&r>Lt["5m"]&&(s.tardias+=1),n.
|
|
759
|
+
contadas|=1<<i;}),this.reducirSiHaceFalta(e.contadores[n.tipo]);}vencer(e,n){for(jt.forEach((r,o)=>{let i=Math.max(e.cursores[r],e.cabeza);for(;i<e.cola.length&&n-e.cola[i].escrita>Lt[r];){let s=e.cola[i];
|
|
760
|
+
!s.descartada&&!(s.contadas&1<<o)&&(e.pendientes[s.tipo][r]=Math.max(0,e.pendientes[s.tipo][r]-1),e.contadores[s.tipo][r].resueltas+=1,this.reducirSiHaceFalta(e.contadores[s.tipo])),s.contadas|=1<<o,i+=
|
|
761
|
+
1;}e.cursores[r]=i;});e.cabeza<e.cursores["1h"];){let r=e.cola[e.cabeza];this.porHuella.get(r.huella)===r&&this.porHuella.delete(r.huella),e.cabeza+=1;}if(e.cabeza>1024&&e.cabeza*2>e.cola.length){e.cola.
|
|
762
|
+
splice(0,e.cabeza);for(let r of jt)e.cursores[r]-=e.cabeza;e.cabeza=0;}}reducirSiHaceFalta(e){for(let n of jt)e[n].resueltas>=this.memoria&&(e[n].resueltas=Math.floor(e[n].resueltas/2),e[n].reutilizadas=
|
|
763
|
+
Math.floor(e[n].reutilizadas/2),e[n].tardias=Math.floor(e[n].tardias/2));}};function Li(t){return t.resueltas>0?t.reutilizadas/t.resueltas:0}function ji(t,e){let n=t-e;return n>0?Math.max(0,(t-1)/n):1}
|
|
764
|
+
function Ni(t,e,n=1.96){if(e<=0)return [0,1];let r=t/e,o=n*n,i=(r+o/(2*e))/(1+o/e),s=n*Math.sqrt(r*(1-r)/e+o/(4*e*e))/(1+o/e);return [Math.max(0,i-s),Math.min(1,i+s)]}function $i(t,e,n,r,o){return e+n>=
|
|
765
|
+
o&&Ni(t,e+n)[0]>r?true:e>=o&&Ni(t,e)[1]<r?false:null}function nu(t){let e=t.muestrasMinimas??5,n=t.tramo.cacheReadMultiplier,r=t.tramo.cacheWriteMultiplier,o=t.primaDeUnaHora!=null&&t.primaDeUnaHora>r?t.primaDeUnaHora:
|
|
766
|
+
null,i=ji(r,n),s=o!=null?ji(o,n):null,a={historial:true,cola:false,ttl:"5m",razon:"",equilibrio:i};if(t.estadistica.apagada)return {...a,razon:`fixed placement: the provider's counter confirmed only ${t.estadistica.
|
|
767
|
+
confirmadas} of ${t.estadistica.predichas} cache reads the layer predicted for this traffic, so the layer stopped trusting its own reuse measurement here`};let c=b=>({en5m:$i(b.k5m,b.muestras5m,b.pendientes5m,
|
|
768
|
+
i,e),en1h:s!=null?$i(b.k1h,b.muestras1h,b.pendientes1h,s,e):null}),u=[],l=t.estadistica.H,d=t.estadistica.T,m=c(l),f=c(d),h=b=>`${b.k5m}/${b.muestras5m} in 5 min, ${b.k1h}/${b.muestras1h} in 1 h`,g=true;
|
|
769
|
+
t.hayHistorial&&(m.en5m===true||m.en1h===true?u.push(`history re-sent (${h(l)}): above break-even, marked`):m.en5m===false?(g=false,u.push(`history re-sent only ${h(l)} (break-even ${Nt(i)}): breakpoint moved b\
|
|
770
|
+
ack to the system header, no write premium on a prefix nobody re-reads`)):u.push(`history: not conclusive yet (${h(l)}), fixed placement kept`));let p=f.en5m===true||f.en1h===true;u.push(p?`continued ${h(
|
|
771
|
+
d)}: above break-even, tail marked so the next turn reads this whole prompt`:f.en5m===false?`continued only ${h(d)} (break-even ${Nt(i)}): tail not marked`:`tail: not conclusive yet (${h(d)}), not marked`);
|
|
772
|
+
let y="5m";if(o!=null){let b=p?"T":g&&t.hayHistorial?"H":"S",v=t.estadistica[b],w=b==="T"?f:b==="H"?m:c(v),S=b==="T"?t.tokens.T:b==="H"?t.tokens.H:t.tokens.S;if(w.en5m!==true&&w.en1h===true)y="1h",u.push(
|
|
773
|
+
`1h TTL: re-sent ${h(v)} (1 h break-even ${Nt(s)}), while 5 min does not pay`);else if(w.en5m===true&&v.muestras1h>=e&&S>0){let[k]=Ni(v.kTardias,v.muestras1h+v.pendientes1h),x=Math.max(0,S-t.lecturaPrevista()),
|
|
774
|
+
E=k*(r-n)*S,C=(o-r)*x;E>C&&(y="1h",u.push(`1h TTL: at least ${Nt(k)} of re-sends come after 5 min; re-reading ${S} tokens then beats the extra premium on the ${x} written now`));}}return {historial:g,cola:p,
|
|
775
|
+
ttl:y,razon:u.join("; "),equilibrio:i}}function ru(t){let e=t.muestrasMinimas??5,n=ji(t.tramo.cacheWriteMultiplier,t.tramo.cacheReadMultiplier),r=t.estadistica.T,o=t.estadistica.H,i=(a,c,u)=>$i(a,c,u,
|
|
776
|
+
n,e)===false;if(t.estadistica.apagada)return {explicita:false,historial:true,razon:`provider default kept: the provider's counter confirmed only ${t.estadistica.confirmadas} of ${t.estadistica.predichas} predi\
|
|
777
|
+
cted cache reads`,equilibrio:n};if(!i(r.k30m,r.muestras30m,r.pendientes30m))return {explicita:false,historial:true,razon:`provider default kept: continued ${r.k30m}/${r.muestras30m} within 30 min, not clear\
|
|
778
|
+
ly below the ${Nt(n)} break-even`,equilibrio:n};let s=!t.hayHistorial||!i(o.k30m,o.muestras30m,o.pendientes30m);return {explicita:true,historial:s,razon:`explicit mode: continued only ${r.k30m}/${r.muestras30m}\
|
|
779
|
+
within 30 min (break-even ${Nt(n)}), so the question is not written; breakpoint at the ${s?"end of the stable history":"system header"}`,equilibrio:n}}function Nt(t){return `${(t*100).toFixed(1)}%`}var ou=.5;function df(t,e){return e.inputPer1k<=0||e.outputPer1k<=0?null:Math.max(t.inputPer1k/e.inputPer1k,t.outputPer1k/e.outputPer1k)}function pf(t){return 1-t}function ff(t,e=ou){return e-t}function iu(t,e,n=ou){
|
|
780
|
+
if(!t||!e)return null;let r=df(t,e);if(r==null||!Number.isFinite(r))return null;let o=pf(r),i=ff(r,n),s=i>0,a=c=>`${(c*100).toFixed(1)}%`;return {r,equilibrio:o,escaladoMaximo:i,viable:s,razon:s?`the c\
|
|
631
781
|
heap model costs ${a(r)} of the strong one, so routing pays off while escalations stay under ${a(i)} (it stops saving money at ${a(o)})`:`the cheap model costs ${a(r)} of the strong one: even with zer\
|
|
632
|
-
o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var
|
|
633
|
-
ude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-opus":"claude-3-haiku","claude-3-5-sonnet":"claude-3-5-haiku"};function
|
|
634
|
-
length||e.localeCompare(n))}function
|
|
635
|
-
for(let n of
|
|
636
|
-
e)}decidir(e,n){let r=this.estados.get(e),o=
|
|
782
|
+
o escalations it cannot reach the ${a(n)} target, so this pair is not worth the quality risk`}}var Bi={"gpt-4":"gpt-4o","gpt-4-turbo":"gpt-4o-mini","gpt-4o":"gpt-4o-mini","gpt-4.1":"gpt-4.1-mini","cla\
|
|
783
|
+
ude-opus-4":"claude-haiku-4-5","claude-sonnet-4":"claude-haiku-4-5","claude-3-opus":"claude-3-haiku","claude-3-5-sonnet":"claude-3-5-haiku"};function mf(t){return Object.keys(t).sort((e,n)=>n.length-e.
|
|
784
|
+
length||e.localeCompare(n))}function su(t,e=Bi){if(!t)return null;let n=t.lastIndexOf("/"),r=n>=0?t.slice(0,n+1):"",o=n>=0?t.slice(n+1):t,i=e[t]??e[o]??hf(o,e);return !i||i===o?null:r+i}function hf(t,e){
|
|
785
|
+
for(let n of mf(e))if(t.startsWith(n)&&t.charAt(n.length)==="-"&&/^\d{4}/.test(t.slice(n.length+1)))return e[n]}var Ir=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(
|
|
786
|
+
e)}decidir(e,n){let r=this.estados.get(e),o=gf(r),i=r?.enrutadas??0,s=a=>a==null?"n/a":`${(a*100).toFixed(1)}%`;return r?.apagada?{enrutar:false,razon:`model cascade OFF for this workload: measured escal\
|
|
637
787
|
ation rate ${s(o)} is at or above the ${s(n.equilibrio)} break-even, so routing was costing money`,observada:o,muestras:i}:i<this.exploracion?{enrutar:true,razon:`measuring this workload (${i}/${this.exploracion}\
|
|
638
788
|
); the escalation rate is only observable on requests that were actually routed`,observada:o,muestras:i}:o!=null&&o<n.equilibrio?{enrutar:true,razon:`measured escalation rate ${s(o)} stays under the ${s(
|
|
639
789
|
n.equilibrio)} break-even (this is a MONEY check, not a quality one)`,observada:o,muestras:i}:(r&&(r.apagada=true),{enrutar:false,razon:`model cascade OFF for this workload: measured escalation rate ${s(o)}\
|
|
640
790
|
is at or above the ${s(n.equilibrio)} break-even, so routing was costing money`,observada:o,muestras:i})}registrar(e,n){let r=this.estados.get(e)??{enrutadas:0,escaladas:0,apagada:false};r.enrutadas+=1,
|
|
641
|
-
n&&(r.escaladas+=1),this.estados.set(e,r);}};function
|
|
642
|
-
for(let r of
|
|
791
|
+
n&&(r.escaladas+=1),this.estados.set(e,r);}};function gf(t){return !t||t.enrutadas<=0?null:t.escaladas/t.enrutadas}var bf=["enum","pattern","maximum","minimum","maxLength","minLength","maxItems","minItems"];function vf(t){return t?Fi(t)?"value-constrained":"structural":"none"}function Fi(t,e=0){if(e>12)return false;let n=t;
|
|
792
|
+
for(let r of bf)if(n[r]!==void 0)return true;if(t.properties){for(let r of Object.values(t.properties))if(Fi(r,e+1))return true}return !!(t.items&&Fi(t.items,e+1))}function au(t){let e=vf(t.schema),n=(t.tools??
|
|
643
793
|
[]).filter(r=>r.risk==="write"||r.risk==="destructive");return n.length>0?{elegible:false,fuerza:e,razon:`the request carries ${n.length} write/destructive tool(s); a cheaper model's choice of ACTION can\
|
|
644
794
|
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\
|
|
645
795
|
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 \
|
|
646
|
-
content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function
|
|
796
|
+
content has somewhere to fall":"output contract checks shape only: a well-formed answer with wrong content passes"}}function zi(t){let e=[];if(e.push("non-empty"),t.texto.trim()==="")return {acepta:false,
|
|
647
797
|
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 \
|
|
648
798
|
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\
|
|
649
799
|
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,
|
|
650
|
-
motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=
|
|
651
|
-
acepta:false,motivo:`the cheap model's answer does not satisfy the output contract (${r.errors.slice(0,3).map(i=>`${i.path}: ${i.message}`).join("; ")})`,comprobaciones:e}}function
|
|
652
|
-
JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=
|
|
653
|
-
le facts (free prose only)"}:
|
|
654
|
-
of a false valid \u2014 it is a reason to look, never a verdict"}}var
|
|
655
|
-
an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=
|
|
656
|
-
t")for(let r of Object.keys(t).sort())
|
|
657
|
-
, because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function
|
|
658
|
-
0,t)}function
|
|
659
|
-
"object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:
|
|
660
|
-
{valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=
|
|
661
|
-
ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let i=
|
|
662
|
-
t);return e?JSON.stringify(e.valor):null}function
|
|
663
|
-
let o=r.minimumSavingsTokens??
|
|
800
|
+
motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=le(n,t.schema);return r.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
|
|
801
|
+
acepta:false,motivo:`the cheap model's answer does not satisfy the output contract (${r.errors.slice(0,3).map(i=>`${i.path}: ${i.message}`).join("; ")})`,comprobaciones:e}}function cu(t,e){let n,r;try{n=
|
|
802
|
+
JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=Dr(n),i=Dr(r);return o.length===0&&i.length===0?{divergen:false,motivo:"no comparab\
|
|
803
|
+
le facts (free prose only)"}:kf(o,i)?{divergen:false,motivo:"the hard values agree"}:{divergen:true,motivo:"both answers satisfy the contract but disagree on at least one hard value; this is the signature \
|
|
804
|
+
of a false valid \u2014 it is a reason to look, never a verdict"}}var yf=40;function Dr(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\
|
|
805
|
+
an")n.push(`b:${t}`);else if(typeof t=="string"){let r=t.trim();r.length>0&&r.length<=yf&&n.push(`s:${r.toLowerCase()}`);}else if(Array.isArray(t))for(let r of t)Dr(r,e+1,n);else if(t&&typeof t=="objec\
|
|
806
|
+
t")for(let r of Object.keys(t).sort())Dr(t[r],e+1,n);return n.sort()}function kf(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 uu="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\
|
|
807
|
+
, because a number nobody can check is not a number at all but a promise, and this product exists to stop making those. ";function xf(t){if(t<=0)return "";let e=uu;for(;e.length<t;)e+=uu;return e.slice(
|
|
808
|
+
0,t)}function wf(t){let e=t[0],n=-1;for(let r of t){let o=JSON.stringify(r)?.length??0;o>n&&(n=o,e=r);}return e}function qi(t){if(t.enum&&t.enum.length>0)return {valor:wf(t.enum)};switch(t.type??(t.properties?
|
|
809
|
+
"object":t.items?"array":void 0)){case "string":return t.maxLength!=null?{valor:xf(t.maxLength)}:void 0;case "boolean":return {valor:false};case "null":return {valor:null};case "integer":return t.maximum!=null?
|
|
810
|
+
{valor:Math.trunc(t.maximum)}:void 0;case "number":return;case "array":{if(t.maxItems==null||!t.items)return;let n=qi(t.items);return n?{valor:Array.from({length:t.maxItems},()=>n.valor)}:void 0}case "ob\
|
|
811
|
+
ject":{if(t.additionalProperties!==false||!t.properties)return;let n={};for(let[r,o]of Object.entries(t.properties)){let i=qi(o);if(!i)return;n[r]=i.valor;}return {valor:n}}default:return}}function Sf(t){let e=qi(
|
|
812
|
+
t);return e?JSON.stringify(e.valor):null}function lu(t,e){let n=Sf(t);return n===null?null:e(n)}var _r=16,du=64,Tf=8,Pf="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 pu(t,e,n,r={}){
|
|
813
|
+
let o=r.minimumSavingsTokens??Tf,i;try{if(Hi(t,0))return {applied:!1,reason:"schema has a pattern; no witness can be synthesised to prove the round trip"};i=Ji(t,0);}catch(M){return {applied:false,reason:M instanceof
|
|
664
814
|
RangeError?"schema too deep or cyclic":"schema could not be compacted"}}if(i.renamed===0&&i.coded===0)return {applied:false,reason:"nothing to compact (no renameable keys, no codeable enums)"};let s=i.node;
|
|
665
|
-
if(!s)return {applied:false,reason:"nothing to compact"};let a=
|
|
666
|
-
i.compact)),
|
|
667
|
-
|
|
668
|
-
evidencia;if(
|
|
669
|
-
e model, not of the schema: ${
|
|
670
|
-
chmarks/ab-live.ts) and pass it in`};let
|
|
671
|
-
he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${
|
|
672
|
-
n.inputPer1k:
|
|
673
|
-
ut tokens ($${
|
|
674
|
-
1)} input tokens equivalent): the compact contract saves ${
|
|
675
|
-
codedEnumValues:i.coded,schemaTokensOriginal:d,schemaTokensCompact:
|
|
676
|
-
function
|
|
677
|
-
ok:false,reason:"compact witness does not validate against the compact schema"};if(!
|
|
678
|
-
ject"||t.type==null&&t.properties!=null}function
|
|
679
|
-
ng")?null:e}function
|
|
815
|
+
if(!s)return {applied:false,reason:"nothing to compact"};let a=M=>$t(M,s,true),c=M=>$t(M,s,false),u=_f(t),l=Cf(t,i.compact,s,u);if(!l.ok)return {applied:false,reason:l.reason};let d=e(JSON.stringify(t)),m=e(JSON.stringify(
|
|
816
|
+
i.compact)),f=d-m,h=Number.POSITIVE_INFINITY;for(let M of u){let O=e(JSON.stringify(M))-e(JSON.stringify(a(M)));O<h&&(h=O);}Number.isFinite(h)||(h=0);let g=M=>M/1e3*n.inputPer1k,p=M=>M/1e3*n.outputPer1k,
|
|
817
|
+
y=g(o),b=n.outputPer1k>0?(o-f)*n.inputPer1k/n.outputPer1k:Number.NEGATIVE_INFINITY,v=Number.isFinite(b)?b.toFixed(1):"any",w=n.inputPer1k>0?`${(n.outputPer1k/n.inputPer1k).toFixed(1)}x`:"more than",S=r.
|
|
818
|
+
evidencia;if(S==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\
|
|
819
|
+
e model, not of the schema: ${Pf}. Here the compact contract saves ${f} input tokens and output is billed ${w} input, so it only pays while the output delta stays above ${v} tokens. Measure yours (ben\
|
|
820
|
+
chmarks/ab-live.ts) and pass it in`};let k=S.deltaTokens;if(k<0)return {applied:false,reason:`the measured output delta is ${k} tokens: this model writes MORE from a compact contract (${S.procedencia}). T\
|
|
821
|
+
he input win is capped by the size of the schema while the output loss grows with the answer and is billed ${w} input, so no schema is big enough to buy it back`};let x=g(f)+p(k),E=n.inputPer1k>0?x*1e3/
|
|
822
|
+
n.inputPer1k:f,C=`+${k} tokens (${k>0?"the model wrote LESS":"no measured change"}), ${S.procedencia}`;return x<y?{applied:false,reason:`net saving $${x.toFixed(9)}/request is below the floor of ${o} inp\
|
|
823
|
+
ut tokens ($${y.toFixed(9)}): the compact contract saves ${f} input tokens and the measured output delta is ${C}; break-even at ${v}`}:{applied:true,reason:`net saving $${x.toFixed(9)}/request (${E.toFixed(
|
|
824
|
+
1)} input tokens equivalent): the compact contract saves ${f} input tokens and the measured output delta is ${C}; break-even at ${v}`,plan:{compactSchema:i.compact,expand:c,compact:a,renamedKeys:i.renamed,
|
|
825
|
+
codedEnumValues:i.coded,schemaTokensOriginal:d,schemaTokensCompact:m,modelledShapeSavingTokens:h,measuredOutputDeltaTokens:k,outputDeltaProvenance:S.procedencia,breakEvenOutputDeltaTokens:b,netSavingUsd:x}}}
|
|
826
|
+
function Cf(t,e,n,r){for(let o of r){if(!le(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let i=$t(o,n,true);if(!le(i,e).valid)return {
|
|
827
|
+
ok:false,reason:"compact witness does not validate against the compact schema"};if(!Wi($t(i,n,false),o))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function fu(t){return t.type==="ob\
|
|
828
|
+
ject"||t.type==null&&t.properties!=null}function mu(t){return t.type==="array"||t.type==null&&t.items!=null}function Ef(t){let e=t.enum;return !e||e.length===0||e.length>du||!e.every(n=>typeof n=="stri\
|
|
829
|
+
ng")?null:e}function Ji(t,e){if(e>_r)throw new RangeError("schema too deep");let n=Ef(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=hu(n,true);if(!r)return {compact:t,renamed:0,
|
|
680
830
|
coded:0};let o=[...r].filter(([s,a])=>s!==a).length;if(o===0)return {compact:t,renamed:0,coded:0};let i=new Map;for(let[s,a]of r)i.set(a,s);return {compact:{...t,enum:n.map(s=>r.get(s))},node:{enumFwd:r,
|
|
681
|
-
enumBack:i},renamed:0,coded:o}}return
|
|
682
|
-
let r=0,o=0,i=new Map,s=new Map;for(let[f
|
|
683
|
-
let
|
|
684
|
-
h,
|
|
685
|
-
if(!t.items)return {compact:t,renamed:0,coded:0};let n=
|
|
686
|
-
...t].sort(),r=new Set,o=new Map;n.forEach((s,a)=>{let
|
|
687
|
-
!r.has(l)&&(
|
|
688
|
-
t;if(e.items&&Array.isArray(t))return t.map(i
|
|
689
|
-
|
|
690
|
-
r,0));return n}function
|
|
691
|
-
if(n>
|
|
692
|
-
0)return [];let r=Math.max(1,t.minItems??1),o=t.maxItems!=null?Math.min(r,t.maxItems):r,i=t.items;return Array.from({length:o},()=>i?
|
|
831
|
+
enumBack:i},renamed:0,coded:o}}return fu(t)?Rf(t,e):mu(t)?If(t,e):{compact:t,renamed:0,coded:0}}function Rf(t,e){let n=Object.entries(t.properties??{});if(n.length===0)return {compact:t,renamed:0,coded:0};
|
|
832
|
+
let r=0,o=0,i=new Map,s=new Map;for(let[m,f]of n){let h=Ji(f,e+1);s.set(m,h.compact),h.node&&i.set(m,h.node),r+=h.renamed,o+=h.coded;}let a=null;t.additionalProperties===false&&(a=hu(n.map(([m])=>m),false));
|
|
833
|
+
let c={};for(let[m]of n)c[a?.get(m)??m]=s.get(m);let u={...t,properties:c};t.required&&(u.required=t.required.map(m=>a?.get(m)??m));let l={};if(a){let m=new Map;for(let[h,g]of a)m.set(g,h);let f=false;for(let[
|
|
834
|
+
h,g]of a)h!==g&&(f=true);if(f){l.keysFwd=a,l.keysBack=m;for(let[h,g]of a)h!==g&&(r+=1);}}i.size>0&&(l.props=i);let d=!l.keysFwd&&!l.props;return {compact:u,...d?{}:{node:l},renamed:r,coded:o}}function If(t,e){
|
|
835
|
+
if(!t.items)return {compact:t,renamed:0,coded:0};let n=Ji(t.items,e+1);return {compact:{...t,items:n.compact},...n.node?{node:{items:n.node}}:{},renamed:n.renamed,coded:n.coded}}function hu(t,e){let n=[
|
|
836
|
+
...t].sort(),r=new Set,o=new Map;n.forEach((s,a)=>{let c=e?s.toUpperCase():s,u=s;for(let l=1;l<s.length;l++){let d=c.slice(0,l);if(!r.has(d)){u=d;break}}if(u===s){let l=a.toString(36);l.length<s.length&&
|
|
837
|
+
!r.has(l)&&(u=l);}r.add(u),o.set(s,u);});let i=new Set(t);for(let[s,a]of o)if(a!==s&&i.has(a))return null;return o}function $t(t,e,n){let r=n?e.enumFwd:e.enumBack;if(r&&typeof t=="string")return r.get(t)??
|
|
838
|
+
t;if(e.items&&Array.isArray(t))return t.map(i=>$t(i,e.items,n));let o=n?e.keysFwd:e.keysBack;if((o||e.props)&&Df(t)){let i={};for(let[s,a]of Object.entries(t)){let c=o?.get(s)??s,u=n?s:c,l=e.props?.get(
|
|
839
|
+
u);i[c]=l?$t(a,l,n):a;}return i}return t}function Df(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function _f(t){let e=Math.min(du,Math.max(1,Vi(t,0))),n=[];for(let r=0;r<e;r++)n.push(Ui(t,
|
|
840
|
+
r,0));return n}function Vi(t,e){if(e>_r)return 0;let n=t.enum?.length??0;for(let r of Object.values(t.properties??{}))n=Math.max(n,Vi(r,e+1));return t.items&&(n=Math.max(n,Vi(t.items,e+1))),n}function Ui(t,e,n){
|
|
841
|
+
if(n>_r)return null;if(t.enum&&t.enum.length>0)return t.enum[Math.min(e,t.enum.length-1)];if(fu(t)){let r={};for(let[o,i]of Object.entries(t.properties??{}))r[o]=Ui(i,e,n+1);return r}if(mu(t)){if(t.maxItems===
|
|
842
|
+
0)return [];let r=Math.max(1,t.minItems??1),o=t.maxItems!=null?Math.min(r,t.maxItems):r,i=t.items;return Array.from({length:o},()=>i?Ui(i,e,n+1):null)}switch(t.type){case "string":{if(t.maxLength===0)return "";
|
|
693
843
|
let r=Math.max(1,t.minLength??1),o=t.maxLength!=null?Math.min(r,t.maxLength):r;return "x".repeat(o)}case "number":case "integer":{let r=t.minimum??1;return t.maximum!=null&&r>t.maximum&&(r=t.maximum),t.type===
|
|
694
|
-
"integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function
|
|
695
|
-
values(t.properties??{}))if(
|
|
696
|
-
isArray(t),r=Array.isArray(e);if(n||r){if(!n||!r||t.length!==e.length)return false;for(let s=0;s<t.length;s++)if(!
|
|
697
|
-
return false;for(let s of o)if(!Object.prototype.hasOwnProperty.call(e,s)||!
|
|
698
|
-
enums)",pares:8}},
|
|
844
|
+
"integer"?Math.round(r):r}case "boolean":return true;case "null":return null;default:return null}}function Hi(t,e){if(e>_r)throw new RangeError("schema too deep");if(t.pattern!=null)return true;for(let n of Object.
|
|
845
|
+
values(t.properties??{}))if(Hi(n,e+1))return true;return !!(t.items&&Hi(t.items,e+1))}function Wi(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.
|
|
846
|
+
isArray(t),r=Array.isArray(e);if(n||r){if(!n||!r||t.length!==e.length)return false;for(let s=0;s<t.length;s++)if(!Wi(t[s],e[s]))return false;return true}let o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)
|
|
847
|
+
return false;for(let s of o)if(!Object.prototype.hasOwnProperty.call(e,s)||!Wi(t[s],e[s]))return false;return true}var Af="2026-08-14",gu={"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 \
|
|
848
|
+
enums)",pares:8}},Of=oo(gu);function Mf(t){return ro(gu,Of,t)}var Ar=class t{deltas=new Map;static clave(e,n){return `${e}\0${n}`}recordar(e,n,r){this.deltas.set(t.clave(e,n),r);}resolver(e,n,r){if(r!=null&&
|
|
699
849
|
Number.isFinite(r))return this.recordar(e,n,r),{deltaTokens:r,origen:"caller",procedencia:`measured by the caller for this contract on ${e}`};let o=this.deltas.get(t.clave(e,n));if(o!=null)return {deltaTokens:o,
|
|
700
|
-
origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let i=
|
|
701
|
-
Velio on ${e} (${
|
|
702
|
-
r=
|
|
703
|
-
n)}:${
|
|
704
|
-
o=new Map;for(let
|
|
705
|
-
o.set(
|
|
706
|
-
get(
|
|
707
|
-
(r,o)=>n.has(o)?{...r,content:
|
|
708
|
-
o==="google"||o==="google-vertex"?
|
|
850
|
+
origen:"remembered",procedencia:`measured by the caller on an earlier request for this contract on ${e}`};let i=Mf(e);return i?{deltaTokens:i.deltaTokens,origen:"catalogue",procedencia:`measured by Bi\
|
|
851
|
+
Velio on ${e} (${Af}, ${i.pares} paired reps, ${i.contrato}, ${i.salidaDelBrazoA}-token answers) \u2014 NOT measured on YOUR contract`}:null}};var Gi="[BiVelio Savings: an older tool result was trimmed here to lower the cost; the most recent results travel in full.]",Lf=new TextEncoder;function jf(t){return Lf.encode(t).length}function Nf(t,e){if(!t)return null;let n=(e??"").trim();if(n===""||n==="{}"||n==="[]")return null;let r;try{let o=JSON.parse(n);if(o&&typeof o=="object"&&!Array.isArray(o)&&Object.keys(o).length===0)return null;
|
|
852
|
+
r=Ki(o);}catch{r=n;}return `${t} ${r}`}function Ki(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(Ki).join(",")}]`:`{${Object.keys(t).sort().map(n=>`${JSON.stringify(
|
|
853
|
+
n)}:${Ki(t[n])}`).join(",")}}`}function bu(t){let e=new Map,n=new Map;for(let u of t)if(u.role==="assistant"&&u.toolCalls)for(let l of u.toolCalls)l.id&&(e.set(l.id,l.arguments),n.set(l.id,l.name));let r=[],
|
|
854
|
+
o=new Map;for(let u=0;u<t.length;u++){let l=t[u];if(l.role!=="tool")continue;r.push(u);let d=(l.toolCallId?n.get(l.toolCallId):void 0)??l.name,m=l.toolCallId?e.get(l.toolCallId):void 0,f=Nf(d,m);f!==null&&
|
|
855
|
+
o.set(u,f);}let i=r.length?r[r.length-1]:-1,s=new Map;for(let u of r){let l=o.get(u);if(l===void 0)continue;let d=s.get(l);(d===void 0||u>d)&&s.set(l,u);}let a=[],c=0;for(let u of r){if(u===i)continue;let l=o.
|
|
856
|
+
get(u);if(l===void 0||s.get(l)===u)continue;let d=jf(t[u].content);d<1024||(a.push(u),c+=d);}return {indices:a,bytesOriginales:c}}function vu(t,e){if(e.length===0)return t;let n=new Set(e);return t.map(
|
|
857
|
+
(r,o)=>n.has(o)?{...r,content:Gi}:r)}function Or(t,e){if(e?.cacheTier)return e.cacheTier;let n=t.toLowerCase(),r=n.indexOf("/"),o=r>0?n.slice(0,r):"",i=r>=0?n.slice(r+1):n;return o==="openai"||o==="azure-openai"?Ii:o==="anthropic"?Di(i):
|
|
858
|
+
o==="google"||o==="google-vertex"?_i:/^(gpt-|o[1-9](-|$)|chatgpt)/.test(i)?Ii:i.startsWith("claude")?Di(i):i.startsWith("gemini")?_i:Gc}function yu(t){let e=t.prefix!=null,n=Ai({originalTokens:t.originalTokens,
|
|
709
859
|
compressedTokens:t.compressedTokens,stablePrefixTokens:t.prefix?.stableTokens??0,prefixHitRate:t.prefix?.hitRate??0,tier:t.tier,...t.compressorCostTokens!=null?{compressorCostTokens:t.compressorCostTokens}:
|
|
710
860
|
{}});if(e)return n;let r=t.tier.minimumCacheTokens;return r!=null&&t.originalTokens>=r&&t.compressedTokens<r?{...n,comprimir:false,razon:`compressing would drop the prompt out of the cacheable tier (${t.
|
|
711
|
-
compressedTokens} < ${r}) and nobody has measured the prefix hit rate, so it cannot be claimed to pay for itself. Declare it in \`compressionEconomics.prefix\` to unlock the full decision`}:n}function
|
|
712
|
-
i=r+e(t.promptTokens+t.esquemasDeLaSegunda)+n(t.salidaFinal),s=o-i,a=r,
|
|
713
|
-
mas avoided (${t.esquemasCompletos-t.esquemasDeLaSegunda}) do not cover it`:u
|
|
714
|
-
ompt and the probe`:
|
|
715
|
-
costeDeDosLlamadas:i,ganancia:s,perdidaSiDegrada:a,razon:
|
|
716
|
-
0,
|
|
717
|
-
get(
|
|
718
|
-
let n=0,r=[];for(let o of t)o.risk==="read"?r.push(o.tokens):n+=o.tokens;r.sort((o,i)=>i-o);for(let o of r.slice(0,Math.max(0,e)))n+=o;return n}var
|
|
719
|
-
"number"&&Number.isInteger(t)&&t>=0;function
|
|
720
|
-
return "simulated-provider";let e=t.usoPrimario;if(!e||e.complete===false||!
|
|
721
|
-
return "no-usage";if(t.eliminatedInput!==0||t.compressedInput!==0||t.elididoLocal!==0||Math.abs(t.sentLocalSinSondeo-t.baselineInput)>
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
o=r?.conDescuento&&r.factor!=null&&r.factor>0&&r.factor<1?r.factor:void 0,i=
|
|
725
|
-
n.outputTokens):e.outputTokens,...o!==void 0?{tierFactor:o}:{},layerInsertions:Math.max(0,t.mensajesDeLaCapa)+Math.
|
|
726
|
-
huella(),textSha256:
|
|
727
|
-
|
|
728
|
-
typeof n.at=="number"&&Number.isFinite(n.at)&&(r===void 0||typeof r=="number"&&r>0&&r<1)&&
|
|
729
|
-
{v:2,requestId:n.requestId,at:n.at,model:n.model,inputTokens:n.inputTokens,outputTokens:n.
|
|
730
|
-
{},requestFingerprint:n.requestFingerprint,textSha256:n.textSha256,...typeof n.cacheKey==
|
|
731
|
-
|
|
732
|
-
return
|
|
733
|
-
|
|
734
|
-
quality"};let r=e.precio,o=r?.cachedInputPer1k;if(!r||typeof o!="number"||!Number.
|
|
735
|
-
r.outputPer1k)||r.outputPer1k<0)return {ok:false,reason:"no-cached-price"};let i=t.inputTokens-
|
|
736
|
-
isFinite(e.topeDeSalida)?Math.max(0,e.topeDeSalida):Number.POSITIVE_INFINITY,a=
|
|
737
|
-
|
|
738
|
-
outputPer1k,tierFactor:
|
|
739
|
-
this.now=e,this.inicio=e();let r,o,i=new Promise((a,
|
|
861
|
+
compressedTokens} < ${r}) and nobody has measured the prefix hit rate, so it cannot be claimed to pay for itself. Declare it in \`compressionEconomics.prefix\` to unlock the full decision`}:n}function xu(t){let e=l=>l/1e3*t.precio.inputPer1k,n=l=>l/1e3*t.precio.outputPer1k,r=e(t.promptTokens+t.descriptoresLigeros)+n(t.salidaDelSondeo),o=e(t.promptTokens+t.esquemasCompletos)+n(t.salidaFinal),
|
|
862
|
+
i=r+e(t.promptTokens+t.esquemasDeLaSegunda)+n(t.salidaFinal),s=o-i,a=r,c=s>0&&s>=a,u;return s<=0?u=`discovery costs more than it saves: the prompt (${t.promptTokens} tokens) is paid twice and the sche\
|
|
863
|
+
mas avoided (${t.esquemasCompletos-t.esquemasDeLaSegunda}) do not cover it`:c?u=`${t.esquemasCompletos-t.esquemasDeLaSegunda} schema tokens avoided in the worst case, enough to pay for the repeated pr\
|
|
864
|
+
ompt and the probe`:u="the gain does not cover the cost of degrading: if the probe does not choose, the request goes out unchanged with every schema and the probe is pure cost",{aplicar:c,costeDeUnaLlamada:o,
|
|
865
|
+
costeDeDosLlamadas:i,ganancia:s,perdidaSiDegrada:a,razon:u}}function wu(t){let n=(t.description??(Array.isArray(t.intents)?t.intents.join("; "):"")).trim().split(/\r?\n/,1)[0]??"",r=n.length>ku?n.slice(
|
|
866
|
+
0,ku-1).trimEnd()+"\u2026":n;return {id:t.id,intents:t.intents,risk:t.risk,...r?{description:r}:{}}}var ku=200;function Su(t,e,n){let r=new Map(e.map(c=>[c.id,c])),o=[],i=[],s=new Set;for(let c of t){let u=r.
|
|
867
|
+
get(c);if(!u){i.push(c);continue}o.includes(u.id)||(o.push(u.id),u.risk==="read"&&s.size<Math.max(0,n)&&s.add(u.id));}return {tools:e.filter(c=>c.risk!=="read"||s.has(c.id)),reconocidos:o,ignorados:i}}function Tu(t,e){
|
|
868
|
+
let n=0,r=[];for(let o of t)o.risk==="read"?r.push(o.tokens):n+=o.tokens;r.sort((o,i)=>i-o);for(let o of r.slice(0,Math.max(0,e)))n+=o;return n}var Bf=2;function Yi(t){return ne(ve({messages:t.messages,structuredData:t.structuredData??null,tools:t.tools??[],schema:t.response?.schema??null}))}function Pu(t){return t.temperature===0}
|
|
869
|
+
var et=t=>typeof t=="number"&&Number.isInteger(t)&&t>=0;function Ff(t,e){if(et(t.reasoningTokens)){if(!e)return t.reasoningTokens;if(et(e.reasoningTokens))return t.reasoningTokens+e.reasoningTokens}}function Cu(t){
|
|
870
|
+
if(t.contadorSimulado)return "simulated-provider";let e=t.usoPrimario;if(!e||e.complete===false||!et(e.inputTokens)||e.inputTokens<=0||!et(e.outputTokens))return "no-usage";let n=t.usoReparacion;if(n&&(n.complete===
|
|
871
|
+
false||!et(n.outputTokens)))return "no-usage";if(t.eliminatedInput!==0||t.compressedInput!==0||t.elididoLocal!==0||Math.abs(t.sentLocalSinSondeo-t.baselineInput)>Bf)return "layer-changed-request";if(t.codebookAplicado)
|
|
872
|
+
return "codebook";if(t.tokensDelSondeo!==0||t.sondeoAplicado)return "tool-discovery";if(t.busquedaNativa===true)return "native-tool-search";if(t.hayEsquema&&(!t.esquemaNativo||t.esquemaPorPrompt))return "sc\
|
|
873
|
+
hema-in-prompt";if(t.hayEsquema&&!t.esquemaEnFormatoNativo)return "schema-not-verbatim";if(t.hayEsquema&&!t.esquemaEstricto)return "schema-not-strict";if(t.modeloServido!==t.modeloPedido)return "cheaper-\
|
|
874
|
+
model-served";if(!t.cacheable)return "not-cacheable";let r=$o(t.tierServido),o=r?.conDescuento&&r.factor!=null&&r.factor>0&&r.factor<1?r.factor:void 0,i=Ff(e,n);return {v:2,requestId:t.requestId,at:t.at,
|
|
875
|
+
model:t.modeloPedido,inputTokens:e.inputTokens,outputTokens:n?Math.min(e.outputTokens,n.outputTokens):e.outputTokens,...o!==void 0?{tierFactor:o}:{},layerInsertions:Math.max(0,t.mensajesDeLaCapa)+Math.
|
|
876
|
+
max(0,t.piezasDelAdaptador)+(t.hayEsquema?1:0),...i!==void 0?{reasoningTokens:i}:{},requestFingerprint:t.huella(),textSha256:ne(t.textoServido)}}var Mr=t=>typeof t=="string"&&t.length>0;function Eu(t){
|
|
877
|
+
if(t==null||typeof t!="object")return "absent";let e=t.reference;if(e==null)return "absent";if(typeof e!="object"||Array.isArray(e))return "malformed";let n=e,r=n.tierFactor,o=n.reasoningTokens;return n.
|
|
878
|
+
v===2&&typeof n.inputTokens=="number"&&Number.isInteger(n.inputTokens)&&n.inputTokens>0&&et(n.outputTokens)&&typeof n.at=="number"&&Number.isFinite(n.at)&&(r===void 0||typeof r=="number"&&r>0&&r<1)&&et(
|
|
879
|
+
n.layerInsertions)&&(o===void 0||et(o))&&Mr(n.requestId)&&Mr(n.model)&&Mr(n.requestFingerprint)&&Mr(n.textSha256)?{v:2,requestId:n.requestId,at:n.at,model:n.model,inputTokens:n.inputTokens,outputTokens:n.
|
|
880
|
+
outputTokens,...r!==void 0?{tierFactor:r}:{},layerInsertions:n.layerInsertions,...o!==void 0?{reasoningTokens:o}:{},requestFingerprint:n.requestFingerprint,textSha256:n.textSha256,...typeof n.cacheKey==
|
|
881
|
+
"string"?{cacheKey:n.cacheKey}:{}}:"malformed"}function zf(t,e){if(!e.determinista)return "sampled";if(e.salidaDelModelo!==void 0)return e.salidaDelModelo;if(t.reasoningTokens===void 0)return "reasoning\
|
|
882
|
+
-not-reported";if(t.reasoningTokens!==0)return "reasoning-reported"}function Ru(t,e){if(e.textoServidoSha256!==t.textSha256)return {ok:false,reason:"witness"};if(e.claveLeida!==void 0&&t.cacheKey!==e.claveLeida)
|
|
883
|
+
return {ok:false,reason:"witness"};if(t.model!==e.modeloPedido||e.modeloServido!==e.modeloPedido)return {ok:false,reason:"model-mismatch"};let n=e.ahoraMs-t.at;if(!(n>=-3e5&&n<=2592e6))return {ok:false,reason:"exp\
|
|
884
|
+
ired"};if(e.huella!==t.requestFingerprint)return {ok:false,reason:"different-request"};if(!e.calidadOk)return {ok:false,reason:"quality"};let r=e.precio,o=r?.cachedInputPer1k;if(!r||typeof o!="number"||!Number.
|
|
885
|
+
isFinite(o)||!(o>0)||!Number.isFinite(r.inputPer1k)||o>r.inputPer1k||typeof r.outputPer1k!="number"||!Number.isFinite(r.outputPer1k)||r.outputPer1k<0)return {ok:false,reason:"no-cached-price"};let i=t.inputTokens-
|
|
886
|
+
8*t.layerInsertions;if(!(i>0))return {ok:false,reason:"no-credit"};let s=typeof e.topeDeSalida=="number"&&Number.isFinite(e.topeDeSalida)?Math.max(0,e.topeDeSalida):Number.POSITIVE_INFINITY,a=zf(t,e),c=a===
|
|
887
|
+
void 0?Math.floor(.95*Math.min(t.outputTokens,s)):0,u=Math.min(1,t.tierFactor??1,e.diferible?ha:1);return {ok:true,...a!==void 0?{outputNotCredited:a}:{},credit:{requestId:t.requestId,at:t.at,inputTokens:t.
|
|
888
|
+
inputTokens,outputTokens:t.outputTokens,creditedInputTokens:i,creditedOutputTokens:c,cachedInputPer1k:o,outputPer1k:r.outputPer1k,tierFactor:u}}}var mn={done:true,value:void 0},hn=class{handle;sumidero;now;inicio;controlador=new AbortController;resolver;rechazar;cola=[];esperas=[];cerrada=false;errorPendiente=null;consumidorSalio=false;iterado=false;_abortado=false;vivo=false;proveedorTerminado=false;terminado=false;primerEventoAt;quitarEscucha;constructor(e,n){
|
|
889
|
+
this.now=e,this.inicio=e();let r,o,i=new Promise((a,c)=>{r=a,o=c;});i.catch(()=>{}),this.resolver=r,this.rechazar=o;let s=this;if(this.sumidero={senal:this.controlador.signal,texto(a){s.recibirTexto(a);},
|
|
740
890
|
proveedorTermino(){s.proveedorTerminado=true;},sirvioEnVivo:false},this.handle={result:i,abort:a=>this.abort(a),[Symbol.asyncIterator]:()=>this.iterador()},n)if(n.aborted)this.abort(n.reason);else {let a=()=>this.
|
|
741
891
|
abort(n.reason);n.addEventListener("abort",a,{once:true}),this.quitarEscucha=()=>n.removeEventListener("abort",a);}}get abortado(){return this._abortado}entrarEnVivo(){this.vivo=true;}completar(e,n){if(this.
|
|
742
892
|
terminado)return;let r=e.toolCalls?.length??0,o=this.primerEventoAt??(n.vivo&&r>0?this.now():void 0),i=n.vivo?{delivery:"live",...o!==void 0?{firstEventMs:o-this.inicio}:{}}:{delivery:"whole",...n.motivo?
|
|
@@ -744,55 +894,54 @@ terminado)return;let r=e.toolCalls?.length??0,o=this.primerEventoAt??(n.vivo&&r>
|
|
|
744
894
|
encolar({type:"tool_call",call:a});this.encolar({type:"done",result:s});}this.cerrar(),this.acabar();}fallar(e){this.terminado||(this.rechazar(e),this._abortado?this.cerrar():this.fallarCola(e),this.acabar());}acabar(){
|
|
745
895
|
this.terminado=true,this.quitarEscucha?.(),this.quitarEscucha=void 0;}abort(e){this.terminado||this._abortado||(this._abortado=true,this.cola.length=0,this.cerrar(),this.vivo&&!this.proveedorTerminado&&this.
|
|
746
896
|
controlador.abort(e));}recibirTexto(e){e===""||this._abortado||this.terminado||(this.primerEventoAt===void 0&&(this.primerEventoAt=this.now()),this.encolar({type:"text",delta:e}));}encolar(e){if(this.cerrada)
|
|
747
|
-
return;let n=this.esperas.shift();n?n.resolve({done:false,value:e}):this.cola.push(e);}cerrar(){this.cerrada=true;for(let e of this.esperas.splice(0))e.resolve(
|
|
748
|
-
esperas.splice(0);if(n){n.reject(e);for(let o of r)o.resolve(
|
|
749
|
-
resolve({done:false,value:e});if(this.errorPendiente){let{valor:n}=this.errorPendiente;return this.errorPendiente=null,Promise.reject(n)}return this.cerrada?Promise.resolve(
|
|
897
|
+
return;let n=this.esperas.shift();n?n.resolve({done:false,value:e}):this.cola.push(e);}cerrar(){this.cerrada=true;for(let e of this.esperas.splice(0))e.resolve(mn);}fallarCola(e){this.cerrada=true;let[n,...r]=this.
|
|
898
|
+
esperas.splice(0);if(n){n.reject(e);for(let o of r)o.resolve(mn);}else this.errorPendiente={valor:e};}siguiente(){if(this.consumidorSalio)return Promise.resolve(mn);let e=this.cola.shift();if(e)return Promise.
|
|
899
|
+
resolve({done:false,value:e});if(this.errorPendiente){let{valor:n}=this.errorPendiente;return this.errorPendiente=null,Promise.reject(n)}return this.cerrada?Promise.resolve(mn):new Promise((n,r)=>{this.esperas.
|
|
750
900
|
push({resolve:n,reject:r});})}iterador(){if(this.iterado)throw new Error("[bvsala] a SavingsStream can be iterated only once");return this.iterado=true,{next:()=>this.siguiente(),return:()=>(this.abort(),
|
|
751
|
-
this.consumidorSalio=true,this.cola.length=0,Promise.resolve(
|
|
752
|
-
"fail_open"?"fail_open":"provider"}}function
|
|
753
|
-
void 0?{sampleDiverged:t.divergedOnSample}:{}};let e=t.servedModel!==t.requestedModel?"accepted":t.escalated===true?"escalated":"not_routed";return {mode:"on",gate:t.verifier,outcome:e}}function
|
|
754
|
-
hechos,n=
|
|
901
|
+
this.consumidorSalio=true,this.cola.length=0,Promise.resolve(mn))}}};function qf(t,e){switch(t){case "deterministic":return "deterministic";case "exact":return "exact_cache";case "semantic":return "semantic_cache";case "singleflight":return "coalesced";default:return e?.origen===
|
|
902
|
+
"fail_open"?"fail_open":"provider"}}function Vf(t){if(!t||t.mode!=="shadow"&&t.mode!=="on")return;if(t.mode==="shadow")return {mode:"shadow",gate:t.verifier,outcome:"not_applied",...t.divergedOnSample!==
|
|
903
|
+
void 0?{sampleDiverged:t.divergedOnSample}:{}};let e=t.servedModel!==t.requestedModel?"accepted":t.escalated===true?"escalated":"not_routed";return {mode:"on",gate:t.verifier,outcome:e}}function Iu(t){let e=t.
|
|
904
|
+
hechos,n=qf(t.cacheResult,e),r={source:n};if(t.hayEsquema)if(t.structurallyValid===null)r.schema={outcome:"not_applicable",decodeTimeConstraint:t.backend!=="none",errorCount:0};else {let i=e?.validacion,
|
|
755
905
|
s=i?.errores??(t.structurallyValid?0:1);r.schema={outcome:t.structurallyValid?"passed":"failed",decodeTimeConstraint:t.backend!=="none",errorCount:s,...i?.desenvuelto?{unwrapped:true}:{}};}if(n==="provid\
|
|
756
906
|
er"&&e?.reparacion&&(r.repair={...e.reparacion}),n==="provider"||n==="fail_open"){let i=e?.final,s=i?.topeDelLlamante;r.truncation={truncated:i?.finishReason==="length",...i?.finishReason!==void 0?{finishReason:i.
|
|
757
907
|
finishReason}:{},capSetByCaller:s!=null,...s!=null?{outputLimit:s}:{}};}if(n==="exact_cache")r.cacheMatch={kind:"exact",...t.ageMs!==void 0?{ageMs:t.ageMs}:{}};else if(n==="semantic_cache"&&e?.semantico){
|
|
758
908
|
let i=e.semantico;r.cacheMatch={kind:"semantic",ageMs:i.ageMs,similarity:i.similarity,similarityFloor:i.similarityFloor,acceptFloor:i.acceptFloor,...i.verifierRan?{verifierScore:i.verifierScore}:{},embedder:i.
|
|
759
|
-
embedder,factGuard:"passed"};}let o=
|
|
760
|
-
|
|
761
|
-
...t.cascade}}:{}}}
|
|
762
|
-
ted before any provider request was sent"),this.name="StreamAbortedError",this.requestSent=e;}};function mr(t){if(t==null)return {activo:false,motivo:"ausente"};if(typeof t!="object")return {activo:false,motivo:"invalido"};let e=t.sampleRate;if(typeof e!="number"||!Number.isFinite(e)||e<0||e>1)return {activo:false,
|
|
909
|
+
embedder,factGuard:"passed",...i.calibration?{calibration:{...i.calibration}}:{}};}let o=Vf(t.cascada);return o&&(r.cascade=o),r}function Du(t){return {source:"coalesced",sharedFrom:t==null?"provider":t.
|
|
910
|
+
source==="coalesced"?t.sharedFrom??"provider":t.source,...t?.schema?{schema:{...t.schema}}:{},...t?.repair?{repair:{...t.repair}}:{},...t?.truncation?{truncation:{...t.truncation}}:{},...t?.cacheMatch?
|
|
911
|
+
{cacheMatch:Uf(t.cacheMatch)}:{},...t?.cascade?{cascade:{...t.cascade}}:{}}}function Uf(t){return t.kind==="semantic"&&t.calibration?{...t,calibration:{...t.calibration}}:{...t}}function Lr(t){if(t==null)return {activo:false,motivo:"ausente"};if(typeof t!="object")return {activo:false,motivo:"invalido"};let e=t.sampleRate;if(typeof e!="number"||!Number.isFinite(e)||e<0||e>1)return {activo:false,
|
|
763
912
|
motivo:"invalido"};let n=t.maxCheckCostUsd;if(n!==void 0&&(typeof n!="number"||!Number.isFinite(n)||n<=0))return {activo:false,motivo:"invalido"};if(e===0)return {activo:false,motivo:"cero"};let r=typeof t.onCheck==
|
|
764
|
-
"function"?t.onCheck:void 0,o=typeof t.waitUntil=="function"?t.waitUntil:void 0;return {activo:true,tasa:e,...n!==void 0?{tope:n}:{},...r?{onCheck:r}:{},...o?{waitUntil:o}:{}}}function
|
|
765
|
-
n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function
|
|
913
|
+
"function"?t.onCheck:void 0,o=typeof t.waitUntil=="function"?t.waitUntil:void 0;return {activo:true,tasa:e,...n!==void 0?{tope:n}:{},...r?{onCheck:r}:{},...o?{waitUntil:o}:{}}}function Hf(t){let e=t*100,
|
|
914
|
+
n=Math.round(e*100)/100;return n===0?"<0.01%":Number.isInteger(n)?`${n}%`:`${n.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}%`}function _u(t){let e=Hf(t);return `[bvsala] Verification sampling is ON \
|
|
766
915
|
(sampleRate ${t}): about ${e} of eligible requests are sent a second time, unoptimized, to your own provider \u2014 in the background, after your answer is returned \u2014 and the second answer is discarded. Yo\
|
|
767
916
|
u pay your provider for those calls: roughly ${e} of what that traffic would cost without the layer. The pairs appear under Proof \u203A Your bench in your dashboard; they are informational and never enter\
|
|
768
|
-
your statement or any commission.`}function
|
|
769
|
-
\` must be a number from 0 to 1 and \`verification.maxCheckCostUsd\`, when set, a positive number (got sampleRate ${e}); verification sampling is OFF.`}var
|
|
917
|
+
your statement or any commission.`}function Au(t){let e;try{let n=t?.sampleRate;e=typeof n=="string"?JSON.stringify(n):String(n);}catch{e="an unreadable value";}return `[bvsala] \`verification.sampleRate\
|
|
918
|
+
\` must be a number from 0 to 1 and \`verification.maxCheckCostUsd\`, when set, a positive number (got sampleRate ${e}); verification sampling is OFF.`}var Ou="[bvsala] Verification sampling is set, b\
|
|
770
919
|
ut its pairs have nowhere to go: set `serviceAccountKey` and `licenseServerUrl` (with metering on) to see them in your dashboard \u2014 a custom `meteringUrl` is followed only when it ends in `/api/meterin\
|
|
771
|
-
g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",
|
|
772
|
-
request was not affected.";function
|
|
920
|
+
g/usage` \u2014 or pass `verification.onCheck` to receive them yourself. No request will be sent twice until then.",Mu="[bvsala] verification sampling hit an internal error and skipped a request; your\
|
|
921
|
+
request was not affected.";function Lu(t){let e=t.messages.map(n=>({...n}));return t.structuredData!==void 0&&e.push({role:"user",content:JSON.stringify(t.structuredData)}),{model:t.model,messages:e,...t.tools&&t.tools.length>0?
|
|
773
922
|
{tools:[...t.tools]}:{},...t.response?.schema?{schema:t.response.schema}:{},...t.response?.maxOutputTokens!=null?{maxOutputTokens:t.response.maxOutputTokens}:{},...t.temperature!==void 0?{temperature:t.
|
|
774
|
-
temperature}:{},...t.seed!==void 0?{seed:t.seed}:{}}}function
|
|
923
|
+
temperature}:{},...t.seed!==void 0?{seed:t.seed}:{}}}function ju(t){let{request:e,result:n,via:r}=t,o=n.report;if(r==="fail-open")return {excluida:"fail_open"};if(e.savings?.verification===false)return {excluida:"opted_out"};let i=n.finishReason;return i==="\
|
|
775
924
|
length"?{excluida:"truncated"}:i!==void 0&&i!=="stop"&&i!=="tool_calls"?{excluida:"incomplete"}:o.constraints.structurallyValid===false||o.qualityStatus==="rejected"?{excluida:"contract_failed"}:o.cost.basis===
|
|
776
925
|
"unmeasured"?{excluida:"unmeasured"}:o.calls.actualRetrieval>0?{excluida:"retrieval"}:t.precio(e.model)===void 0||t.precio(o.model)===void 0?{excluida:"no_price"}:t.tope!==void 0&&o.cost.baselineEstimate>
|
|
777
926
|
t.tope?{excluida:"over_cap"}:o.calls.avoidedLlm>0?{estrato:"avoided_call"}:o.model!==e.model?{estrato:"cheaper_model"}:o.tokens.eliminatedInput>0?{estrato:"tokens_removed"}:o.tokens.compressedInput>0?
|
|
778
|
-
{estrato:"tokens_compressed"}:{estrato:"unchanged"}}function
|
|
779
|
-
i*1e10)/1e10}var
|
|
927
|
+
{estrato:"tokens_compressed"}:{estrato:"unchanged"}}function Nu(t,e){if(!(e>0))return false;if(e>=1)return true;let n=ne(`${t}:verification-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function $u(t,e){let n=t.inputTokens,r=Math.min(t.cachedInputTokens??0,n),o=e.cachedInputPer1k??e.inputPer1k,i=Math.max(0,n-r)/1e3*e.inputPer1k+r/1e3*o+t.outputTokens/1e3*e.outputPer1k;return Math.round(
|
|
928
|
+
i*1e10)/1e10}var Wf=32,Jf=6e5;function Kf(t){return new Date(t).toISOString().slice(0,10)}var jr=class{tasa;tope;onCheck;waitUntil;provider;precio;contrato;now;sumidero;avisar;enVuelo=new Set;cerrado=false;constructor(e){
|
|
780
929
|
this.tasa=e.ajustes.tasa,this.tope=e.ajustes.tope,this.onCheck=e.ajustes.onCheck,this.waitUntil=e.ajustes.waitUntil,this.provider=e.provider,this.precio=e.precio,this.contrato=e.contrato,this.now=e.now,
|
|
781
|
-
this.sumidero=e.sumidero,this.avisar=e.avisar;}get copiasEnVuelo(){return this.enVuelo.size}decidir(e,n,r){if(this.cerrado)return n;try{let o=n.report,i=
|
|
782
|
-
via:r,precio:this.precio,...this.tope!==void 0?{tope:this.tope}:{}}),a;if(i&&"estrato"in s){let l=this.precio(e.model);if(!l)throw new Error("price vanished between classification and launch");a={peticion:
|
|
783
|
-
e),precios:l,estrato:s.estrato};}let
|
|
784
|
-
excluida};return {...n,report:{...o,verification:
|
|
930
|
+
this.sumidero=e.sumidero,this.avisar=e.avisar;}get copiasEnVuelo(){return this.enVuelo.size}decidir(e,n,r){if(this.cerrado)return n;try{let o=n.report,i=Nu(o.requestId,this.tasa),s=ju({request:e,result:n,
|
|
931
|
+
via:r,precio:this.precio,...this.tope!==void 0?{tope:this.tope}:{}}),a;if(i&&"estrato"in s){let l=this.precio(e.model);if(!l)throw new Error("price vanished between classification and launch");a={peticion:Lu(
|
|
932
|
+
e),precios:l,estrato:s.estrato};}let c=this.now();this.sumidero.contar?.(Kf(c),"estrato"in s?s.estrato:s.excluida),a&&this.lanzar(e,n,c,a);let u="estrato"in s?{sampled:i,stratum:s.estrato}:{sampled:i,excluded:s.
|
|
933
|
+
excluida};return {...n,report:{...o,verification:u}}}catch{return this.avisar("verificacion-fallo-interno",Mu),n}}cerrar(){this.cerrado=true;let e=[...this.enVuelo];this.enVuelo.clear();for(let n of e)if(!n.
|
|
785
934
|
decidido){n.decidido=true,n.reloj&&clearTimeout(n.reloj);try{n.abortar.abort();}catch{}this.registrar({...n.base,outcome:"abandoned"}),n.terminar();}}lanzar(e,n,r,o){let i=n.report,s=o.precios,a={requestId:i.
|
|
786
935
|
requestId,at:r,stratum:o.estrato,requestedModel:e.model,servedModel:i.model,cacheResult:i.cache.result,optimized:{cost:i.cost.actual,inputTokens:i.tokens.actualInput,cachedInputTokens:i.tokens.providerCachedInput??
|
|
787
|
-
0,outputTokens:i.tokens.actualOutput},prices:{inputPer1k:s.inputPer1k,...s.cachedInputPer1k!==void 0?{cachedInputPer1k:s.cachedInputPer1k}:{},outputPer1k:s.outputPer1k}};if(this.enVuelo.size>=
|
|
788
|
-
registrar({...a,outcome:"dropped"});return}let
|
|
789
|
-
try{l.abortar.abort();}catch{}this.resolverVuelo(l,{...a,outcome:"check_failed"});},
|
|
790
|
-
{signal:l.abortar.signal}));}catch(
|
|
791
|
-
l,{...a,outcome:"check_failed"});});},0),this.waitUntil)try{this.waitUntil(
|
|
792
|
-
0,
|
|
793
|
-
"string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost
|
|
794
|
-
void 0?{finishReason:
|
|
795
|
-
size===0)try{await this.sumidero.enReposo();}catch{}e.terminar();}}registrar(e){try{this.sumidero.encolar(e);}catch{}if(this.onCheck)try{this.onCheck(e);}catch{}}};var
|
|
936
|
+
0,outputTokens:i.tokens.actualOutput},prices:{inputPer1k:s.inputPer1k,...s.cachedInputPer1k!==void 0?{cachedInputPer1k:s.cachedInputPer1k}:{},outputPer1k:s.outputPer1k}};if(this.enVuelo.size>=Wf){this.
|
|
937
|
+
registrar({...a,outcome:"dropped"});return}let c=()=>{},u=new Promise(d=>{c=d;}),l={base:a,abortar:new AbortController,decidido:false,reloj:void 0,terminar:c};if(this.enVuelo.add(l),l.reloj=setTimeout(()=>{
|
|
938
|
+
try{l.abortar.abort();}catch{}this.resolverVuelo(l,{...a,outcome:"check_failed"});},Jf),l.reloj.unref?.(),setTimeout(()=>{if(l.decidido)return;let d;try{d=Promise.resolve(this.provider.generate(o.peticion,
|
|
939
|
+
{signal:l.abortar.signal}));}catch(m){d=Promise.reject(m);}d.then(m=>{let f;try{f=this.checkDeLaRespuesta(a,o.peticion,m,s);}catch{f={...a,outcome:"check_failed"};}this.resolverVuelo(l,f);},()=>{this.resolverVuelo(
|
|
940
|
+
l,{...a,outcome:"check_failed"});});},0),this.waitUntil)try{this.waitUntil(u.catch(()=>{}));}catch{}}checkDeLaRespuesta(e,n,r,o){let i=r?.usage,s=i?.inputTokens,a=i?.outputTokens,c=i?.cachedInputTokens??
|
|
941
|
+
0,u=f=>typeof f=="number"&&Number.isSafeInteger(f)&&f>=0;if(!i||i.complete===false||!u(s)||!u(a)||!u(c)||s===0&&a===0)return {...e,outcome:"check_unmeasured"};let l=Math.min(c,s),d=r.finishReason,m=typeof d==
|
|
942
|
+
"string"?/^[a-z_]{1,32}$/.test(d)?d:"other":void 0;return {...e,outcome:"paired",naive:{cost:$u({inputTokens:s,outputTokens:a,cachedInputTokens:l},o),inputTokens:s,cachedInputTokens:l,outputTokens:a,...m!==
|
|
943
|
+
void 0?{finishReason:m}:{},contract:this.contrato(n,r)}}}async resolverVuelo(e,n){if(!e.decidido){if(e.decidido=true,e.reloj&&clearTimeout(e.reloj),this.enVuelo.delete(e),this.registrar(n),this.enVuelo.
|
|
944
|
+
size===0)try{await this.sumidero.enReposo();}catch{}e.terminar();}}registrar(e){try{this.sumidero.encolar(e);}catch{}if(this.onCheck)try{this.onCheck(e);}catch{}}};var Zi=true,Hu=new WeakSet;function Gf(t){typeof t=="object"&&t!==null&&Hu.add(t);}function zu(t){return typeof t=="object"&&t!==null&&Hu.has(t)}function qu(t,e){switch(t){case "none":return Yf();case "inv\
|
|
796
945
|
alid":return e==="malformed"?"BiVelio license key is not a license token (malformed): a BiVelio license key looks like `xxxx.yyyy.zzzz` \u2014 three dot-separated base64url segments, several hundred charac\
|
|
797
946
|
ters long \u2014 did you paste the `bvk_` service-account key by mistake? That one goes in `serviceAccountKey`; the license key is the other value on https://savings.bivelio.com/dashboard/install (license \
|
|
798
947
|
status: invalid)":"BiVelio license key is not valid (it does not verify). Check you pasted the WHOLE key, and that it is the license key from your dashboard \u2014 not the `bvk_` service-account key, which\
|
|
@@ -800,415 +949,559 @@ status: invalid)":"BiVelio license key is not valid (it does not verify). Check
|
|
|
800
949
|
lling status at https://savings.bivelio.com/dashboard/account or write to support@bivelio.com (license status: revoked)";case "stale":return "BiVelio could not confirm your license with the control plan\
|
|
801
950
|
e in time \u2014 this is a connectivity problem, not a billing one: your license is still valid. Allow outbound HTTPS to your `licenseServerUrl` (https://savings.bivelio.com by default) and retry. (license\
|
|
802
951
|
status: stale)";case "expired":case "grace":return `BiVelio license is not active. Renew your subscription at https://savings.bivelio.com/dashboard/account (license status: ${t})`;default:return `BiVelio\
|
|
803
|
-
license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function
|
|
952
|
+
license is not active. See https://savings.bivelio.com/dashboard/account${t?` (license status: ${t})`:""}`}}function Yf(){return "BiVelio license required: none was configured. Pass { licenseKey } \u2014 t\
|
|
804
953
|
he signed token from your subscription, verified offline. This published package has no unlicensed mode. Copy your key and a ready-to-paste snippet at https://savings.bivelio.com/dashboard/install (li\
|
|
805
|
-
cense status: none)"}function
|
|
806
|
-
path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var
|
|
807
|
-
this.config=e,this.deps=
|
|
808
|
-
exploration!=null?{exploracion:e.modelCascade.exploration}:{});let r=
|
|
809
|
-
contrato:(o,i)=>
|
|
954
|
+
cense status: none)"}function Zf(){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 \
|
|
955
|
+
path at all \u2014 pass { licenseKey } instead, from https://savings.bivelio.com/dashboard/install (license status: invalid)"}var $r=class{deps;config;now;generateId;contratosQueIncumplen;verjaDeCache=new Er;espejoDeCache=new Rr;verjaDeCascada;memoriaDelCodebook=new Ar;referenciasDeLider=new WeakMap;noReproducibles=new WeakSet;comprobador;constructor(e,n={}){
|
|
956
|
+
this.config=e,this.deps=Wc(e),this.now=e.now??(()=>Date.now()),this.generateId=e.generateId??(()=>Jt()),this.contratosQueIncumplen=e.constraintMemory??new Set,this.verjaDeCascada=new Ir(e.modelCascade?.
|
|
957
|
+
exploration!=null?{exploracion:e.modelCascade.exploration}:{});let r=Lr(e.verification);this.comprobador=r.activo&&n.verificacion?new jr({ajustes:r,provider:e.provider,precio:o=>this.precioConocido(o),
|
|
958
|
+
contrato:(o,i)=>Qf(o,i),now:this.now,sumidero:n.verificacion,avisar:(o,i)=>this.avisar(o,i)}):void 0;}conVerificacion(e,n,r){return this.comprobador?this.comprobador.decidir(e,n,r):n}cerrarVerificacion(){
|
|
810
959
|
this.comprobador?.cerrar();}async generate(e){this.assertLicensed(),e=this.conPalancasPorDefecto(e);let n={llamadas:0,falloDelProveedor:false,sinContador:0},r;try{r=await this.generateOptimized(e,n);}catch(o){
|
|
811
|
-
if(o instanceof
|
|
812
|
-
r,"optimizado")}generateStream(e,n={},r){let o;try{o=new
|
|
813
|
-
try{if(r&&await r,n.abortado)throw new
|
|
814
|
-
n.entrarEnVivo();let i={llamadas:0,falloDelProveedor:!1,sinContador:0},s;try{s=await this.generateOptimized(e,i,n.sumidero);}catch(a){if(a instanceof
|
|
815
|
-
throw new
|
|
960
|
+
if(o instanceof Je||this.config.failOpen===false||n.falloDelProveedor||n.llamadas>0||zu(o))throw o;return this.conVerificacion(e,await this.failOpenDirect(e,o),"fail-open")}return this.conVerificacion(e,
|
|
961
|
+
r,"optimizado")}generateStream(e,n={},r){let o;try{o=new hn(this.now,n?.signal);}catch(i){let s=new hn(this.now);return s.fallar(i),s.handle}return this.ejecutarStream(e,o,r),o.handle}async ejecutarStream(e,n,r){
|
|
962
|
+
try{if(r&&await r,n.abortado)throw new ye(!1);e=this.conPalancasPorDefecto(e);let o=this.motivoDeEntregaEntera(e);if(o){let a=await this.generate(e);n.completar(a,{vivo:!1,motivo:o});return}this.assertLicensed(),
|
|
963
|
+
n.entrarEnVivo();let i={llamadas:0,falloDelProveedor:!1,sinContador:0},s;try{s=await this.generateOptimized(e,i,n.sumidero);}catch(a){if(a instanceof Je||a instanceof ye)throw a;if(n.sumidero.senal.aborted)
|
|
964
|
+
throw new ye(i.llamadas>0);if(this.config.failOpen===!1||i.falloDelProveedor||i.llamadas>0||zu(a))throw a;let c=this.conVerificacion(e,await this.failOpenDirect(e,a),"fail-open");n.completar(c,{vivo:!1,
|
|
816
965
|
motivo:"fail-open"});return}s=this.conVerificacion(e,s,"optimizado"),n.completar(s,n.sumidero.sirvioEnVivo?{vivo:!0}:{vivo:!1,motivo:"shortcut"});}catch(o){n.fallar(o);}}conPalancasPorDefecto(e){let n=this.
|
|
817
966
|
config.priceLevers;if(!n)return e;let r=e.savings,o=n.deferrable===true&&r?.deferrable===void 0,i=n.standalone===true&&r?.standalone===void 0;return !o&&!i?e:{...e,savings:{...r??{},...o?{deferrable:true}:{},
|
|
818
967
|
...i?{standalone:true}:{}}}}motivoDeEntregaEntera(e){return e.response?.schema!=null?"output-contract":e.savings?.deferrable===true?"deferrable":typeof this.config.provider.generateStream!="function"?"pro\
|
|
819
968
|
vider-without-streaming":null}async llamarProveedor(e,n){n.llamadas+=1;let r;try{r=await this.config.provider.generate(e);}catch(o){throw n.falloDelProveedor=true,o}return r.usage.complete===false&&(n.sinContador+=
|
|
820
|
-
1),r}async llamarProveedorEnStream(e,n,r){if(r.senal.aborted)throw new
|
|
821
|
-
aborted)break;if(s.type==="text")s.delta!==""&&(o+=s.delta,r.texto(s.delta));else if(s.type==="done"){i=s.response;break}}}catch(s){throw r.senal.aborted?new
|
|
822
|
-
senal.aborted?new
|
|
969
|
+
1),r}async llamarProveedorEnStream(e,n,r){if(r.senal.aborted)throw new ye(n.llamadas>0);n.llamadas+=1;let o="",i;try{for await(let s of this.config.provider.generateStream(e,{signal:r.senal})){if(r.senal.
|
|
970
|
+
aborted)break;if(s.type==="text")s.delta!==""&&(o+=s.delta,r.texto(s.delta));else if(s.type==="done"){i=s.response;break}}}catch(s){throw r.senal.aborted?new ye(true):(n.falloDelProveedor=true,s)}if(!i)throw r.
|
|
971
|
+
senal.aborted?new ye(true):(n.falloDelProveedor=true,new Error(`provider "${this.config.provider.id}" stream ended without a final response`));return r.proveedorTermino(),i.usage.complete===false&&(n.sinContador+=
|
|
823
972
|
1),i.text!==o&&(this.avisar(`stream-texto-distinto:${this.config.provider.id}`,`[bvsala] provider "${this.config.provider.id}" streamed text that differs from its final response; the streamed text is \
|
|
824
|
-
what the caller received, so it is what is reported and cached. Its generateStream must end with a done whose response.text equals the concatenated deltas.`),i=
|
|
825
|
-
let
|
|
826
|
-
compressionEconomics);if(!d)return a.record("prefix-cache","skipped",{reason:`no cache read discount for model "${n}" (unrecognised provider, or a declared tier
|
|
827
|
-
|
|
828
|
-
it is a measured saving); pass the tools you want fixed."}),l;if(i)return a.record("prefix-cache","skipped",{reason:"savings.toolDiscovery is on: which schemas
|
|
829
|
-
probe, so the tool block \u2014 which renders first \u2014 varies across requests that would share a prefix fingerprint. Marking would pay the 1.25x write premium for a
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
"
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
e
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
973
|
+
what the caller received, so it is what is reported and cached. Its generateStream must end with a done whose response.text equals the concatenated deltas.`),i=Ta(i,{...i,text:o})),r.sirvioEnVivo=true,i}decidirMarcadoDeCache(e,n,r,o,i,s,a){
|
|
974
|
+
let c=e.savings?.standalone===true&&St(n,Ct(this.config.provider))?Fo(n):null,u=c!==null,l={marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:u,explicitaPorColocador:false,
|
|
975
|
+
colocacion:null},d=Uu(n,this.config.compressionEconomics);if(!d)return a.record("prefix-cache","skipped",{reason:`no cache read discount for model "${n}" (unrecognised provider, or a declared tier tha\
|
|
976
|
+
t does not discount reads): not claiming a cacheable prefix`}),l;if(!o.setIsStable)return a.record("prefix-cache","skipped",{reason:"the tool SET is selected per request; tools render first, so the pr\
|
|
977
|
+
efix cannot hit. Pruning wins here (it is a measured saving); pass the tools you want fixed."}),l;if(i)return a.record("prefix-cache","skipped",{reason:"savings.toolDiscovery is on: which schemas trav\
|
|
978
|
+
el is decided by a non-deterministic probe, so the tool block \u2014 which renders first \u2014 varies across requests that would share a prefix fingerprint. Marking would pay the 1.25x write premium for a pref\
|
|
979
|
+
ix that cannot hit. Turn tool discovery off to reclaim the prefix cache."}),l;let m=null;if(this.config.cacheBreakpoints==="auto"&&!u){let v=this.colocarConEspejo(e,n,r,o,s,d,a);if("marcado"in v)return v.
|
|
980
|
+
marcado;m=v.observacion;}if(s<=0)return {...l,colocacion:m};let f=r.slice(0,s),h=this.tokensFor(this.assemblePromptText(f,o.tools),e),g=this.tokensFor(this.assemblePromptText(r,o.tools),e),p=ne(ve({model:n,
|
|
981
|
+
tools:(o.tools??[]).map(v=>v.id),prefijo:f.map(v=>`${v.role}:${v.content}`)})),y=u?`${p}|explicit`:p,b=this.verjaDeCache.decidir(y,{totalTokens:g,stablePrefixTokens:h,tier:c??d});return a.record("pref\
|
|
982
|
+
ix-cache",b.marcar?"marked":"skipped",{reason:b.razon,stablePrefixTokens:h,breakEvenHitRate:b.umbral,observedHitRate:b.observada,...u?{mode:"explicit"}:{}}),b.marcar?{marcar:true,huella:p,claveDeVerja:y,
|
|
983
|
+
mensajesDePrefijo:s,cacheWriteMultiplier:d.cacheWriteMultiplier,explicita:u,explicitaPorColocador:false,colocacion:m}:{...l,colocacion:m}}colocarConEspejo(e,n,r,o,i,s,a){let c=Ct(this.config.provider),u=e.
|
|
984
|
+
savings?.standalone===void 0&&St(n,c),l=u?Fo(n):null;if(!(s.cacheWriteMultiplier>1&&!u)&&!l)return {observacion:null};let m=tu(r),f=Math.max(m,Math.min(i,r.length)),h=r.length,g=(o.tools??[]).map(F=>F.
|
|
985
|
+
id),p=ve({model:n,tools:g,schema:e.response?.schema??null}),y=eu(p,r),b=y[m],v=this.now(),w=this.espejoDeCache.observar(b,y,v),S=this.espejoDeCache.estadistica(b,v),k={S:m,...f>m?{H:f}:{},T:h},x=F=>this.
|
|
986
|
+
tokensFor(this.assemblePromptText(r.slice(0,F),o.tools),e),E={clase:b,huellas:y,tramos:k,coincidencia:w,enviada:v};if(l){let F=ru({estadistica:S,tramo:l,hayHistorial:f>m});a.record("prefix-cache-place\
|
|
987
|
+
ment",F.explicita?"explicit":"provider-default",{reason:F.razon,breakEvenReuseRate:F.equilibrio,continuedWithin30m:S.T.en30m,samples:S.T.muestras30m});let U={...E,cola:!F.explicita,ttl:"5m",ultimo:F.explicita?
|
|
988
|
+
null:"T",indiceDelUltimo:F.explicita?null:h};if(!F.explicita)return {observacion:U};let V=F.historial?f:m;if(V<=0)return {marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,
|
|
989
|
+
explicita:true,explicitaPorColocador:true,colocacion:{...U,ultimo:null,indiceDelUltimo:null}}};let X=V===m?"S":"H",de=`${b}|explicit|${X}`,D=this.verjaDeCache.decidir(de,{totalTokens:x(h),stablePrefixTokens:x(
|
|
990
|
+
V),tier:l});return a.record("prefix-cache",D.marcar?"marked":"skipped",{reason:D.razon,breakEvenHitRate:D.umbral,observedHitRate:D.observada,mode:"explicit"}),{marcado:{marcar:D.marcar,huella:D.marcar?
|
|
991
|
+
this.huellaDelPrefijo(n,o.tools,r,V):"",claveDeVerja:D.marcar?de:"",mensajesDePrefijo:D.marcar?V:0,cacheWriteMultiplier:1,explicita:true,explicitaPorColocador:true,colocacion:{...U,ultimo:D.marcar?X:null,
|
|
992
|
+
indiceDelUltimo:D.marcar?V:null}}}}let C={S:m>0?x(m):0,H:f>m?x(f):0,T:x(h)},M=jo(n),O=nu({estadistica:S,tramo:s,primaDeUnaHora:M>s.cacheWriteMultiplier?M:null,tokens:C,hayHistorial:f>m,lecturaPrevista:()=>w?
|
|
993
|
+
x(w.indice):0}),T=O.historial&&f>m?f:m,R=O.cola?"T":T>0?T===f&&f>m?"H":"S":null,I=O.cola?h:T>0?T:null;a.record("prefix-cache-placement",R??"none",{reason:O.razon||"fixed placement",boundary:T===0?"non\
|
|
994
|
+
e":T===m?"system":"history",tail:O.cola,ttl:O.ttl,breakEvenReuseRate:O.equilibrio,historyReusedWithin5m:S.H.en5m,continuedWithin5m:S.T.en5m,samples:S.T.muestras5m,providerConfirmedReads:`${S.confirmadas}\
|
|
995
|
+
/${S.predichas}`});let A={...E,cola:O.cola,ttl:O.ttl,ultimo:null,indiceDelUltimo:null};if(R==null||I==null)return {marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,
|
|
996
|
+
explicita:false,explicitaPorColocador:false,colocacion:A}};let j=O.ttl==="1h"?{...s,cacheWriteMultiplier:M}:s,B=`${b}|${T===0?"-":T===m?"S":"H"}${O.cola?"+T":""}@${O.ttl}`,L=this.verjaDeCache.decidir(B,{totalTokens:C.
|
|
997
|
+
T,stablePrefixTokens:O.cola?C.T:T===m?C.S:C.H,tier:j});return a.record("prefix-cache",L.marcar?"marked":"skipped",{reason:L.razon,stablePrefixTokens:O.cola?C.T:T===m?C.S:C.H,breakEvenHitRate:L.umbral,
|
|
998
|
+
observedHitRate:L.observada}),L.marcar?{marcado:{marcar:true,huella:this.huellaDelPrefijo(n,o.tools,r,T),claveDeVerja:B,mensajesDePrefijo:T,cacheWriteMultiplier:s.cacheWriteMultiplier,explicita:false,explicitaPorColocador:false,
|
|
999
|
+
colocacion:{...A,ultimo:R,indiceDelUltimo:I}}}:{marcado:{marcar:false,huella:"",claveDeVerja:"",mensajesDePrefijo:0,cacheWriteMultiplier:1,explicita:false,explicitaPorColocador:false,colocacion:A}}}apuntarEnElEspejo(e,n,r){
|
|
1000
|
+
let o=e.colocacion,i=n.complete!==false,s=Math.max(0,n.cachedInputTokens??0),a=Math.max(0,n.cacheWriteInputTokens??0),c=o.ultimo!=null&&o.indiceDelUltimo!=null,u=o.coincidencia?.indice;if(i&&c&&o.coincidencia&&
|
|
1001
|
+
u!==void 0&&o.indiceDelUltimo>=u&&o.indiceDelUltimo-u<Xc){let l=this.espejoDeCache.estadistica(o.clase,o.enviada);this.espejoDeCache.verificar(o.clase,o.coincidencia,s);let d=this.espejoDeCache.estadistica(
|
|
1002
|
+
o.clase,o.enviada);d.predichas>l.predichas&&r.record("prefix-cache-placement","verified",{predictedRead:o.coincidencia.posicionDelProveedor,providerCacheRead:s,confirmed:d.confirmadas>l.confirmadas,...d.
|
|
1003
|
+
apagada&&!l.apagada?{reason:`the provider's counter confirmed only ${d.confirmadas} of ${d.predichas} predicted cache reads: this traffic goes back to the fixed placement`}:{}});}this.espejoDeCache.registrar(
|
|
1004
|
+
{clase:o.clase,huellas:o.huellas,tramos:o.tramos,enviada:o.enviada,ultimoMarcado:c?o.ultimo:null,posicionDelProveedor:i&&c?s+a:null,ttl:o.ttl});}huellaDelPrefijo(e,n,r,o){return ne(ve({model:e,tools:(n??
|
|
1005
|
+
[]).map(i=>i.id),prefijo:r.slice(0,o).map(i=>`${i.role}:${i.content}`)}))}decidirCascada(e,n,r,o,i=this.now()){let s=r.modelCascade??"off",a={modo:"off",modeloPedido:e.model,modeloServido:e.model,candidato:null,
|
|
1006
|
+
enruta:false,elegible:false,razon:"the model cascade is off",fuerza:"none",bucket:"",economia:null,observada:null,muestras:0,precioBarato:null,tasaDeMuestreo:0};if(s==="off")return a;let c=au({schema:e.response?.
|
|
1007
|
+
schema,tools:e.tools}),u=su(e.model,this.config.modelCascade?.pairs??Bi),l=this.precioConocido(e.model,i),d=u?this.precioConocido(u,i):void 0,m=iu(d,l),f=ne(ve({tenant:n.tenantId,scope:n.authorizationScope,
|
|
1008
|
+
contract:n.contractId,schema:n.schemaVersion,fuerte:e.model,barato:u,tools:n.toolsetHash})),h=this.verjaDeCascada.estado(f),g={modo:s,modeloPedido:e.model,modeloServido:e.model,candidato:u,enruta:false,elegible:false,
|
|
1009
|
+
razon:c.razon,fuerza:c.fuerza,bucket:f,economia:m,observada:h&&h.enrutadas>0?h.escaladas/h.enrutadas:null,muestras:h?.enrutadas??0,precioBarato:d??null,tasaDeMuestreo:0},p=v=>(o.record("model-cascade",
|
|
1010
|
+
s==="on"?"not routed":"not eligible",{reason:v}),{...g,razon:v});if(!c.elegible)return p(c.razon);if(!u)return p(`no cheaper model is paired with "${e.model}"; declare one in createSavingsLayer({ mode\
|
|
1011
|
+
lCascade: { pairs } }) if your provider has one`);if(!m){let v=[...this.precioConocido(e.model,i)?[]:[e.model],...d?[]:[u]];return p(`no known price for ${v.map(w=>`"${w}"`).join(" or ")||"this pair"}\
|
|
1012
|
+
, so the arithmetic that decides whether routing pays cannot be run. The illustrative default price is deliberately NOT used here: it would approve a pair nobody has priced. Pass \`costModels\` for both\
|
|
1013
|
+
models to enable the cascade for them`)}if(!m.viable)return p(m.razon);let y=Math.min(1,Math.max(0,this.config.modelCascade?.shadowSampleRate??0));if(s==="shadow")return o.record("model-cascade","sha\
|
|
1014
|
+
dow",{candidateModel:u,costRatio:m.r,breakEvenEscalationRate:m.equilibrio,verifier:c.fuerza,workload:f,note:"measuring only: the request goes to the model you asked for. The escalation rate is not a q\
|
|
1015
|
+
uality score \u2014 a well-formed answer with wrong content passes the verifier."}),{...g,elegible:true,razon:c.razon,tasaDeMuestreo:y};let b=this.verjaDeCascada.decidir(f,m);return b.enrutar?(this.avisar(
|
|
1016
|
+
`cascada:${e.model}->${u}`,`[bv-sala] model cascade ON: requests for "${e.model}" may be answered by "${u}" when a deterministic gate accepts the answer. The gate checks the SHAPE of the answer agains\
|
|
1017
|
+
t your output contract, never its meaning, so a well-formed answer with wrong content is served and counted as a success. report.model always names the model that answered, and report.qualityStatus re\
|
|
1018
|
+
ads "bounded_degradation".`),o.record("model-cascade","routed",{candidateModel:u,costRatio:m.r,breakEvenEscalationRate:m.equilibrio,observedEscalationRate:b.observada,verifier:c.fuerza,workload:f,reason:b.
|
|
1019
|
+
razon}),{...g,modeloServido:u,enruta:true,elegible:true,razon:b.razon,observada:b.observada,muestras:b.muestras,tasaDeMuestreo:0}):(o.record("model-cascade","off (gate)",{reason:b.razon,observedEscalationRate:b.
|
|
1020
|
+
observada,breakEvenEscalationRate:m.equilibrio}),{...g,elegible:true,razon:b.razon,observada:b.observada,muestras:b.muestras})}devOpen(){return false}exigirLicencia(){this.assertLicensed();}assertLicensed(){
|
|
1021
|
+
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,r=typeof e.reason=="function"?e.reason():
|
|
1022
|
+
void 0;throw new Je(qu(n,r),n)}throw e?new Je(Zf(),"invalid"):new Je(qu("none"),"none")}avisar(e,n){this.config.silenceWarnings||W(e,n);}avisarDeTruncado(e,n,r,o,i){let s=e.response?.maxOutputTokens,a=yn(
|
|
1023
|
+
e)||"(no contractId)",c=i?" The layer has NOTED it: the next requests for this contract will carry their value limits written into the prompt, which is the only thing that can fix it without touching \
|
|
1024
|
+
your cap. If it still gets cut off, the task does not fit the contract: widen the schema and raise the cap with it.":"",u=o===null?" The schema does not bound the response (no `maxLength`/`maxItems`),\
|
|
1025
|
+
so there is no way to know in advance how much it needs: bound it and the cap stops being a guess.":s==null?` The contract allows ~${o} tokens and this request declares no cap, so the cut came from a\
|
|
1026
|
+
PROVIDER cap (the Anthropic API requires \`max_tokens\` and the adapter sends 4096 by default). Declare \`maxOutputTokens\` and the cut stops being a surprise.`:o>s?` The contract allows responses of\
|
|
1027
|
+
up to ~${o} tokens with this model (what its \`maxLength\`/\`maxItems\` permit) and the cap is ${s}: no response that uses what the schema itself permits fits. A cap calibrated with another model is \
|
|
1028
|
+
NOT inherited \u2014 the schema bounds CHARACTERS, which are the same everywhere, and the cap bounds TOKENS, which differ per tokenizer.`:` The contract allows ~${o} tokens and the cap is ${s}, so the\
|
|
1029
|
+
cap is not the problem: this model is writing more than its own schema permits (no structured mode enforces \`maxLength\`).${c}`;this.avisar(`salida-truncada:${a}:${n}`,`[bvsala] The response was cut\
|
|
1030
|
+
off after exhausting \`maxOutputTokens\`${s!=null?` (${s})`:""} with model ${n} and contract "${a}": the provider returned finish_reason "length" and ${r} output tokens, so the JSON does not validate\
|
|
1031
|
+
. NOT retried: with the same cap it would be cut off again, a paid call for the same failure.${u}`);}avisarDePalancasSinConfigurar(e){this.config.silenceWarnings||((e.compression===true||e.compression===
|
|
1032
|
+
"auto")&&!this.config.compressor&&this.avisar("palanca-sin-compresor","[bv-sala] `savings.compression` was requested but this layer has no compressor, so NOTHING is compressed: the long context travel\
|
|
1033
|
+
s and is paid in full. In the report, `report.compression` is ABSENT and `tokens.eliminatedInput` is 0 \u2014 the same as when there was nothing to compress. The compressor is a sidecar because it adds lat\
|
|
1034
|
+
ency and compute that only you should decide to pay for: plug it in with `createSavingsLayer({ compressor })`, any object with `compress({ text })`. If your plan does not include `long_context_compres\
|
|
1035
|
+
sion`, that feature is needed too. The rest of the layer keeps saving as usual."),e.semanticCache&&!this.deps.semanticCache&&this.avisar("palanca-sin-cache-semantica",'[bv-sala] `savings.semanticCache\
|
|
1036
|
+
` was requested but this layer has no semantic cache, so every rephrased question will come out `cache: "miss"` and be paid to the provider again. It is not on by default because it needs an embedder,\
|
|
1037
|
+
which is your own cost and provider: plug it in with `createSavingsLayer({ semanticCache: new InMemorySemanticCache({ embed }) })`. The exact cache and the rest of the layer keep working.'));}async generateOptimized(e,n={
|
|
1038
|
+
llamadas:0,falloDelProveedor:false,sinContador:0},r=null){this.assertLicensed();let o=new sn(this.now),i=new kt,s=mo(e),a=_n(s),c=e.savings??{};this.avisarDePalancasSinConfigurar(c),c.semanticCache&&c.semanticCache!==
|
|
1039
|
+
"include-agentic"&&this.deps.semanticCache&&Vu(s,a)&&this.avisar("semantica-agentica-apagada",'[bv-sala] `savings.semanticCache` is on, but this request is agentic (it declares tools, carries tool cal\
|
|
868
1040
|
ls or results, or holds more than one user turn), so the semantic cache was neither consulted nor written for it. That is the default: two runs of an agent loop can differ only in what a tool returned\
|
|
869
1041
|
, and the guard under the similarity score cannot see that. The exact cache is unaffected. To include agentic requests, set `savings.semanticCache: "include-agentic"` after measuring it on your own tr\
|
|
870
|
-
affic.');let
|
|
871
|
-
join("; ")||"no restrictions",{allowExactCache:a.allowExactCache,allowSemanticCache:a.allowSemanticCache});let
|
|
872
|
-
|
|
873
|
-
"resolver",
|
|
874
|
-
model}))}let p=
|
|
875
|
-
toggles:
|
|
876
|
-
i.referenceRejected=
|
|
877
|
-
outputNotCredited}:{}}),this.finish(e,s,
|
|
878
|
-
modeloServido,deferrable:
|
|
879
|
-
n,e,s,a,
|
|
880
|
-
|
|
881
|
-
asCoalescedFollower(
|
|
882
|
-
run(
|
|
883
|
-
this.referenciasDeLider.get(
|
|
884
|
-
ejected"});return this.asCoalescedFollower(
|
|
885
|
-
i.semanticCache!=="include-agentic"&&this.deps.semanticCache&&
|
|
886
|
-
i.semanticCache&&this.deps.semanticCache&&!h&&
|
|
887
|
-
deps.semanticCache.find(r);if(
|
|
888
|
-
answer,"semantic",s,a,
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
this.
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
1042
|
+
affic.');let u=this.now(),l=this.decidirCascada(e,s,c,o,u),d=this.costModelFor(l.modeloServido,u);o.record("canonicalize","done",{tenant:s.tenantId,contract:s.contractId}),o.record("policy",a.reasons.
|
|
1043
|
+
join("; ")||"no restrictions",{allowExactCache:a.allowExactCache,allowSemanticCache:a.allowSemanticCache});let m=this.tokensFor(this.assembleBaselinePrompt(e),e),f=e.response?.maxOutputTokens??256,h,g=()=>h??=
|
|
1044
|
+
Yi(e);if(i.baselineInput=m,i.baselineOutput=f,i.baselineTools=e.tools?.length??0,c.deterministicResolvers!==false){let v=this.deps.resolvers.try(s);if(v)return i.avoidCall(m,this.tokensFor(v.text,e)),o.record(
|
|
1045
|
+
"resolver",v.resolver,{avoided:true}),this.finish(e,s,{text:v.text,data:v.data,storedAtMs:this.now()},"deterministic",i,d,o,bn(),vn(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(l,{servedModel:e.
|
|
1046
|
+
model}))}let p=ho(s,{servedModel:l.modeloServido});if(a.allowExactCache&&c.exactCache!==false){let v=await this.deps.exactCache.get(p);if(v){let w=this.creditoPorReferencia(Eu(v.meta),{request:e,cascada:l,
|
|
1047
|
+
toggles:c,huella:g,texto:v.text,claveLeida:p,calidad:()=>{let S=e.response?.schema;return !S||le(v.data,S).valid}});return w.ok?i.avoidCallByReference(w.credit):(i.avoidCall(m,this.tokensFor(v.text,e)),
|
|
1048
|
+
i.referenceRejected=w.reason),o.record("exact-cache","hit",{ageMs:this.now()-v.storedAtMs,basis:w.ok?"reference":"estimated",...w.ok?{}:{referenceRejected:w.reason},...w.ok&&w.outputNotCredited?{outputNotCredited:w.
|
|
1049
|
+
outputNotCredited}:{}}),this.finish(e,s,v,"exact",i,d,o,bn(),vn(),this.now()-v.storedAtMs,void 0,void 0,void 0,void 0,this.informeDeCascada(l))}o.record("exact-cache","miss");}let y=_s(s,{servedModel:l.
|
|
1050
|
+
modeloServido,deferrable:c.deferrable===true,toolDiscovery:c.toolDiscovery===true,...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.maxOutputTokens}:{}}),b=async()=>{try{return await this.expensivePath(
|
|
1051
|
+
n,e,s,a,c,i,d,o,p,m,l,r,u)}catch(v){throw (n.falloDelProveedor||n.llamadas>0)&&Gf(v),v}};if(a.allowSingleflight&&c.singleflight!==false){if(r){let S=this.deps.singleflight,k=typeof S.join=="function"?S.join(
|
|
1052
|
+
y):void 0;if(k){let x=await k;return this.noReproducibles.has(x)?(o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),b()):(o.record("singleflight","coalesced",{key:y}),this.
|
|
1053
|
+
asCoalescedFollower(x,m,this.tokensFor(x.text??"",e),d,e))}return o.record("singleflight","skipped (streaming: a streamed request never leads)"),b()}let{value:v,coalesced:w}=await this.deps.singleflight.
|
|
1054
|
+
run(y,b);if(w&&this.noReproducibles.has(v))return o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),b();if(w){o.record("singleflight","coalesced",{key:y});let S=this.creditoPorReferencia(
|
|
1055
|
+
this.referenciasDeLider.get(v)??"absent",{request:e,cascada:l,toggles:c,huella:g,texto:v.text??"",claveLeida:void 0,calidad:()=>v.report.constraints.structurallyValid!==false&&v.report.qualityStatus!=="r\
|
|
1056
|
+
ejected"});return this.asCoalescedFollower(v,m,this.tokensFor(v.text??"",e),d,e,S)}return v}return b()}async expensivePath(e,n,r,o,i,s,a,c,u,l,d,m,f){let h=this.entitled("semantic_cache"),g=null;if(i.
|
|
1057
|
+
semanticCache&&i.semanticCache!=="include-agentic"&&this.deps.semanticCache&&Vu(r,o)&&c.record("semantic-cache",'skipped: agentic traffic (default); set savings.semanticCache: "include-agentic" to inc\
|
|
1058
|
+
lude it'),o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache&&!h&&c.record("semantic-cache","degraded: feature not included in this license"),o.allowSemanticCache&&i.semanticCache&&this.deps.
|
|
1059
|
+
semanticCache&&h){let P=this.deps.semanticCache,_=P.calibrated?await P.lookup(r,{agentic:o.isAgentic}):{hit:await P.find(r),probe:null},N=_.hit;if(g=_.probe,N)return s.avoidCall(l,this.tokensFor(N.record.
|
|
1060
|
+
answer.text,n)),c.record("semantic-cache","hit",{confidence:N.confidence,similarity:N.similarity}),this.finish(n,r,N.record.answer,"semantic",s,a,c,bn(),vn(),N.ageMs,N.confidence,void 0,void 0,void 0,
|
|
1061
|
+
this.informeDeCascada(d,{servedModel:n.model}),void 0,void 0,void 0,{semantico:N});c.record("semantic-cache","miss",g?{calibration:g.reason,score:g.score}:void 0);}let p=i.router===false,y=p?bn():this.deps.
|
|
1062
|
+
router.classify(r);c.record("router",y.executionClass,{confidence:y.confidence,reason:y.reason});let b=this.planearBusquedaNativa(n,i,y.executionClass,p,d,a,c),v=b?b.seleccion:p?this.deps.toolSelector.
|
|
1063
|
+
passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,y.executionClass,r.toolsetHash);if(!b&&So(i.toolSearch).modo==="off"&&this.avisarDeCatalogoRecortado(n,v,d.modeloServido),s.
|
|
1064
|
+
actualTools=v.tools.length,v.droppedIds.length){let P=new Set(v.droppedIds),_=(n.tools??[]).filter(N=>P.has(N.id)).reduce((N,H)=>N+this.tokensFor(Nr(H),n),0);s.eliminate(_),c.record("tool-selector",v.
|
|
1065
|
+
reason,{dropped:v.droppedIds,eliminatedTokens:_});}s.baselineRetrieval=this.config.retriever?y.rounds:0;let w=await Ks({execution:y.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.maxRounds??
|
|
1066
|
+
y.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});s.actualRetrieval=w.rounds,
|
|
1067
|
+
w.retrievedCount>0&&c.record("retrieval",`kept ${w.keptCount}/${w.retrievedCount}`,{rounds:w.rounds});let S=vn(),k=[...n.messages],x=Xi(n.messages),E=false,C=w.docs.length>0?{role:"system",content:`Retri\
|
|
1068
|
+
eved context \u2014 answer using only this evidence and cite sources by [id]:
|
|
895
1069
|
|
|
896
|
-
`+
|
|
897
|
-
${
|
|
1070
|
+
`+w.docs.map((P,_)=>`[${P.source??P.id??`doc${_+1}`}]
|
|
1071
|
+
${P.text}`).join(`
|
|
898
1072
|
|
|
899
|
-
`)}:null,
|
|
900
|
-
JSON limits (not API-enforced): ${
|
|
901
|
-
{model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let
|
|
902
|
-
`:"")+
|
|
903
|
-
disabled; sent compact JSON"});}if(
|
|
904
|
-
{},
|
|
905
|
-
{}},H=0,
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
this.assemblePromptText(
|
|
909
|
-
compressorCostTokens});
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
d
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
1073
|
+
`)}:null,M=yn(n),O=n.response?.maxOutputTokens!=null?Math.floor(n.response.maxOutputTokens*3.2):null,T=this.contratosQueIncumplen.has(M)?Qi(n.response?.schema,"",O):"";if(T&&kn(k,{role:"system",content:`\
|
|
1074
|
+
JSON limits (not API-enforced): ${T}`}),n.structuredData!==void 0){let P=JSON.stringify(n.structuredData),_=this.tokensFor(P,n);if(i.serialization!==false){S=this.deps.formatSelector.choose(n.structuredData,
|
|
1075
|
+
{model:n.model,...n.tokenizer?{tokenizer:n.tokenizer}:{}});let N=this.tokensFor(S.encoded+S.instruction,n);s.compress(_,N),kn(k,{role:"system",content:(S.instruction?S.instruction+`
|
|
1076
|
+
`:"")+S.encoded}),c.record("serialization",S.chosen,{reason:S.reason,jsonTokens:_,chosenTokens:N});}else kn(k,{role:"system",content:P}),c.record("serialization","json-compact",{reason:"format selector\
|
|
1077
|
+
disabled; sent compact JSON"});}if(C&&kn(k,C),(i.compression===true||i.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let P=this.config.compressionEconomics??
|
|
1078
|
+
{},_=Or(n.model,P),N={compressorCostTokens:P.compressorCostTokens??0,...P.minimumContextTokens!=null?{minimumContextTokens:P.minimumContextTokens}:{},...P.minimumNetTokens!=null?{minimumNetTokens:P.minimumNetTokens}:
|
|
1079
|
+
{}},H=0,G=0;for(let te of k)te.role==="system"?H+=1:G+=this.tokensFor(te.content,n);let ae=this.tokensFor(this.assemblePromptText(k,v.tools),n),ke=_o({...N,contextTokens:G,projectedEliminable:G}),ee=0,
|
|
1080
|
+
Y=0,qe=false,xe=ke.reason;if(ke.compress){let te=[];for(let Ie of k){if(Ie.role==="system"){te.push(Ie);continue}let Ut=this.tokensFor(Ie.content,n),Ht=await this.config.compressor.compress({text:Ie.content}),
|
|
1081
|
+
xs=!Ht.skipped&&Ht.fidelityPassed&&ia(Ie.content,Ht.compressed),ws=xs?this.tokensFor(Ht.compressed,n):Ut;xs&&ws<Ut?(te.push({...Ie,content:Ht.compressed}),ee+=Ut,Y+=ws):te.push(Ie);}let ue=this.tokensFor(
|
|
1082
|
+
this.assemblePromptText(te,v.tools),n),eo=_o({...N,contextTokens:G,projectedEliminable:ee-Y}),me=yu({originalTokens:ae,compressedTokens:ue,tier:_,...P.prefix?{prefix:P.prefix}:{},compressorCostTokens:N.
|
|
1083
|
+
compressorCostTokens});Y>=ee?xe="no fidelity-passed net reduction":eo.compress?me.comprimir?(qe=true,xe=me.razon,E=te.slice(0,x).some((Ie,Ut)=>Ie.content!==k[Ut]?.content),k=te,s.compress(ee,Y)):xe=me.razon:
|
|
1084
|
+
xe=eo.reason;}qe||(ee=0,Y=0),c.record("compression",qe?"applied":"skipped",{reason:xe,before:ee,after:Y,contextTokens:G,promptTokens:ae,cacheTierMinimum:_.minimumCacheTokens,protectedSystemMessages:H,prefixRewritten:E}),
|
|
1085
|
+
s.compressionReport={originalTokens:ee,compressedTokens:Y,protectedSpans:H,fidelityPassed:true};}if(i.elision!==false&&o.allowElision&&this.entitled("tool_result_elision")){let P=bu(k);if(P.indices.length>0){
|
|
1086
|
+
let _=this.tokensFor(Gi,n),N=0;for(let H of P.indices){let G=this.tokensFor(k[H].content,n);N+=Math.max(0,G-_);}(P.indices.some(H=>H<x)&&(E=true),k=vu(k,P.indices),s.eliminate(N),s.elididoLocal+=N),c.
|
|
1087
|
+
record("elision","applied",{elided:P.indices.length,eliminatedTokens:N,grossBytes:P.bytesOriginales,live:Zi});}else c.record("elision","skipped",{reason:"no old/large tool_result over the a\
|
|
1088
|
+
ge\xD7size threshold"});}let R=am(this.config.toolOutputCompaction,i.toolOutputCompaction);if(R&&!this.entitled("long_context_compression")&&c.record("tool-output-compaction","degraded: feature not inc\
|
|
1089
|
+
luded in this license"),R&&o.allowCompression&&this.entitled("long_context_compression")){let P=la(k,R),_=0,N=0,H=0,G=0,ae={};if(P.compactados.length>0){let ee=k.slice();for(let Y of P.compactados){let qe=k[Y.
|
|
1090
|
+
indice],xe=this.tokensFor(qe.content,n),te=this.tokensFor(Y.texto,n);ee[Y.indice]={...qe,content:Y.texto},_+=xe,N+=te,Y.enLaCola?H+=Math.max(0,xe-te):G+=Math.max(0,xe-te);for(let ue of Y.aplicadas)ae[ue]=
|
|
1091
|
+
(ae[ue]??0)+1;}k=ee,s.compress(_,N),s.compactedLocal+=Math.max(0,_-N);}let ke=Or(n.model,this.config.compressionEconomics);c.record("tool-output-compaction",P.compactados.length>0?"applied":"skipped",{compacted:P.
|
|
1092
|
+
compactados.length,before:_,after:N,tailSavedTokens:H,replayedSavedTokens:G,transforms:ae,fileViewsKeptVerbatim:P.vistasDeFichero,exceptedTools:P.exceptuados,cacheWriteMultiplier:ke.cacheWriteMultiplier,
|
|
1093
|
+
cacheReadMultiplier:ke.cacheReadMultiplier,note:"counted in tokens.compressedInput only; never priced into savings or commission. each tail token saved is one token fewer written now and re-read on ev\
|
|
1094
|
+
ery later turn"});}let I=n.response?.schema,A=I&&i.outputCodebook===true?pu(I,P=>this.tokensFor(P,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,yn(n),i.outputCodebookMeasuredOutputDeltaTokens)}):
|
|
1095
|
+
null;A&&c.record("output-codebook",A.applied?"applied":"skipped",{reason:A.reason,...A.applied?{renamedKeys:A.plan.renamedKeys,codedEnumValues:A.plan.codedEnumValues,schemaTokensOriginal:A.plan.schemaTokensOriginal,
|
|
1096
|
+
schemaTokensCompact:A.plan.schemaTokensCompact,modelledShapeSavingTokens:A.plan.modelledShapeSavingTokens,measuredOutputDeltaTokens:A.plan.measuredOutputDeltaTokens,outputDeltaProvenance:A.plan.outputDeltaProvenance,
|
|
1097
|
+
breakEvenOutputDeltaTokens:A.plan.breakEvenOutputDeltaTokens,netSavingUsd:A.plan.netSavingUsd,pricedForModel:d.modeloServido}:{}});let j=A?.applied?A.plan.compactSchema:I,B=j?oa(d.modeloServido,j,this.
|
|
1098
|
+
deps.constraintBackends):{backend:"none",reason:"no output contract"};c.record("constraints",B.backend,{reason:B.reason});let L=this.decidirMarcadoDeCache(n,d.modeloServido,k,b?{tools:b.prefijo,setIsStable:v.
|
|
1099
|
+
setIsStable}:v,i.toolDiscovery===true&&!b,E?Xi(k,true):x,c),F=this.now();if(m?.senal.aborted)throw new ye(e.llamadas>0);let U=b?this.sinDescubrimientoPorBusquedaNativa(i,v.tools,c):await this.descubrirHerramientas(
|
|
1100
|
+
e,n,i,v.tools,k,s,a,c),V=U.tools;s.actualTools=V.length;let X={messages:k,...V.length?{tools:V}:{},...j?{schema:j}:{},...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:
|
|
1101
|
+
{},...n.temperature!=null?{temperature:n.temperature}:{},...n.seed!=null?{seed:n.seed}:{},...i.deferrable?{deferrable:true}:{},...L.explicita?{explicitCacheWrites:true}:{},...b?{toolSearch:b.plan}:{},constraintBackend:B.
|
|
1102
|
+
backend},de={model:d.modeloServido,...X,...L.marcar?{stablePrefixMessages:L.mensajesDePrefijo,promptCacheKey:L.huella,...L.colocacion&&!L.explicita&&(L.colocacion.cola||L.colocacion.ttl!=="5m")?{cachePlacement:{
|
|
1103
|
+
tail:L.colocacion.cola,ttl:L.colocacion.ttl}}:{}}:{}},D,Tn=false,ms={...e};try{D=m?await this.llamarProveedorEnStream(de,e,m):await this.llamarProveedor(de,e);}catch(P){if(!this.respaldaFaltaDeCapacidad(i,
|
|
1104
|
+
P,m))throw P;Object.assign(e,ms),Tn=true,c.record("deferred-tier","capacity-fallback",{error:P instanceof Error?P.message.slice(0,200):String(P),reason:'the cheaper tier had no capacity; repeated once a\
|
|
1105
|
+
t the standard tier and price, as configured with priceLevers.onCapacityError: "standard"'});let{deferrable:_,...N}=de;D=await this.llamarProveedor(N,e);}let hs=Zn(D),ml=D.servedServiceTier;b&&c.record(
|
|
1106
|
+
"tool-search","provider",{searches:D.toolSearch?.searches??null,loaded:D.toolSearch?.loaded??[],errors:D.toolSearch?.errors??0,reason:D.toolSearch?"what the provider's tool search did in this call; it\
|
|
1107
|
+
s cost is in the provider's counter and credited to no ledger":"the adapter did not report what the search did"}),s.actualLlm+=1;let Qr=P=>{if(!A?.applied)return P;let _=Ne(P);return _.ok?JSON.stringify(
|
|
1108
|
+
A.plan.expand(_.value)):P},pe=Qr(D.text),Be=D.usage,rt=false;if(d.enruta){let P=zi({texto:pe,schema:I,finishReason:D.finishReason,pidioHerramientas:(D.toolCalls?.length??0)>0});this.verjaDeCascada.registrar(
|
|
1109
|
+
d.bucket,!P.acepta),c.record("model-cascade",P.acepta?"accepted":"escalating",{servedModel:d.modeloServido,reason:P.motivo,checks:P.comprobaciones}),P.acepta||(rt=true,s.cascadeAttempt(D.usage,d.precioBarato??
|
|
1110
|
+
a,L.marcar&&L.cacheWriteMultiplier>1?1:tn(d.modeloServido)),s.actualLlm+=1,D=await this.llamarProveedor({model:n.model,...X},e),pe=Qr(D.text));}let Re=rt?n.model:d.modeloServido,zt=rt?this.costModelFor(
|
|
1111
|
+
n.model,f):a;s.actualInput+=D.usage.inputTokens,s.actualOutput+=D.usage.outputTokens;let hl=D.usage,gl=D.servedServiceTier,bl=D.structuredNatively===true,Pn=Zn(D),gs;A?.applied&&c.record("output-codeboo\
|
|
1112
|
+
k",Ne(D.text).ok?"expanded":"not-expanded (response was not JSON)",Ne(D.text).ok?{localOutputTokensCompact:this.tokensFor(D.text,n),localOutputTokensExpanded:this.tokensFor(pe,n),creditedLedger:"none",
|
|
1113
|
+
note:"local count of the served answer in both shapes; not credited to any ledger"}:{}),I&&B.backend==="provider-native"&&D.structuredNatively===false&&(B={backend:"none",reason:"provider did not enforce\
|
|
1114
|
+
the contract natively; the schema travelled in the prompt and the layer is the only validator"},c.record("constraints","none",{downgradedFrom:"provider-native",reason:B.reason})),s.sentInputLocal=this.
|
|
1115
|
+
tokensFor(this.assemblePromptText(k,V),n),s.removedInputLocal=Math.max(0,l-s.sentInputLocal-s.elididoLocal-s.compactedLocal);let vl=s.sentInputLocal;s.sentInputLocal+=U.tokensLocalesDelSondeo,s.estimatorExact=
|
|
1116
|
+
this.estimatorEsExacto(n),D.usage.cachedInputTokens&&s.providerCached(D.usage.cachedInputTokens);let bs=tn(Re),yl=!rt&&L.marcar&&L.cacheWriteMultiplier>1;if(bs>1&&!yl&&(D.usage.cacheWriteInputTokens??
|
|
1117
|
+
0)>0&&s.providerCacheWritePremium(D.usage.cacheWriteInputTokens??0,bs,zt),L.marcar&&Be.complete===false)c.record("prefix-cache","not measured: the provider reported no usage for this call");else if(L.marcar){
|
|
1118
|
+
let P=Math.max(0,Be.cacheWriteInputTokens??0),_=Math.min(P,Math.max(0,Be.cacheWrite1hInputTokens??(L.colocacion?.ttl==="1h"?P:0)));s.cacheWritePremium(P-_,L.cacheWriteMultiplier,d.precioBarato??a),_>0&&
|
|
1119
|
+
s.cacheWritePremium(_,jo(d.modeloServido),d.precioBarato??a),this.verjaDeCache.registrar(L.claveDeVerja,Be),c.record("prefix-cache","measured",{cacheRead:Be.cachedInputTokens??0,cacheWritePremiumTokens:Be.
|
|
1120
|
+
cacheWriteInputTokens??0,..._>0?{cacheWrite1hTokens:_}:{}});}L.colocacion&&this.apuntarEnElEspejo(L,Be,c);let mt=null;if(d.modo==="shadow"&&d.elegible&&d.candidato&&d.precioBarato&&im(u,d.tasaDeMuestreo))
|
|
1121
|
+
try{let P=await this.llamarProveedor({model:d.candidato,...X},e);s.actualLlm+=1;let _=s.extraCostUsd;s.cascadeAttempt(P.usage,d.precioBarato,tn(d.candidato));let N=Qr(P.text),H=zi({texto:N,schema:I,finishReason:P.
|
|
1122
|
+
finishReason,pidioHerramientas:(P.toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!H.acepta);let G=H.acepta?cu(N,pe):null;mt={coste:s.extraCostUsd-_,divergio:G?G.divergen:null},c.record(
|
|
1123
|
+
"model-cascade",H.acepta?"sample accepted":"sample escalated",{candidateModel:d.candidato,reason:H.motivo,sampleCost:mt.coste,...G?{diverged:G.divergen,divergence:G.motivo}:{},note:"measurement only: \
|
|
1124
|
+
this answer was NEVER served. The escalation rate it feeds is a money figure, not a quality one"});}catch(P){c.record("model-cascade","sample failed (measurement only; the answer is unaffected)",{error:P instanceof
|
|
1125
|
+
Error?P.message:String(P)});}let Cn=pe,ht=true,Fe={},qt=(D.toolCalls?.length??0)>0;if(qt&&(ht=null,I&&c.record("validation","n/a: model requested tool calls (the output contract applies to the final answ\
|
|
1126
|
+
er)")),I&&!qt){let P=Ne(pe),_=P.ok?le(P.value,I):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},N=false;P.ok&&P.rescatado!=null&&_.valid&&(pe=P.rescatado,N=true,c.record("validation","rescued-loca\
|
|
1127
|
+
lly",{reason:"the model wrapped valid JSON in prose or a markdown fence; it was extracted locally instead of paying a repair call"})),!_.valid&&sm(_.errors)&&this.contratosQueIncumplen.add(yn(n));let H=D.
|
|
1128
|
+
finishReason==="length",G=!_.valid&&_.errors.some(ae=>/not a valid regular expression/.test(ae.message));if(!_.valid&&G)c.record("validation","repair-skipped",{reason:"schema defect (uncompilable patt\
|
|
1129
|
+
ern); no output can satisfy it, a retry is a wasted call",errors:_.errors}),this.avisar("esquema-roto","[bvsala] The response contract has a `pattern` that is not a valid regex, so no response can sat\
|
|
1130
|
+
isfy it. NOT retried (it would be a paid call for the same failure). Fix the schema's `pattern`."),Fe.reparacion={outcome:"skipped",skipReason:"schema_defect"};else if(!_.valid&&H){let ae=lu(I,Y=>this.
|
|
1131
|
+
tokensFor(Y,n)),ke=n.response?.maxOutputTokens??null,ee=ae!==null&&ke!=null&&ae<=ke;ee&&this.contratosQueIncumplen.add(yn(n)),c.record("validation","repair-skipped",{reason:"output truncated by maxOut\
|
|
1132
|
+
putTokens; a retry with the same cap would truncate again",maxOutputTokens:n.response?.maxOutputTokens??null,outputTokens:D.usage.outputTokens,model:Re,...ae!==null?{schemaAllowsTokens:ae}:{},learnedValueLimits:ee}),
|
|
1133
|
+
this.avisarDeTruncado(n,Re,D.usage.outputTokens,ae,ee),Fe.reparacion={outcome:"skipped",skipReason:"output_truncated"};}else if(!_.valid&&B.backend==="none"){let ae=_.errors.slice(0,5).map(me=>`- ${me.
|
|
1134
|
+
path}: ${me.message}`).join(`
|
|
1135
|
+
`),ke=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
|
|
951
1136
|
|
|
952
1137
|
Previous reply:
|
|
953
|
-
${
|
|
1138
|
+
${pe}
|
|
954
1139
|
|
|
955
1140
|
Problems found:
|
|
956
|
-
${
|
|
1141
|
+
${ae}
|
|
957
1142
|
|
|
958
|
-
Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],
|
|
959
|
-
round(
|
|
960
|
-
|
|
961
|
-
invalid answer is served as-is and reported as invalid",errors:
|
|
962
|
-
bvsala] The answer did not satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${
|
|
963
|
-
actual}, repair ~$${
|
|
964
|
-
uest carrying both tools and an output contract; see the adapter warning for the cheaper shapes.`),
|
|
965
|
-
"validation","repair-attempt",{errors:
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
invalid"};}}else
|
|
969
|
-
d",errores:
|
|
970
|
-
|
|
971
|
-
amount,basis:"estimated"}:{},creditedLedger:"none",reason:
|
|
972
|
-
servedTier?{servedTier:
|
|
973
|
-
|
|
974
|
-
baselineInput:l,codebookAplicado:
|
|
975
|
-
|
|
976
|
-
length-n.messages.length,requestId:
|
|
977
|
-
|
|
978
|
-
"reference","not-written",{reason:
|
|
979
|
-
|
|
980
|
-
cannot replay":"skipped: answered with a reduced tool view (tool discovery), so it must not be replayed");let
|
|
981
|
-
null?
|
|
982
|
-
i.semanticCache&&this.deps.semanticCache?await this.deps.semanticCache.store(r,
|
|
983
|
-
on the model the caller asked for")
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
{}}}
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
o.map(
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
(m.
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
(
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
e
|
|
1012
|
-
|
|
1013
|
-
the
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
it"}
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
s
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1143
|
+
Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],ee=this.tokensFor(this.assemblePromptText(ke),n),Y=s.sentInputLocal>0?s.actualInput/s.sentInputLocal:1,qe=Math.
|
|
1144
|
+
round(Y*ee),xe=Math.min(D.usage.outputTokens,n.response?.maxOutputTokens??Number.POSITIVE_INFINITY),te=qe/1e3*zt.inputPer1k+xe/1e3*zt.outputPer1k,ue=this.config.skipRepairAboveBaseline?s.estimateCost(
|
|
1145
|
+
zt):void 0;if(ue!=null&&ue.baselineEstimate>0&&ue.actual+te>ue.baselineEstimate&&ue!=null)c.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the\
|
|
1146
|
+
invalid answer is served as-is and reported as invalid",errors:_.errors,baselineUsd:ue.baselineEstimate,actualUsd:ue.actual,repairEstimateUsd:te}),this.avisar("reparacion-mas-cara-que-el-baseline",`[\
|
|
1147
|
+
bvsala] The answer did not satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${ue.baselineEstimate}, already spent ~$${ue.
|
|
1148
|
+
actual}, repair ~$${te.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 req\
|
|
1149
|
+
uest carrying both tools and an output contract; see the adapter warning for the cheaper shapes.`),Fe.reparacion={outcome:"skipped",skipReason:"would_cost_more_than_no_layer"};else {s.retries=1,c.record(
|
|
1150
|
+
"validation","repair-attempt",{errors:_.errors}),D=await this.llamarProveedor({model:Re,messages:ke,schema:I,...n.response?.maxOutputTokens!=null?{maxOutputTokens:n.response.maxOutputTokens}:{}},e),gs=
|
|
1151
|
+
D.usage,s.actualLlm+=1,s.actualInput+=D.usage.inputTokens,s.actualOutput+=D.usage.outputTokens,s.repairOutput+=D.usage.outputTokens,s.repairInput+=D.usage.inputTokens,s.sentInputLocal+=ee,pe=D.text;let me=Ne(
|
|
1152
|
+
pe);_=me.ok?le(me.value,I):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},me.ok&&(Cn=me.value,me.rescatado!=null&&_.valid&&(pe=me.rescatado)),Fe.reparacion={outcome:_.valid?"repaired":"still_\
|
|
1153
|
+
invalid"};}}else P.ok&&(Cn=P.value);ht=_.valid,!_.valid&&Fe.reparacion===void 0&&(Fe.reparacion={outcome:"skipped",skipReason:"decode_time_constraint"}),Fe.validacion={resultado:_.valid?"passed":"faile\
|
|
1154
|
+
d",errores:_.errors.length,desenvuelto:N},c.record("validation",ht?"valid":"invalid");}let kl=this.now()-F,xl=tm(Cn),gt={text:pe,data:Cn,rendered:xl,storedAtMs:this.now()},ze=this.informeDeDiferido(i,D,
|
|
1155
|
+
Re,Tn),ot=this.informeDeEscrituras(i,hs,Be,ml,d.modeloServido,L.marcar,L.explicitaPorColocador);ot&&c.record("cache-writes",ot.mode,{breakpoints:ot.breakpoints,...ot.avoidedWritePremium?{avoidedWritePremium:ot.
|
|
1156
|
+
avoidedWritePremium.amount,basis:"estimated"}:{},creditedLedger:"none",reason:ot.reason}),ze&&c.record("deferred-tier",ze.credited?"credited":"not-credited",{...ze.requestedTier?{requestedTier:ze.requestedTier}:
|
|
1157
|
+
{},...ze.servedTier?{servedTier:ze.servedTier}:{},creditedLedger:"none",reason:ze.reason});let wl=U.aplicado,vs=D.finishReason==="length",Xr=D.replayable===false,bt=ht!==false&&!qt&&!wl&&!vs&&!Xr,ys=this.generateId(),
|
|
1158
|
+
fe;try{fe=Cu({contadorSimulado:Oo(this.config.provider),usoPrimario:hl,usoReparacion:gs,tierServido:gl,eliminatedInput:s.eliminatedInput,compressedInput:s.compressedInput,elididoLocal:s.elididoLocal,sentLocalSinSondeo:vl,
|
|
1159
|
+
baselineInput:l,codebookAplicado:A?.applied===!0,tokensDelSondeo:U.tokensLocalesDelSondeo,sondeoAplicado:U.aplicado,busquedaNativa:b!==null,hayEsquema:I!=null,esquemaNativo:bl,esquemaEnFormatoNativo:Pn?.
|
|
1160
|
+
esquemaEnFormatoNativo===!0&&j===I,esquemaEstricto:Pn?.esquemaEstricto===!0,esquemaPorPrompt:Pn?.esquemaPorPrompt===!0,piezasDelAdaptador:Pn?.piezasDelAdaptador??0,modeloPedido:n.model,modeloServido:Re,
|
|
1161
|
+
cacheable:bt,mensajesDeLaCapa:k.length-n.messages.length,requestId:ys,at:this.now(),textoServido:pe,huella:()=>Yi(n)});}catch{fe="fingerprint-failed";}let ks=bt&&o.allowExactCache&&i.exactCache!==false;typeof fe==
|
|
1162
|
+
"object"?c.record("reference","written",{inputTokens:fe.inputTokens,outputTokens:fe.outputTokens,layerInsertions:fe.layerInsertions,...fe.reasoningTokens!==void 0?{reasoningTokens:fe.reasoningTokens}:
|
|
1163
|
+
{},exactCache:ks}):c.record("reference","not-written",{reason:fe});try{bt||c.record("cache-write",qt?"skipped: tool-call turn (an action request must not be replayed from cache)":ht===!1?"skipped: res\
|
|
1164
|
+
ponse fails its output contract":vs?'skipped: answer cut off by the output cap (finish_reason "length"); replaying half an answer would bill it as a 100% avoided call':Xr?"skipped: the provider answer\
|
|
1165
|
+
carries content this layer cannot replay":"skipped: answered with a reduced tool view (tool discovery), so it must not be replayed");let P=rt?ho(r,{servedModel:Re}):u;if(ks){let N=this.config.exactCacheTtlMs??
|
|
1166
|
+
864e5,H=o.maxCacheAgeMs==null?N:Math.min(N,o.maxCacheAgeMs);await this.deps.exactCache.set(P,typeof fe=="object"?{...gt,meta:{...gt.meta??{},reference:{...fe,cacheKey:P}}}:gt,H);}let _=Re!==n.model;bt&&
|
|
1167
|
+
!_&&o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache?await this.deps.semanticCache.store(r,gt):bt&&_&&i.semanticCache&&c.record("cache-write","semantic write skipped: a cheaper model ans\
|
|
1168
|
+
wered, and this cache keys on the model the caller asked for"),g&&this.deps.semanticCache&&(bt&&!_&&o.allowSemanticCache&&i.semanticCache?(c.record("semantic-calibration","label requested",{reason:g.reason,
|
|
1169
|
+
score:g.score}),this.deps.semanticCache.observe(g,gt)):c.record("semantic-calibration","no label: the cache would not store this answer"));}catch(P){c.record("cache-write","failed (non-fatal; answer al\
|
|
1170
|
+
ready served)",{error:P instanceof Error?P.message:String(P)});}s.callsWithoutUsage=e.sinContador;let Vt=this.finish(n,r,gt,"miss",s,zt,c,y,S,void 0,void 0,ht,B.backend,kl,this.informeDeCascada(d,{servedModel:Re,
|
|
1171
|
+
...d.enruta?{escalated:rt}:{},...d.elegible&&d.precioBarato?{estimatedSwapSaving:om(s,rt,d.precioBarato,this.costModelFor(n.model,f))}:{},...mt?{sampled:true,sampleCost:dt(mt.coste),...mt.divergio!==null?
|
|
1172
|
+
{divergedOnSample:mt.divergio}:{}}:{},...s.cascadeInput>0||s.cascadeOutput>0?{cascadeInputTokens:s.cascadeInput,cascadeOutputTokens:s.cascadeOutput}:{}}),ze,ys,ot,{...Fe,final:{...D.finishReason!==void 0?
|
|
1173
|
+
{finishReason:D.finishReason}:{},...n.response?.maxOutputTokens!=null?{topeDelLlamante:n.response.maxOutputTokens}:{}}});return typeof fe=="object"&&this.referenciasDeLider.set(Vt,fe),Xr&&this.noReproducibles.
|
|
1174
|
+
add(Vt),qt&&(Vt.toolCalls=D.toolCalls),D.finishReason!==void 0&&(Vt.finishReason=D.finishReason),Vt}planearBusquedaNativa(e,n,r,o,i,s,a){let c=So(n.toolSearch),u=e.tools??[];if(c.modo==="off"||u.length===
|
|
1175
|
+
0)return null;let l=Js(u,r==="TOOL_ACTION",o),d=Ws({opciones:c,capacidad:zo(this.config.provider),modelo:i.modeloServido,herramientas:l.map(g=>({id:g.id,tokens:this.tokensFor(Nr(g),e)})),hayContrato:e.
|
|
1176
|
+
response?.schema!=null,cascadaActiva:i.modo!=="off",precio:s,lecturaDeCache:this.lecturaDeCacheDe(i.modeloServido,s)});if(a.record("tool-search",d.aplicar?"native":"selector",{mode:c.modo,variant:d.variante,
|
|
1177
|
+
reason:d.razon,deferred:d.diferidas,deferredTokens:d.tokensDiferidos,alwaysLoaded:d.siempreCargadas,...d.ahorroDelPrefijo!=null?{prefixSavingPerRequest:d.ahorroDelPrefijo}:{},...d.costeDeUnaBusqueda!=
|
|
1178
|
+
null?{worstCaseSearchCost:d.costeDeUnaBusqueda}:{}}),!d.aplicar)return null;let m=new Set(l.map(g=>g.id)),f=new Set(d.siempreCargadas),h=c.siempreCargadas.filter(g=>u.some(p=>p.id===g));return {seleccion:{
|
|
1179
|
+
tools:l,droppedIds:u.filter(g=>!m.has(g.id)).map(g=>g.id),reason:d.razon,setIsStable:h.every(g=>m.has(g))},prefijo:l.filter(g=>f.has(g.id)),plan:{variant:d.variante,alwaysLoaded:d.siempreCargadas}}}lecturaDeCacheDe(e,n){
|
|
1180
|
+
let r=Uu(e,this.config.compressionEconomics)?.cacheReadMultiplier??1,o=n.cachedInputPer1k!=null&&n.inputPer1k>0?n.cachedInputPer1k/n.inputPer1k:void 0;return o!=null?Math.min(o,r):r}sinDescubrimientoPorBusquedaNativa(e,n,r){
|
|
1181
|
+
return e.toolDiscovery===true&&r.record("tool-discovery","skipped (native tool search applies)",{reason:"the provider's tool search already keeps unused schemas out of the prompt, with no second call an\
|
|
1182
|
+
d without moving the cached prefix"}),{tools:n,tokensLocalesDelSondeo:0,aplicado:false}}avisarDeCatalogoRecortado(e,n,r){let o=e.tools??[];n.droppedIds.length===0||!Xt(o)||zo(this.config.provider)===void 0||
|
|
1183
|
+
!wo(r)||this.avisar("catalogo-recortado-con-busqueda-nativa",`[bv-sala] Your tool catalogue declares no \`intents\` or \`risk\`, so the tool selector has nothing to select on and sent only the first ${n.
|
|
1184
|
+
tools.length} of ${o.length} tools: the model cannot call the others. This provider and model support native tool search: \`savings: { toolSearch: "auto" }\` sends all of them deferred and lets the mode\
|
|
1185
|
+
l search, without breaking the prompt cache. Its effect is the provider's and the layer credits nothing for it.`);}async descubrirHerramientas(e,n,r,o,i,s,a,c){let u={tools:o,tokensLocalesDelSondeo:0,aplicado:false};
|
|
1186
|
+
if(r.toolDiscovery!==true)return u;if(o.length<2)return c.record("tool-discovery","skipped (nothing to discover)",{candidates:o.length}),u;let l=p=>this.tokensFor(Nr(p),n),d=o.map(wu),m=xu({promptTokens:this.
|
|
1187
|
+
tokensFor(this.assemblePromptText(i),n),esquemasCompletos:o.reduce((p,y)=>p+l(y),0),descriptoresLigeros:d.reduce((p,y)=>p+l(y),0),esquemasDeLaSegunda:Tu(o.map(p=>({risk:p.risk,tokens:l(p)})),3),salidaFinal:n.
|
|
1188
|
+
response?.maxOutputTokens??256,salidaDelSondeo:96,precio:a});if(!m.aplicar)return c.record("tool-discovery","skipped (not worth a second call)",{reason:m.razon,oneCall:m.costeDeUnaLlamada,twoCalls:m.costeDeDosLlamadas}),
|
|
1189
|
+
u;let f,h=this.tokensFor(this.assemblePromptText(i,d),n);try{f=await this.llamarProveedor({model:n.model,messages:i,tools:d,maxOutputTokens:96,...n.temperature!=null?{temperature:n.temperature}:{},...n.
|
|
1190
|
+
seed!=null?{seed:n.seed}:{}},e);}catch(p){return c.record("tool-discovery","failed (falling back to a single call with every schema)",{error:p instanceof Error?p.message:String(p)}),u}s.actualLlm+=1,s.
|
|
1191
|
+
actualInput+=f.usage.inputTokens,s.actualOutput+=f.usage.outputTokens,s.discoveryInput+=f.usage.inputTokens,s.discoveryOutput+=f.usage.outputTokens;let g=Su((f.toolCalls??[]).map(p=>p.name),o,3);return g.
|
|
1192
|
+
reconocidos.length===0?(c.record("tool-discovery","degraded: probe named no known tool",{finishReason:f.finishReason??null,...g.ignorados.length?{unknownNames:g.ignorados}:{}}),{tools:o,tokensLocalesDelSondeo:h,
|
|
1193
|
+
aplicado:false}):(c.record("tool-discovery","applied (two provider calls)",{chosen:g.reconocidos,sent:g.tools.map(p=>p.id),candidates:o.length,...g.ignorados.length?{unknownNames:g.ignorados}:{}}),{tools:g.
|
|
1194
|
+
tools,tokensLocalesDelSondeo:h,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,
|
|
1195
|
+
creditedLedger:"none",...e.candidato?{candidateModel:e.candidato}:{},...e.economia?{costRatio:gn(e.economia.r),breakEvenEscalationRate:gn(e.economia.equilibrio),targetEscalationRate:gn(e.economia.escaladoMaximo)}:
|
|
1196
|
+
{},...e.bucket?{workload:e.bucket}:{},...e.observada!=null?{escalationRate:gn(e.observada),escalationSamples:e.muestras}:{},...n,requestedModel:e.modeloPedido}}informeDeDiferido(e,n,r,o=false){if(e.deferrable!==
|
|
1197
|
+
true)return;let i=Zn(n),s=i?.origen??null,a=n.servedServiceTier;if(o)return {...Ct(this.config.provider)!==void 0?{requestedTier:wt}:{},...a?{servedTier:a}:{},credited:false,capacityFallback:true,creditedLedger:"\
|
|
1198
|
+
none",latency:"the cheaper tier refused the request for lack of capacity, and it was repeated once at the standard tier: the wait is the refused attempt plus a standard-tier call.",reason:'the cheaper\
|
|
1199
|
+
tier had no capacity (HTTP 429 or 503), so, as configured with priceLevers.onCapacityError: "standard", the request was repeated once at the standard tier and price; the refused attempt is not counte\
|
|
1200
|
+
d as a call and nothing is credited'};let c=n.requestedServiceTier,u={...c?{requestedTier:c}:{},...a?{servedTier:a}:{},credited:false,creditedLedger:"none",latency:va(c,s),reason:""};if(!c)return {...u,reason:ba};
|
|
1201
|
+
let l=this.precioDelCliente(r),d=Gn({modelo:r,uso:n.usage,tierServido:a,origen:s,...i?.tierLeidoDe?{tierLeidoDe:i.tierLeidoDe}:{},...l?{precioDelCliente:l}:{},ahoraMs:this.now()});if(!d.ok){let m=d.motivo===
|
|
1202
|
+
"no-tier-price"&&s==="openai"&&ga(r,s,this.now())?"; this model's deferred discount is published for the provider's batch API instead: send such requests with layer.batches.submit()":"";return {...u,reason:rm(
|
|
1203
|
+
d.motivo,c,a)+m}}return {...u,credited:true,discountRate:gn(d.factorEfectivo),estimatedTierSaving:d.importe,tierSaving:{amount:d.importe,basis:d.basis,standardCost:dt(d.costeEstandar),appliedCost:dt(d.costeAplicado),
|
|
1204
|
+
pricesCheckedOn:d.consultado,basisReason:d.motivoBasis},reason:`the provider reports serving the "${a}" tier; this call's usage was priced at the standard and at the "${a}" published rate cards, compo\
|
|
1205
|
+
nent by component (${(d.factorEfectivo*100).toFixed(1)}% of standard). The discount stacks with provider prefix caching rather than replacing it`}}informeDeEscrituras(e,n,r,o,i,s,a=false){if(e.standalone!==
|
|
1206
|
+
true&&!a)return;let c=n?.cacheExplicita;if(!c){let p=Ct(this.config.provider),y="the provider chose where to write its prompt cache, as it does by default";return {mode:"provider-default",breakpoints:0,reason:St(
|
|
1207
|
+
i,"openai")?p===void 0?`this provider is not one of this package's adapters, so nothing attests explicit prompt-cache control on it: ${y}`:p!=="openai"?`explicit prompt-cache control only exists on Op\
|
|
1208
|
+
enAI's own API, and this endpoint is not it: ${y}`:`model "${i}" has no list price of its own here, so the layer cannot tell whether writing its prefix pays: ${y}`:`model "${i}" is not an OpenAI model\
|
|
1209
|
+
that bills prompt-cache writes above the input rate, so there was no write premium to avoid: ${y}`}}let u=c.puntos,l=(a?`Chosen by cacheBreakpoints: "auto" because continuations of this traffic withi\
|
|
1210
|
+
n 30 minutes were measured below the write premium's break-even (see the prefix-cache-placement trace). `:"")+"Trade-off: repeats and continuations of this exact prompt lose the cache reads the provid\
|
|
1211
|
+
er default would have given them.",d=u===1?"explicit mode: the provider wrote its prompt cache only at the end of the stable prefix, so the rest of this request was billed at the input rate with no ca\
|
|
1212
|
+
che-write charge. "+l:(s?"explicit mode with no breakpoint: the message at the prefix boundary cannot carry one":"explicit mode with no breakpoint: there was no stable prefix worth writing, or the mea\
|
|
1213
|
+
sured hit rate on it did not pay for the write premium")+", so the provider neither wrote nor read its prompt cache for this request. "+l,m=o?rn("openai",o,i,this.now()):void 0,f=Wn(i),h=m&&m.cacheWritePer1k!==
|
|
1214
|
+
void 0?{inputPer1k:m.inputPer1k,cacheWritePer1k:m.cacheWritePer1k,consultado:m.consultado}:f?{inputPer1k:f.inputPer1k,cacheWritePer1k:f.cacheWritePer1k,consultado:void 0}:void 0;if(!h||r.complete===false)
|
|
1215
|
+
return {mode:"explicit",breakpoints:u,reason:d};let g=ka({uso:r,fila:{inputPer1k:h.inputPer1k,cacheWritePer1k:h.cacheWritePer1k},...h.consultado?{consultado:h.consultado}:{}});return {mode:"explicit",breakpoints:u,
|
|
1216
|
+
avoidedWritePremium:{amount:g.importe,basis:"estimated",standardCost:dt(g.costeEstandar),appliedCost:dt(g.costeAplicado),pricesCheckedOn:g.consultado,basisReason:g.tokensOrdinarios>0&&r.inputTokens>=1024?
|
|
1217
|
+
"estimated: the provider default was not run for this request. This is the write premium the default would have charged on the tokens after the last breakpoint; it does not subtract the cache reads th\
|
|
1218
|
+
e default could have given a later repeat":"estimated: below the provider's minimum cacheable length (or with nothing written past the breakpoint) the default would not have charged a write premium ei\
|
|
1219
|
+
ther"},reason:d}}escriturasSinLlamada(e){if(e.savings?.standalone===true)return {mode:"provider-default",breakpoints:0,reason:"no provider call was made, so nothing was written to or read from the provid\
|
|
1220
|
+
er's prompt cache for this request"}}respaldaFaltaDeCapacidad(e,n,r){return e.deferrable!==true||r!==null||this.config.priceLevers?.onCapacityError!=="standard"||Ct(this.config.provider)===void 0?false:n instanceof
|
|
1221
|
+
Error&&/^provider (429|503)\b/.test(n.message)}diferidoSinLlamada(e){if(e.savings?.deferrable===true)return {credited:false,creditedLedger:"none",latency:"not applicable: no provider call was made for this \
|
|
1222
|
+
request.",reason:"no provider call was made, so no processing tier was served and none is credited; the call was avoided outright, which is worth more than any tier discount on it"}}finish(e,n,r,o,i,s,a,c,u,l,d,m,f="\
|
|
1223
|
+
none",h=0,g,p,y,b,v){let w=e.response?.schema,S,k=m===null?null:m??(w?(()=>{let C=le(r.data,w);return S={resultado:C.valid?"passed":"failed",errores:C.errors.length,desenvuelto:false},C.valid})():true),x=S&&
|
|
1224
|
+
!v?.validacion?{...v,validacion:S}:v,E=this.buildReport(e,n,o,i,s,a,c,u,l,d,k,f,h,g,p??this.diferidoSinLlamada(e),y,b??this.escriturasSinLlamada(e),x);return {requestId:E.requestId,data:r.data,text:r.text,
|
|
1225
|
+
...r.rendered!==void 0?{rendered:r.rendered}:{},report:E}}buildReport(e,n,r,o,i,s,a,c,u,l,d,m,f,h,g,p,y,b){let v=o.estimateCost(i),w=s.elapsed(),S=h!=null&&h.servedModel!==h.requestedModel;return {requestId:p??
|
|
1226
|
+
this.generateId(),model:h?.servedModel??e.model,calls:{baselineLlm:o.baselineLlm,actualLlm:o.actualLlm,avoidedLlm:o.avoidedLlm,baselineRetrieval:o.baselineRetrieval,actualRetrieval:o.actualRetrieval,baselineTools:o.
|
|
1227
|
+
baselineTools,actualTools:o.actualTools,retries:o.retries},tokens:{baselineInput:o.baselineInput,actualInput:o.actualInput,eliminatedInput:o.eliminatedInput,compressedInput:o.compressedInput,baselineOutput:o.
|
|
1228
|
+
publishedBaselineOutput,actualOutput:o.actualOutput,eliminatedOutput:o.eliminatedOutput,...o.providerCachedInput?{providerCachedInput:o.providerCachedInput}:{}},cache:{result:r,...l!==void 0?{confidence:l}:
|
|
1229
|
+
{},...u!==void 0?{ageMs:u}:{},...o.reference?{reference:{...o.reference}}:{},...o.referenceRejected?{referenceRejected:o.referenceRejected}:{}},routing:{executionClass:a.executionClass,confidence:a.confidence,
|
|
1230
|
+
rounds:o.actualRetrieval,reason:a.reason},serialization:{chosen:c.chosen,candidateTokens:c.candidateTokens,instructionOverheadTokens:c.instructionOverheadTokens},...o.compressionReport?{compression:o.
|
|
1231
|
+
compressionReport}:{},constraints:{backend:m,schemaVersion:n.schemaVersion,...d===null?{}:{structurallyValid:d}},qualityStatus:nm(r,d,S),qualityLedger:Iu({cacheResult:r,structurallyValid:d,backend:m,hayEsquema:e.
|
|
1232
|
+
response?.schema!=null,ageMs:u,cascada:h,hechos:b}),...h?{modelCascade:h}:{},...g?{deferred:g}:{},...y?{cacheWrites:y}:{},quality:{...r!=="miss"?{freshnessPassed:!_n(n).requiresFreshData}:{},...r==="s\
|
|
1233
|
+
emantic"&&b?.semantico?{semanticScore:b.semantico.similarity}:{}},cost:v,latencyMs:{total:w,preprocessing:Math.max(0,w-f),provider:f},traces:s.all()}}async failOpenDirect(e,n){let r=new sn(this.now);r.
|
|
1234
|
+
record("fail-open","internal optimizer error \u2014 bypassed to a direct provider call",{error:n instanceof Error?n.message:String(n)});let o=new kt,i=this.costModelFor(e.model),s;try{s=mo(e);}catch{s=
|
|
1235
|
+
{schemaVersion:e.response?.version??e.response?.contractId??"none"};}let a=e.response?.schema,c=[...e.messages];e.structuredData!==void 0&&kn(c,{role:"system",content:JSON.stringify(e.structuredData)});
|
|
1236
|
+
let u=this.now(),l=await this.config.provider.generate({model:e.model,messages:c,...e.tools?.length?{tools:e.tools}:{},...a?{schema:a}:{},...e.response?.maxOutputTokens!=null?{maxOutputTokens:e.response.
|
|
1237
|
+
maxOutputTokens}:{},...e.temperature!=null?{temperature:e.temperature}:{},...e.seed!=null?{seed:e.seed}:{}}),d=this.now()-u;o.baselineLlm=1,o.actualLlm=1,o.actualInput=l.usage.inputTokens,o.actualOutput=
|
|
1238
|
+
l.usage.outputTokens,o.baselineInput=l.usage.inputTokens,o.baselineOutput=l.usage.outputTokens,l.usage.cachedInputTokens&&o.providerCached(l.usage.cachedInputTokens);let m=tn(e.model);m>1&&(l.usage.cacheWriteInputTokens??
|
|
1239
|
+
0)>0&&o.providerCacheWritePremium(l.usage.cacheWriteInputTokens??0,m,i),l.usage.complete===false&&(o.callsWithoutUsage=1);let f=l.text,h=true,g={origen:"fail_open",final:{...l.finishReason!==void 0?{finishReason:l.
|
|
1240
|
+
finishReason}:{},...e.response?.maxOutputTokens!=null?{topeDelLlamante:e.response.maxOutputTokens}:{}}},p=(l.toolCalls?.length??0)>0;if(p&&(h=null),a&&!p){let b=Ne(l.text),v=b.ok?le(b.value,a).errors.
|
|
1241
|
+
length:1;h=v===0,g.validacion={resultado:h?"passed":"failed",errores:v,desenvuelto:false},b.ok&&(f=b.value);}let y=this.buildReport(e,s,"miss",o,i,r,bn(),vn(),void 0,void 0,h,"none",d,void 0,e.savings?.deferrable===
|
|
1042
1242
|
true?{credited:false,creditedLedger:"none",latency:"unchanged: the fail-open path asks for no processing tier, so this request was scheduled exactly as an ordinary one.",reason:"the optimizer failed and th\
|
|
1043
1243
|
is request went out on the direct fail-open path, which asks for no cheaper tier: that tier can be refused for lack of capacity, and trading availability for a discount on a last-resort call is the wr\
|
|
1044
1244
|
ong trade"}:void 0,void 0,e.savings?.standalone===true?{mode:"provider-default",breakpoints:0,reason:"the optimizer failed and this request went out unchanged on the direct fail-open path, so the provid\
|
|
1045
|
-
er chose where to write its prompt cache, as it does by default"}:void 0,
|
|
1046
|
-
{},report:
|
|
1047
|
-
generateId(),l=this.diferidoSinLlamada(i),d=l?{deferred:l}:{},
|
|
1245
|
+
er chose where to write its prompt cache, as it does by default"}:void 0,g);return {requestId:y.requestId,data:f,text:l.text,...p?{toolCalls:l.toolCalls}:{},...l.finishReason!==void 0?{finishReason:l.finishReason}:
|
|
1246
|
+
{},report:y}}asCoalescedFollower(e,n,r,o,i,s={ok:false,reason:"absent"}){let a=new kt;s.ok?a.avoidCallByReference(s.credit):(a.avoidCall(n,r),a.referenceRejected=s.reason);let c=a.estimateCost(o),u=this.
|
|
1247
|
+
generateId(),l=this.diferidoSinLlamada(i),d=l?{deferred:l}:{},m=this.escriturasSinLlamada(i),{deferred:f,streaming:h,cacheWrites:g,...p}=e.report;return {...e,requestId:u,report:{...p,requestId:u,calls:{
|
|
1048
1248
|
...e.report.calls,actualLlm:0,avoidedLlm:1},tokens:{baselineInput:a.baselineInput,actualInput:a.actualInput,eliminatedInput:a.eliminatedInput,compressedInput:a.compressedInput,baselineOutput:a.publishedBaselineOutput,
|
|
1049
1249
|
actualOutput:a.actualOutput,eliminatedOutput:a.eliminatedOutput,...a.providerCachedInput?{providerCachedInput:a.providerCachedInput}:{}},cache:{result:"singleflight",...a.reference?{reference:{...a.reference}}:
|
|
1050
|
-
a.referenceRejected?{referenceRejected:a.referenceRejected}:{}},...d,...
|
|
1051
|
-
reason:e};let r;try{r=n.calidad();}catch{r=false;}try{return
|
|
1052
|
-
claveLeida,calidadOk:r,precio:this.precioDocumentado(n.request.model),determinista:
|
|
1250
|
+
a.referenceRejected?{referenceRejected:a.referenceRejected}:{}},...d,...m?{cacheWrites:m}:{},qualityLedger:Du(e.report.qualityLedger),cost:c}}}creditoPorReferencia(e,n){if(typeof e=="string")return {ok:false,
|
|
1251
|
+
reason:e};let r;try{r=n.calidad();}catch{r=false;}try{return Ru(e,{ahoraMs:this.now(),modeloPedido:n.request.model,modeloServido:n.cascada.modeloServido,huella:n.huella(),textoServidoSha256:ne(n.texto),claveLeida:n.
|
|
1252
|
+
claveLeida,calidadOk:r,precio:this.precioDocumentado(n.request.model),determinista:Pu(n.request),salidaDelModelo:Jc(n.request.model),topeDeSalida:n.request.response?.maxOutputTokens,diferible:n.toggles.
|
|
1053
1253
|
deferrable===!0})}catch{return {ok:false,reason:"different-request"}}}assembleBaselinePrompt(e){return this.assemblePromptText(e.messages,e.tools,e.structuredData)}assemblePromptText(e,n,r){let o=e.map(i=>i.
|
|
1054
|
-
content);r!==void 0&&o.push(JSON.stringify(r));for(let i of n??[])o.push(
|
|
1254
|
+
content);r!==void 0&&o.push(JSON.stringify(r));for(let i of n??[])o.push(Nr(i));return o.join(`
|
|
1055
1255
|
`)}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;
|
|
1056
1256
|
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(
|
|
1057
|
-
e)}precioConocido(e,n=this.now()){return this.precioDelCliente(e)??
|
|
1058
|
-
slice(o+1)];if(i)return i}}precioDocumentado(e){return this.precioDelCliente(e)??
|
|
1257
|
+
e)}precioConocido(e,n=this.now()){return this.precioDelCliente(e)??En(e,n)}precioDelCliente(e){let n=this.config.costModels;if(!n)return;let r=n[e];if(r)return r;let o=e.indexOf("/");if(o>=0){let i=n[e.
|
|
1258
|
+
slice(o+1)];if(i)return i}}precioDocumentado(e){return this.precioDelCliente(e)??Ve(e,this.now())}costModelFor(e,n=this.now()){let r=this.precioConocido(e,n);return r||(this.config.defaultCostModel?this.
|
|
1059
1259
|
config.defaultCostModel:(this.avisar(`precio-ilustrativo:${e}`,`[bv-sala] no cost model configured for "${e}"; falling back to the ILLUSTRATIVE default price. Dollar figures will not match your bill. \
|
|
1060
|
-
Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),
|
|
1061
|
-
n.value,t.schema).valid?"met":"missed"}function
|
|
1062
|
-
let e=[],n=/```[ \t]*[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g;for(let r of t.matchAll(n)){let o=r[1]?.trim();o&&e.push(o);}for(let r of ["{","["]){let o=t.indexOf(r);if(o===-1)continue;let i=
|
|
1063
|
-
e.push(i);}return e}function
|
|
1064
|
-
n)o+=1;else if(
|
|
1065
|
-
dation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "not_verified"}}function
|
|
1260
|
+
Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),Hc))}};function Qf(t,e){if((e.toolCalls?.length??0)>0||!t.schema)return "none";let n=Ne(typeof e.text=="string"?e.text:"");return n.ok&&le(
|
|
1261
|
+
n.value,t.schema).valid?"met":"missed"}function Ne(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of Xf(t))try{return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function Xf(t){
|
|
1262
|
+
let e=[],n=/```[ \t]*[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g;for(let r of t.matchAll(n)){let o=r[1]?.trim();o&&e.push(o);}for(let r of ["{","["]){let o=t.indexOf(r);if(o===-1)continue;let i=em(t,o);i&&
|
|
1263
|
+
e.push(i);}return e}function em(t,e){let n=t[e],r=n==="{"?"}":"]",o=0,i=false,s=false;for(let a=e;a<t.length;a+=1){let c=t[a];if(i){s?s=false:c==="\\"?s=true:c==='"'&&(i=false);continue}if(c==='"'){i=true;continue}if(c===
|
|
1264
|
+
n)o+=1;else if(c===r&&(o-=1,o===0))return t.slice(e,a+1)}}function tm(t){return typeof t=="string"?t:JSON.stringify(t,null,2)}function nm(t,e,n=false){if(e===false)return "rejected";if(n)return "bounded_degra\
|
|
1265
|
+
dation";switch(t){case "deterministic":case "exact":return "exact";case "semantic":return "task_equivalent";default:return "not_verified"}}function rm(t,e,n){switch(t){case "no-served-tier":return `asked the \
|
|
1066
1266
|
provider for the "${e}" tier, and it reported none back: the rate this request was billed at cannot be known, so nothing is credited`;case "unknown-tier":return `asked for "${e}" and the provider report\
|
|
1067
1267
|
s serving "${n}", a tier this layer has no published rate for: nothing is credited`;case "standard-rate-tier":return `asked for "${e}" and the provider reports serving "${n}", which bills at the standar\
|
|
1068
1268
|
d rate: this request was billed as if it had never been deferred`;case "no-tier-price":return `the provider reports serving "${n}", but there is no published price for the "${n}" tier of this model from\
|
|
1069
1269
|
this provider (or it has expired): nothing is credited`;case "no-standard-price":return `the provider reports serving "${n}", but this model has no list price of its own here, so there is no standard r\
|
|
1070
1270
|
ate card to price the difference against: nothing is credited`;case "incomplete-usage":return `the provider reports serving "${n}", but its usage for this call is incomplete, so the difference cannot be\
|
|
1071
|
-
priced: nothing is credited`;case "no-difference":return `the provider reports serving "${n}", and this call's usage costs the same at both published rate cards: nothing is credited`}}function
|
|
1072
|
-
round(t*1e6)/1e6}function
|
|
1073
|
-
return
|
|
1074
|
-
return false;let n=t.original;return
|
|
1075
|
-
reason:"n/a (short-circuited)",rounds:0}}function
|
|
1076
|
-
if(t==null||typeof t!="object")return "";let r=t,o=[],i=e||"the value",s=h=>typeof r[h]=="number"?r[h]:null,a=s("maxLength"),
|
|
1077
|
-
if(a!=null){let h=n!=null?Math.min(a,n):a;o.push(`${i}<=${h}ch`);}
|
|
1078
|
-
null&&o.push(`${i}>=${
|
|
1079
|
-
p&&o.push(p);}if(r.items!==void 0){let h=
|
|
1080
|
-
0,200):""}function
|
|
1081
|
-
{type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function
|
|
1082
|
-
"user"){t.splice(n,0,e);return}t.push(e);}function
|
|
1083
|
-
true)}function
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1271
|
+
priced: nothing is credited`;case "no-difference":return `the provider reports serving "${n}", and this call's usage costs the same at both published rate cards: nothing is credited`}}function gn(t){return Math.
|
|
1272
|
+
round(t*1e6)/1e6}function dt(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function om(t,e,n,r){if(e)return dt(-t.extraCostUsd);let o=i=>t.actualInput/1e3*i.inputPer1k+t.actualOutput/1e3*i.outputPer1k;
|
|
1273
|
+
return dt(o(r)-o(n))}function im(t,e){if(!(e>0))return false;if(e>=1)return true;let n=ne(`${t}:cascade-sample`);return Number.parseInt(n.slice(0,13),16)/2**52<e}function Vu(t,e){if(!e.isAgentic||e.allowSemanticCache)
|
|
1274
|
+
return false;let n=t.original;return _n({...t,original:{...n,savings:{...n.savings??{},semanticCache:"include-agentic"}}}).allowSemanticCache}function bn(){return {executionClass:"NO_RETRIEVAL",confidence:1,
|
|
1275
|
+
reason:"n/a (short-circuited)",rounds:0}}function vn(){return {chosen:"json-compact",encoded:"",instruction:"",candidateTokens:{},instructionOverheadTokens:0,reason:"no structured payload"}}function Qi(t,e="",n=null){
|
|
1276
|
+
if(t==null||typeof t!="object")return "";let r=t,o=[],i=e||"the value",s=h=>typeof r[h]=="number"?r[h]:null,a=s("maxLength"),c=s("minLength"),u=s("maxItems"),l=s("minItems"),d=s("maximum"),m=s("minimum");
|
|
1277
|
+
if(a!=null){let h=n!=null?Math.min(a,n):a;o.push(`${i}<=${h}ch`);}c!=null&&o.push(`${i}>=${c}ch`),u!=null&&o.push(`${i}<=${u} items`),l!=null&&o.push(`${i}>=${l} items`),d!=null&&o.push(`${i}<=${d}`),m!=
|
|
1278
|
+
null&&o.push(`${i}>=${m}`),typeof r.pattern=="string"&&o.push(`${i} matches /${r.pattern}/`);let f=r.properties;if(f&&typeof f=="object")for(let[h,g]of Object.entries(f)){let p=Qi(g,e?`${e}.${h}`:h,n);
|
|
1279
|
+
p&&o.push(p);}if(r.items!==void 0){let h=Qi(r.items,`${i} entries`,n);h&&o.push(h);}return o.join("; ")}function yn(t){let e=t.response;return e?e.contractId??e.version??JSON.stringify(e.schema??{}).slice(
|
|
1280
|
+
0,200):""}function sm(t){return t.some(e=>/exceeds maxItems|exceeds maxLength|match pattern|exceeds maximum|below minimum|below minLength|below minItems/.test(e.message))}function Nr(t){return JSON.stringify(
|
|
1281
|
+
{type:"function",function:{name:t.id,...t.description?{description:t.description}:{},parameters:t.parameters??{type:"object",properties:{}}}})}function kn(t,e){for(let n=t.length-1;n>=0;n--)if(t[n].role===
|
|
1282
|
+
"user"){t.splice(n,0,e);return}t.push(e);}function am(t,e){if(e===false)return null;let n=typeof t=="object"&&t!==null?t:{};return e===true||t?n:null}function Xi(t,e=false){if(e){let n=0;for(;n<t.length&&t[n].
|
|
1283
|
+
role==="system";)n+=1;return n}for(let n=t.length-1;n>=0;n--)if(t[n].role==="user")return n;return Xi(t,true)}function Uu(t,e){let n=Or(t,e);return n.cacheReadMultiplier<1?n:null}var Ku={anthropic:{peticiones:1e5,bytes:256e6},openai:{peticiones:5e4,bytes:2e8}},cm=/^[A-Za-z0-9_-]{1,64}$/,Gu="/v1/chat/completions",um=new Set(["completed","failed","expired","cancelled"]);function Yu(t){
|
|
1284
|
+
return {submit:(e,n)=>lm(t,e,n??{}),status:(e,n)=>bm(t,e,n?.signal),results:(e,n)=>xm(t,e,n?.signal),cancel:(e,n)=>km(t,e,n?.signal)}}function qr(t){let e=Ra(t.provider);if(!e)throw new Error("[bvsala]\
|
|
1285
|
+
layer.batches needs one of the built-in providers: AnthropicProvider (Message Batches API) or OpenAICompatibleProvider (OpenAI's Batch API). This provider has no batch support in the layer.");if(e.origen===
|
|
1286
|
+
"google")throw new Error("[bvsala] Gemini's batch mode is not supported by layer.batches yet: its OpenAI-compatible endpoint creates batches but does not upload or download their files (that needs Gem\
|
|
1287
|
+
ini's own Files API). Nothing was sent.");return e}async function lm(t,e,n){t.exigirLicencia();let r=qr(t);dm(e);let o=pm(n.maxRequestsPerBatch,r.protocolo),i=n.cacheSharedPrefix===true&&r.protocolo==="\
|
|
1288
|
+
anthropic",s=new TextEncoder,a=e.map(({customId:h,request:g})=>{let p;try{p=r.cuerpo(fm(g,i));}catch(v){throw new TypeError(`[bvsala] batch request "${h}": ${Br(v)}`)}let y=r.protocolo==="anthropic"?{custom_id:h,
|
|
1289
|
+
params:p}:{custom_id:h,method:"POST",url:Gu,body:p},b=JSON.stringify(y);return {customId:h,linea:y,bytes:s.encode(b).length,modelo:typeof p.model=="string"?p.model:g.model}}),c=mm(a,r.protocolo,o),u=[],
|
|
1290
|
+
l=new Map,d=new Map;c.forEach((h,g)=>h.forEach(p=>d.set(p.customId,g)));let m=e.map(({customId:h,request:g})=>{let p=g.response?.schema,y;if(p){let b=JSON.stringify(p);y=l.get(b),y===void 0&&(y=u.length,
|
|
1291
|
+
u.push(p),l.set(b,y));}return {customId:h,model:g.model,batch:d.get(h),...y!==void 0?{schema:y}:{}}}),f={kind:"bvsala.batch",version:1,provider:r.protocolo,endpoint:r.endpoint,batchIds:[],submittedAt:new Date(
|
|
1292
|
+
t.now()).toISOString(),requests:m,schemas:u};for(let h=0;h<c.length;h++)try{let g=r.protocolo==="anthropic"?await hm(r,c[h],n.signal):await gm(r,c[h],n.signal);f.batchIds.push(g);}catch(g){let p=f.batchIds.
|
|
1293
|
+
length,y={...f,batchIds:[...f.batchIds],requests:f.requests.filter(v=>v.batch<p)},b=f.requests.filter(v=>v.batch>=p).map(v=>v.customId);throw new Pr(p===0?`[bvsala] batch submission failed before any \
|
|
1294
|
+
provider batch was created: ${Br(g)}.`:`[bvsala] batch submission failed after ${p} of ${c.length} provider batches were created: ${Br(g)}. The created batches run and are billed; error.job holds them\
|
|
1295
|
+
.`,y,b,{cause:g})}return f}function dm(t){if(!Array.isArray(t)||t.length===0)throw new TypeError("[bvsala] layer.batches.submit() needs a non-empty array of { customId, request }.");let e=new Set;for(let[
|
|
1296
|
+
n,r]of t.entries()){let o=r?.customId;if(typeof o!="string"||!cm.test(o))throw new TypeError(`[bvsala] batch request #${n}: customId must be 1 to 64 letters, digits, "_" or "-" (got ${JSON.stringify(o)}\
|
|
1297
|
+
).`);if(e.has(o))throw new TypeError(`[bvsala] batch request "${o}": customId is repeated; it must be unique.`);e.add(o);let i=r.request;if(!i||typeof i.model!="string"||i.model===""||!Array.isArray(i.
|
|
1298
|
+
messages)||i.messages.length===0)throw new TypeError(`[bvsala] batch request "${o}": request needs a model and at least one message.`);if(i.retrieval&&i.retrieval.mode!=="off")throw new TypeError(`[bv\
|
|
1299
|
+
sala] batch request "${o}": retrieval runs in the layer's pipeline, which batches skip. Send the retrieved context in the messages instead.`);if(i.structuredData!==void 0)throw new TypeError(`[bvsala]\
|
|
1300
|
+
batch request "${o}": structuredData is serialized by the layer's pipeline, which batches skip. Put the payload in the messages instead.`)}}function pm(t,e){let n=Ku[e].peticiones;if(t===void 0)return n;
|
|
1301
|
+
if(!Number.isInteger(t)||t<1)throw new TypeError(`[bvsala] maxRequestsPerBatch must be a positive integer (got ${String(t)}).`);return Math.min(t,n)}function fm(t,e){let n=0;for(;n<t.messages.length&&
|
|
1302
|
+
t.messages[n].role==="system";)n+=1;return {model:t.model,messages:t.messages,...t.tools&&t.tools.length>0?{tools:t.tools}:{},...t.response?.schema?{schema:t.response.schema}:{},...t.response?.maxOutputTokens!=
|
|
1303
|
+
null?{maxOutputTokens:t.response.maxOutputTokens}:{},...t.temperature!=null?{temperature:t.temperature}:{},...t.seed!=null?{seed:t.seed}:{},...e&&n>0?{stablePrefixMessages:n}:{}}}function mm(t,e,n){let r=Ku[e],
|
|
1304
|
+
o=new Map;for(let a of t){let c=e==="openai"?a.modelo:"",u=o.get(c);u?u.push(a):o.set(c,[a]);}let i=e==="anthropic"?15:0,s=[];for(let a of o.values()){let c=[],u=i;for(let l of a){let d=l.bytes+1;if(i+
|
|
1305
|
+
d>r.bytes)throw new TypeError(`[bvsala] batch request "${l.customId}" is ${l.bytes} bytes, larger than a whole ${e} batch may be. Send it with generate() instead.`);c.length>0&&(c.length>=n||u+d>r.bytes)&&
|
|
1306
|
+
(s.push(c),c=[],u=i),c.push(l),u+=d;}c.length>0&&s.push(c);}return s}async function hm(t,e,n){let r=await xn(t,"/messages/batches",{method:"POST",json:{requests:e.map(o=>o.linea)},...n?{signal:n}:{}});return ns(
|
|
1307
|
+
r,"Message Batch")}async function gm(t,e,n){let r=e.map(a=>JSON.stringify(a.linea)).join(`
|
|
1308
|
+
`)+`
|
|
1309
|
+
`,o=new FormData;o.append("purpose","batch"),o.append("file",new Blob([r],{type:"application/jsonl"}),"bvsala-batch.jsonl");let i=await xn(t,"/files",{method:"POST",form:o,...n?{signal:n}:{}}),s=await xn(
|
|
1310
|
+
t,"/batches",{method:"POST",json:{input_file_id:ns(i,"file"),endpoint:Gu,completion_window:"24h"},...n?{signal:n}:{}});return ns(s,"batch")}async function bm(t,e,n){t.exigirLicencia();let r=qr(t);rs(e,
|
|
1311
|
+
r);let o=await Fr(r,e,n);return Zu(e,o)}async function Fr(t,e,n){let r=[];for(let[o,i]of e.batchIds.entries()){let s=await xn(t,os(t,i),{method:"GET",...n?{signal:n}:{}}),a=e.requests.filter(c=>c.batch===
|
|
1312
|
+
o).length;r.push(t.protocolo==="anthropic"?vm(i,s):ym(i,s,a));}return r}function vm(t,e){let n=se(e),r=typeof n.processing_status=="string"?n.processing_status:"unknown",o=se(n.request_counts);return {id:t,
|
|
1313
|
+
estado:r,terminado:r==="ended",cancelando:r==="canceling",cuentas:{processing:tt(o.processing),succeeded:tt(o.succeeded),errored:tt(o.errored),canceled:tt(o.canceled),expired:tt(o.expired)}}}function ym(t,e,n){
|
|
1314
|
+
let r=se(e),o=typeof r.status=="string"?r.status:"unknown",i=se(r.request_counts),s=tt(i.total)||n,a=tt(i.completed),c=tt(i.failed),u=Math.max(0,s-a-c),l=um.has(o),d=o==="failed"?{processing:0,succeeded:0,
|
|
1315
|
+
errored:s,canceled:0,expired:0}:{processing:l?0:u,succeeded:a,errored:c+(o==="completed"?u:0),canceled:o==="cancelled"?u:0,expired:o==="expired"?u:0},m=Array.isArray(se(r.errors).data)?se(r.errors).data.
|
|
1316
|
+
map(f=>se(f).message).filter(f=>typeof f=="string"):[];return {id:t,estado:o,terminado:l,cancelando:o==="cancelling",cuentas:d,...typeof r.output_file_id=="string"&&r.output_file_id!==""?{salida:r.output_file_id}:
|
|
1317
|
+
{},...typeof r.error_file_id=="string"&&r.error_file_id!==""?{errores:r.error_file_id}:{},...o==="failed"?{fallo:m.length>0?m.join("; "):"the provider rejected the batch"}:{}}}function Zu(t,e){let n={
|
|
1318
|
+
processing:0,succeeded:0,errored:0,canceled:0,expired:0};for(let o of e)n.processing+=o.cuentas.processing,n.succeeded+=o.cuentas.succeeded,n.errored+=o.cuentas.errored,n.canceled+=o.cuentas.canceled,
|
|
1319
|
+
n.expired+=o.cuentas.expired;return {state:e.every(o=>o.terminado)?"ended":e.some(o=>o.cancelando)?"canceling":"in_progress",requestCount:t.requests.length,counts:n,batches:e.map(o=>({id:o.id,status:o.
|
|
1320
|
+
estado}))}}async function km(t,e,n){t.exigirLicencia();let r=qr(t);rs(e,r);let o=await Fr(r,e,n);for(let i of o)i.terminado||i.cancelando||await xn(r,`${os(r,i.id)}/cancel`,{method:"POST",...n?{signal:n}:
|
|
1321
|
+
{}});return Zu(e,await Fr(r,e,n))}async function xm(t,e,n){t.exigirLicencia();let r=qr(t);rs(e,r);let o=await Fr(r,e,n),i=new Map;for(let u of o)if(u.terminado)if(r.protocolo==="anthropic"){let l=await ts(
|
|
1322
|
+
r,`${os(r,u.id)}/results`,{method:"GET",...n?{signal:n}:{}});for await(let d of Ju(l))wm(i,d);}else for(let l of [u.salida,u.errores]){if(!l)continue;let d=await ts(r,`/files/${encodeURIComponent(l)}/co\
|
|
1323
|
+
ntent`,{method:"GET",...n?{signal:n}:{}});for await(let m of Ju(d))Sm(i,m);}let s=Math.max(t.now(),Date.parse(e.submittedAt)||0),a=[],c=0;for(let u of e.requests){let l=o[u.batch];if(!l.terminado){c+=1;
|
|
1324
|
+
continue}let d=u.schema!==void 0?e.schemas[u.schema]:void 0;a.push(Tm(t,r,u,d,i.get(u.customId),l,s));}return {ended:o.every(u=>u.terminado),items:a,summary:Em(e,a,c)}}function wm(t,e){let n=se(e),r=n.custom_id;
|
|
1325
|
+
if(typeof r!="string"||t.has(r))return;let o=se(n.result);switch(o.type){case "succeeded":t.set(r,{tipo:"ok",cuerpo:o.message});return;case "errored":{let i=se(se(o.error).error);t.set(r,{tipo:"errored",
|
|
1326
|
+
error:{type:typeof i.type=="string"?i.type:"error",message:typeof i.message=="string"?i.message:"the provider reported an error"}});return}case "canceled":t.set(r,{tipo:"canceled"});return;case "expired":
|
|
1327
|
+
t.set(r,{tipo:"expired"});return;default:return}}function Sm(t,e){let n=se(e),r=n.custom_id;if(typeof r!="string"||t.has(r))return;let o=n.error;if(o!=null){let u=se(o),l=typeof u.code=="string"?u.code:
|
|
1328
|
+
"error";if(l==="batch_expired"){t.set(r,{tipo:"expired"});return}if(l==="batch_cancelled"||l==="batch_canceled"){t.set(r,{tipo:"canceled"});return}t.set(r,{tipo:"errored",error:{type:l,message:typeof u.
|
|
1329
|
+
message=="string"?u.message:"the provider reported an error"}});return}let i=se(n.response),s=i.status_code,a=i.body;if(typeof s=="number"&&s>=200&&s<300&&a!==void 0){t.set(r,{tipo:"ok",cuerpo:a});return}
|
|
1330
|
+
let c=se(se(a).error);t.set(r,{tipo:"errored",error:{type:typeof c.type=="string"?c.type:`http_${typeof s=="number"?s:"error"}`,message:typeof c.message=="string"?c.message:"the provider reported an e\
|
|
1331
|
+
rror"}});}function Tm(t,e,n,r,o,i,s){let a={customId:n.customId,model:n.model},c=e.protocolo==="anthropic";if(!o)return i.estado==="failed"?{...a,outcome:"errored",reason:`the provider rejected the who\
|
|
1332
|
+
le batch before running it: ${i.fallo??"no reason given"}`,error:{type:"batch_failed",message:i.fallo??"the provider rejected the batch"}}:i.estado==="expired"?{...a,outcome:"expired",reason:"the batc\
|
|
1333
|
+
h expired before this request ran: no answer and no usage"}:i.estado==="cancelled"?{...a,outcome:"canceled",reason:"the batch was canceled before this request ran: no answer and no usage"}:{...a,outcome:"\
|
|
1334
|
+
missing",reason:"the provider returned no result line for this request; nothing is assumed about it"};switch(o.tipo){case "errored":return {...a,outcome:"errored",reason:`the provider could not run this\
|
|
1335
|
+
request (${o.error.type}: ${o.error.message})`+(c?"; Anthropic documents that errored requests are not billed":""),error:o.error};case "canceled":return {...a,outcome:"canceled",reason:c?"canceled befo\
|
|
1336
|
+
re it was sent to the model; Anthropic documents that it is not billed":"canceled before it ran: no answer and no usage"};case "expired":return {...a,outcome:"expired",reason:c?"the batch reached its 24\
|
|
1337
|
+
-hour expiration before this request was sent to the model; Anthropic documents that it is not billed":"not executed before the batch's completion window expired: no answer and no usage"};}
|
|
1338
|
+
let u={model:n.model,messages:[],...r?{schema:r}:{}},l;try{l=e.leer(o.cuerpo,u);}catch(b){return {...a,outcome:"succeeded",reason:`the provider ran this request but its answer could not be read (${Br(b)}\
|
|
1339
|
+
): nothing is credited`}}let d=Pm(l,r),m=c?l.servedServiceTier:"batch",f=e.origen==="anthropic"||e.origen==="openai"?e.origen:null,h=Rm(t.costModels,n.model),g=Gn({modelo:n.model,uso:l.usage,tierServido:m,
|
|
1340
|
+
origen:f,tierLeidoDe:c?"cuerpo":"lote",...h?{precioDelCliente:h}:{},ahoraMs:s}),p={...a,outcome:"succeeded",text:l.text,...d,...l.toolCalls&&l.toolCalls.length>0?{toolCalls:l.toolCalls}:{},...l.finishReason?
|
|
1341
|
+
{finishReason:l.finishReason}:{},usage:l.usage,...m?{servedTier:m}:{}};if(!g.ok)return {...p,reason:Cm(g.motivo,m)};let y={amount:g.importe,basis:g.basis,standardCost:zr(g.costeEstandar),appliedCost:zr(
|
|
1342
|
+
g.costeAplicado),pricesCheckedOn:g.consultado,basisReason:g.motivoBasis};return {...p,tierSaving:y,reason:`billed at the "${m}" tier; this request's usage was priced at the standard and at the batch pu\
|
|
1343
|
+
blished rate cards, component by component (${(g.factorEfectivo*100).toFixed(1)}% of standard)`}}function Pm(t,e){if(!e||(t.toolCalls?.length??0)>0)return {};let n=Ne(typeof t.text=="string"?t.text:"");
|
|
1344
|
+
return n.ok?le(n.value,e).valid?{data:n.value,contract:"met"}:{contract:"missed"}:{contract:"missed"}}function Cm(t,e){switch(t){case "no-served-tier":return "the provider reported no service tier for t\
|
|
1345
|
+
his result, so the rate it was billed at cannot be known: nothing is credited";case "unknown-tier":return `the provider reports the "${e}" tier for this result, a tier this layer has no published rate f\
|
|
1346
|
+
or: nothing is credited`;case "standard-rate-tier":return `the provider reports the "${e}" tier for this result, which is not billed below the standard rate: nothing is credited`;case "no-tier-price":return "\
|
|
1347
|
+
there is no published batch price for this model from this provider (or it has expired): nothing is credited";case "no-standard-price":return "this model has no list price of its own here, so there is n\
|
|
1348
|
+
o standard rate card to price the difference against: nothing is credited";case "incomplete-usage":return "the provider's usage for this result is incomplete, so the difference cannot be priced: nothing\
|
|
1349
|
+
is credited";case "no-difference":return "this result's usage costs the same at both published rate cards: nothing is credited"}}var Wu=1e10;function Em(t,e,n){let r=0,o=0,i=0,s=0,a=0,c=0,u=0,l=0n,d=0,
|
|
1350
|
+
m=0,f;for(let p of e){p.outcome==="succeeded"?r+=1:p.outcome==="errored"?o+=1:p.outcome==="canceled"?i+=1:p.outcome==="expired"?s+=1:a+=1;let y=p.tierSaving;y&&(c+=1,y.basis==="measured"&&(u+=1),l+=BigInt(
|
|
1351
|
+
Math.round(y.amount*Wu)),d+=y.standardCost,m+=y.appliedCost,(!f||y.pricesCheckedOn<f)&&(f=y.pricesCheckedOn));}let h=c===0?"none":u===c?"measured":"estimated",g=`${r} of ${t.requests.length} requests s\
|
|
1352
|
+
ucceeded`+(n>0?` (${n} still running)`:"")+`; ${c} were valued at the provider's standard and batch published rate cards`+(h==="none"?"":` (${h})`)+". Reported only: batch requests are not metered and\
|
|
1353
|
+
this saving is never billed. The layer's own per-request savings do not run on batches.";return {requestCount:t.requests.length,succeeded:r,errored:o,canceled:i,expired:s,missing:a,pending:n,credited:c,
|
|
1354
|
+
tierSaving:Number(l)/Wu,standardCost:zr(d),appliedCost:zr(m),basis:h,...f?{pricesCheckedOn:f}:{},creditedLedger:"none",reason:g}}function rs(t,e){let n=t;if(!n||n.kind!=="bvsala.batch"||n.version!==1||
|
|
1355
|
+
!Array.isArray(n.batchIds)||!Array.isArray(n.requests)||!Array.isArray(n.schemas)||n.requests.some(r=>!Number.isInteger(r?.batch)||r.batch<0||r.batch>=n.batchIds.length))throw new TypeError("[bvsala] \
|
|
1356
|
+
not a batch job returned by layer.batches.submit().");if(n.provider!==e.protocolo||n.endpoint!==e.endpoint)throw new TypeError(`[bvsala] this job was submitted to ${n.provider} at ${n.endpoint}; this \
|
|
1357
|
+
layer's provider is ${e.protocolo} at ${e.endpoint}. Read it with a layer configured like the one that submitted it.`)}function os(t,e){return t.protocolo==="anthropic"?`/messages/batches/${encodeURIComponent(
|
|
1358
|
+
e)}`:`/batches/${encodeURIComponent(e)}`}async function ts(t,e,n){let r=await t.solicitar(e,n);if(!r.ok){let o="";try{o=await r.text();}catch{o="";}throw new Error(`provider ${r.status}: ${o}`)}return r}
|
|
1359
|
+
async function xn(t,e,n){return await(await ts(t,e,n)).json()}function ns(t,e){let n=se(t).id;if(typeof n!="string"||n==="")throw new Error(`the provider returned no ${e} id`);return n}async function*Ju(t){
|
|
1360
|
+
let e=t.body;if(!e||typeof e.getReader!="function"){for(let s of (await t.text()).split(`
|
|
1361
|
+
`)){let a=es(s);a!==void 0&&(yield a);}return}let n=e.getReader(),r=new TextDecoder,o="";for(;;){let{done:s,value:a}=await n.read();if(s)break;o+=r.decode(a,{stream:true});let c=o.indexOf(`
|
|
1362
|
+
`);for(;c>=0;){let u=es(o.slice(0,c));u!==void 0&&(yield u),o=o.slice(c+1),c=o.indexOf(`
|
|
1363
|
+
`);}}o+=r.decode();let i=es(o);i!==void 0&&(yield i);}function es(t){let e=t.trim();if(e!=="")try{return JSON.parse(e)}catch{return}}function Rm(t,e){if(!t)return;let n=t[e];if(n)return n;let r=e.indexOf(
|
|
1364
|
+
"/");return r>=0?t[e.slice(r+1)]:void 0}function se(t){return typeof t=="object"&&t!==null?t:{}}function tt(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0}function Br(t){return t instanceof
|
|
1365
|
+
Error?t.message:String(t)}function zr(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}var Im=36e5,Dm=7*86400,_m=3e4,Vr=class{opts;pollIntervalMs;refreshLeadSeconds;timer=null;enVuelo=false;parado=false;controller=null;avisadoDeCredencial=false;currentExpiresAt;currentOrg;constructor(e){this.opts=
|
|
1366
|
+
e,this.pollIntervalMs=e.pollIntervalMs??Im,this.refreshLeadSeconds=e.refreshLeadSeconds??Dm;let n=_t(Dt(e.initialToken),e.publicKey);this.currentExpiresAt=n.signatureValid&&n.payload?n.payload.expires_at:
|
|
1367
|
+
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=
|
|
1368
|
+
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.
|
|
1369
|
+
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??
|
|
1370
|
+
_m);n.unref?.();try{let o=await(this.opts.fetchImpl??globalThis.fetch.bind(globalThis))(this.opts.url,{signal:e.signal,headers:{authorization:`Bearer ${this.opts.serviceAccountKey}`,accept:"applicatio\
|
|
1371
|
+
n/json"}});if(!o.ok)return (o.status===401||o.status===403||o.status===404)&&!this.avisadoDeCredencial&&(this.avisadoDeCredencial=!0,console.warn(`[bv-sala] automatic pickup of the renewed license is f\
|
|
1372
|
+
ailing with HTTP ${o.status} at ${this.opts.url}. Check 'serviceAccountKey' (rotated? from another organization?) and 'licenseServerUrl': until this works, the token will NOT renew itself and the SDK \
|
|
1373
|
+
will stop operating when the grace period ends.`)),!1;let i=await o.json();if(typeof i.token!="string")return !1;let s=Dt(i.token),a=_t(s,this.opts.publicKey);return !a.signatureValid||!a.payload||a.payload.
|
|
1374
|
+
expires_at<=this.currentExpiresAt||this.currentOrg&&a.payload.org_id!==this.currentOrg||this.opts.revocados?.snapshot().has(a.payload.jti)||this.parado?!1:(this.currentExpiresAt=a.payload.expires_at,this.
|
|
1375
|
+
currentOrg=a.payload.org_id,this.opts.onNewToken(s),!0)}catch{return false}finally{clearTimeout(n),this.controller===e&&(this.controller=null),this.enVuelo=false;}}};var Qu=2e3,Xu=200,Am=200,Om=10,Mm=1e7,Lm=5,jm=48*3600*1e3,is=/^[A-Za-z0-9._:/-]{1,128}$/,Bt=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0,wn=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=
|
|
1376
|
+
1e3;function Nm(t,e={}){if(!is.test(t.requestId)||!is.test(t.requestedModel)||!is.test(t.servedModel)||typeof t.at!="number"||!Number.isFinite(t.at)||t.at<1e12)return null;let n=typeof e?.ahora=="numb\
|
|
1377
|
+
er"?e.ahora:Date.now();if(t.at>n+jm)return null;let r=t.optimized;if(!wn(r.cost)||!Bt(r.inputTokens)||!Bt(r.cachedInputTokens)||!Bt(r.outputTokens))return null;let o=t.prices;if(!wn(o.inputPer1k)||!wn(
|
|
1378
|
+
o.outputPer1k)||o.cachedInputPer1k!==void 0&&!wn(o.cachedInputPer1k))return null;let i={basis:"verification",requestId:t.requestId,at:Math.floor(t.at),stratum:t.stratum,outcome:t.outcome,requestedModel:t.
|
|
1087
1379
|
requestedModel,servedModel:t.servedModel,cacheResult:t.cacheResult,optimizedCost:r.cost,optimizedInputTokens:r.inputTokens,optimizedCachedInputTokens:Math.min(r.cachedInputTokens,r.inputTokens),optimizedOutputTokens:r.
|
|
1088
|
-
outputTokens,inputPer1k:o.inputPer1k,...o.cachedInputPer1k!==void 0?{cachedInputPer1k:o.cachedInputPer1k}:{},outputPer1k:o.outputPer1k};if(t.outcome==="paired"){let s=t.naive;if(!s||!
|
|
1089
|
-
inputTokens)||!
|
|
1090
|
-
i.naiveOutputTokens=s.outputTokens,s.finishReason!==void 0){if(!/^[a-z_]{1,32}$/.test(s.finishReason))return null;i.naiveFinishReason=s.finishReason;}i.naiveContract=s.contract;}return i}var
|
|
1091
|
-
NEGATIVE_INFINITY;constructor(e){this.o=e,this.flushIntervalMs=e.flushIntervalMs??15e3;}ahora(){return (this.o.now??Date.now)()}encolar(e){let n;try{n=
|
|
1092
|
-
push(n),this.pendientes.length>
|
|
1380
|
+
outputTokens,inputPer1k:o.inputPer1k,...o.cachedInputPer1k!==void 0?{cachedInputPer1k:o.cachedInputPer1k}:{},outputPer1k:o.outputPer1k};if(t.outcome==="paired"){let s=t.naive;if(!s||!wn(s.cost)||!Bt(s.
|
|
1381
|
+
inputTokens)||!Bt(s.cachedInputTokens)||!Bt(s.outputTokens)||s.cachedInputTokens>s.inputTokens)return null;if(i.naiveCost=s.cost,i.naiveInputTokens=s.inputTokens,i.naiveCachedInputTokens=s.cachedInputTokens,
|
|
1382
|
+
i.naiveOutputTokens=s.outputTokens,s.finishReason!==void 0){if(!/^[a-z_]{1,32}$/.test(s.finishReason))return null;i.naiveFinishReason=s.finishReason;}i.naiveContract=s.contract;}return i}var Ur=class{o;flushIntervalMs;pendientes=[];conteos=new Map;reintentos=[];inflight=null;timer;fallosSeguidos=0;ultimoFallo=Number.
|
|
1383
|
+
NEGATIVE_INFINITY;constructor(e){this.o=e,this.flushIntervalMs=e.flushIntervalMs??15e3;}ahora(){return (this.o.now??Date.now)()}encolar(e){let n;try{n=Nm(e,{ahora:this.ahora()});}catch{n=null;}n&&(this.pendientes.
|
|
1384
|
+
push(n),this.pendientes.length>Qu&&this.pendientes.splice(0,this.pendientes.length-Qu),this.pendientes.length>=Xu&&this.flushSiToca());}flushSiToca(){return this.reintentos.length>0&&this.ahora()-this.
|
|
1093
1385
|
ultimoFallo<this.flushIntervalMs?Promise.resolve():this.flush()}contar(e,n){let r=`${e}|${n}`;this.conteos.set(r,(this.conteos.get(r)??0)+1);}start(){this.timer||(this.timer=setInterval(()=>{this.flush();},
|
|
1094
1386
|
this.flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async flush(){if(this.inflight)return this.inflight;this.inflight=this.hacerFlush();
|
|
1095
1387
|
try{await this.inflight;}finally{this.inflight=null;}}hayAlgo(){return this.reintentos.length>0||this.pendientes.length>0||this.conteos.size>0}siguienteSobre(){let e=this.reintentos.shift();if(e)return e;
|
|
1096
|
-
if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,
|
|
1097
|
-
r.push({day:s,category:a,requests:
|
|
1098
|
-
fetch;if(e)for(let n=0;n<
|
|
1099
|
-
Bearer ${this.o.serviceAccountKey}`,"content-type":"application/json",[
|
|
1100
|
-
this.ahora(),this.reencolar(n),this.avisarDeFallo(`the server responded ${r.status}`),!1):r.status===401||r.status===403?(this.o.silenceWarnings||
|
|
1388
|
+
if(this.pendientes.length===0&&this.conteos.size===0)return null;let n=this.pendientes.splice(0,Xu),r=[];for(let[o,i]of this.conteos){if(r.length>=Am)break;let[s="",a=""]=o.split("|"),c=Math.min(i,Mm);
|
|
1389
|
+
r.push({day:s,category:a,requests:c}),i>c?this.conteos.set(o,i-c):this.conteos.delete(o);}return {batchId:(this.o.randomId??Jt)(),samples:n,counts:r}}async hacerFlush(){let e=this.o.fetchImpl??globalThis.
|
|
1390
|
+
fetch;if(e)for(let n=0;n<Lm&&this.hayAlgo();n++){let r=this.siguienteSobre();if(!r||!await this.enviar(e,r))return}}async enviar(e,n){try{let r=await e(this.o.url,{method:"POST",headers:{authorization:`\
|
|
1391
|
+
Bearer ${this.o.serviceAccountKey}`,"content-type":"application/json",[Rn]:`sdk/${De}`},body:JSON.stringify(n)});return r.ok?(this.fallosSeguidos=0,!0):r.status>=500?(this.fallosSeguidos++,this.ultimoFallo=
|
|
1392
|
+
this.ahora(),this.reencolar(n),this.avisarDeFallo(`the server responded ${r.status}`),!1):r.status===401||r.status===403?(this.o.silenceWarnings||W(`verification-auth-${r.status}`,`[bvsala] verificati\
|
|
1101
1393
|
on reporting is being rejected with HTTP ${r.status} at ${this.o.url}. Check \`serviceAccountKey\`. Pairs are not reaching your dashboard; your requests and your usage reporting are not affected.`),!1):
|
|
1102
1394
|
(this.fallosSeguidos++,this.avisarDeFallo(r.status===404||r.status===405?`HTTP ${r.status}: the reporting URL looks wrong, or the server does not have this feature yet`:`the server rejected the batch \
|
|
1103
1395
|
with HTTP ${r.status}`),!1)}catch(r){return this.fallosSeguidos++,this.ultimoFallo=this.ahora(),this.reencolar(n),this.avisarDeFallo(r instanceof Error?r.message:"network error"),false}}reencolar(e){for(this.
|
|
1104
|
-
reintentos.unshift(e);this.reintentos.length>
|
|
1396
|
+
reintentos.unshift(e);this.reintentos.length>Om;)this.reintentos.pop();}avisarDeFallo(e){if(this.o.silenceWarnings)return;let n=this.fallosSeguidos;n<3||(n-3)%12!==0||console.warn(`[bvsala] verificatio\
|
|
1105
1397
|
n reporting has failed ${n} times in a row against ${this.o.url} (${e}). Your requests and usage reporting keep working; the pairs are not arriving.`);}get estado(){return {pendientes:this.pendientes.length,
|
|
1106
|
-
conteos:this.conteos.size,reintentos:this.reintentos.length}}};var
|
|
1398
|
+
conteos:this.conteos.size,reintentos:this.reintentos.length}}};var $m=72*3600,Bm,el=new Set(Object.values(In).flatMap(t=>t.flatMap(e=>[e,`openai/${e}`]))),tl="[bvsala] `gpt-tokenizer` is not installed, so token counts for OpenAI models are ESTIMATED with a built-\
|
|
1107
1399
|
in heuristic and the reconstructed savings are less accurate. Savings where the layer removed something are reported as `estimated` either way, and estimated savings are never billed. Install it once \
|
|
1108
|
-
(`npm i gpt-tokenizer`) and the SDK loads it automatically.";function
|
|
1109
|
-
ted as a `licenseKey` verified against BiVelio's embedded public key. Get yours at https://savings.bivelio.com/dashboard/install"),t={...t,licenseGate:void 0});let n={...t,tokenizer:t.tokenizer??
|
|
1110
|
-
tokenizer==null&&t.exactTokenizer!==false?
|
|
1111
|
-
f,{revocation:
|
|
1112
|
-
status(),reason:()=>
|
|
1400
|
+
(`npm i gpt-tokenizer`) and the SDK loads it automatically.";function gk(t){t.licenseGate&&(console.warn("[bvsala] Ignoring the injected `licenseGate`: in the published package a license is only accep\
|
|
1401
|
+
ted as a `licenseKey` verified against BiVelio's embedded public key. Get yours at https://savings.bivelio.com/dashboard/install"),t={...t,licenseGate:void 0});let n={...t,tokenizer:t.tokenizer??ao},r=t.
|
|
1402
|
+
tokenizer==null&&t.exactTokenizer!==false?Bm??=uo(ao).catch(()=>false):Promise.resolve(true),o,i;if(t.licenseKey&&!t.licenseGate){let f=Nc;if(t.licenseServerUrl){let h=new At,g=b=>wr(b,
|
|
1403
|
+
f,{revocation:h,...t.now?{now:t.now}:{},maxStalenessSeconds:t.licenseRevocation?.maxStalenessSeconds??$m}),p=g(t.licenseKey);n.licenseGate={isEntitled:b=>p.isEntitled(b),isActive:()=>p.isActive(),status:()=>p.
|
|
1404
|
+
status(),reason:()=>p.reason()};let y=`${t.licenseServerUrl.replace(/\/+$/,"")}/licenses/revocations`;o=new Sr({url:y,publicKeyPem:f,snapshot:h,getRefreshAfter:()=>p.refreshAfter?.(),...t.now?{nowSeconds:()=>Math.
|
|
1113
1405
|
floor(t.now()/1e3)}:{},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.licensePollIntervalSeconds!=null?{pollIntervalSeconds:t.licensePollIntervalSeconds}:{},...t.silenceWarnings!=null?{silenceWarnings:t.
|
|
1114
|
-
silenceWarnings}:{},...t.licenseRevocation??{}}),o.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(i=new
|
|
1115
|
-
serviceAccountKey,publicKey:f,initialToken:t.licenseKey,revocados:
|
|
1116
|
-
{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),i.start());}else n.licenseGate=
|
|
1117
|
-
t.verification),a=(f,
|
|
1118
|
-
enabled!==false)if(t.meteringUrl){let
|
|
1119
|
-
/api/metering/verification`);if(!f&&!s.onCheck)a("verificacion-sin-destino",
|
|
1406
|
+
silenceWarnings}:{},...t.licenseRevocation??{}}),o.start(),t.serviceAccountKey&&t.licenseRefresh?.enabled!==false&&(i=new Vr({url:`${t.licenseServerUrl.replace(/\/+$/,"")}/api/license/current`,serviceAccountKey:t.
|
|
1407
|
+
serviceAccountKey,publicKey:f,initialToken:t.licenseKey,revocados:h,onNewToken:b=>{p=g(b);},...t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.licenseRefresh?.intervalMs!=null?
|
|
1408
|
+
{pollIntervalMs:t.licenseRefresh.intervalMs}:{},...t.licenseRefresh?.leadSeconds!=null?{refreshLeadSeconds:t.licenseRefresh.leadSeconds}:{}}),i.start());}else n.licenseGate=Vc(t.licenseKey,f,t.now);}let s=Lr(
|
|
1409
|
+
t.verification),a=(f,h)=>{t.silenceWarnings!==true&&W(f,h);};!s.activo&&s.motivo==="invalido"&&a("verificacion-invalida",Au(t.verification));let c,u;if(s.activo){let f;if(t.serviceAccountKey&&t.metering?.
|
|
1410
|
+
enabled!==false)if(t.meteringUrl){let h=/^(.*)\/api\/metering\/usage\/?$/.exec(t.meteringUrl);h&&(f=`${h[1]}/api/metering/verification`);}else t.licenseServerUrl&&(f=`${t.licenseServerUrl.replace(/\/+$/,"")}\
|
|
1411
|
+
/api/metering/verification`);if(!f&&!s.onCheck)a("verificacion-sin-destino",Ou);else {f&&t.serviceAccountKey&&(c=new Ur({url:f,serviceAccountKey:t.serviceAccountKey,...t.meteringFetch?{fetchImpl:t.meteringFetch}:
|
|
1120
1412
|
t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.silenceWarnings!=null?{silenceWarnings:t.
|
|
1121
|
-
silenceWarnings}:{}}),
|
|
1122
|
-
|
|
1413
|
+
silenceWarnings}:{}}),c.start());let h=c;u={encolar:g=>h?.encolar(g),...h?{contar:(g,p)=>h.contar(g,p)}:{},enReposo:()=>h?.flushSiToca()},a(`verificacion-activa:${s.tasa}`,_u(s.tasa));}}let l=new $r(n,
|
|
1414
|
+
u?{verificacion:u}:{}),d;if(t.serviceAccountKey&&t.metering?.enabled!==false){let f=t.meteringUrl??(t.licenseServerUrl?`${t.licenseServerUrl.replace(/\/+$/,"")}/api/metering/usage`:void 0);if(!f&&t.silenceWarnings!==
|
|
1123
1415
|
true&&console.warn('[bvsala] `serviceAccountKey` is set but there is no `licenseServerUrl` (or `meteringUrl`): seat metering and automatic license renewal are OFF, so nothing will reach your dashboard a\
|
|
1124
|
-
nd a renewed license will not be picked up. Add `licenseServerUrl: "https://savings.bivelio.com"` \u2014 or drop `serviceAccountKey` for a zero-network deployment.'),f){d=new
|
|
1416
|
+
nd a renewed license will not be picked up. Add `licenseServerUrl: "https://savings.bivelio.com"` \u2014 or drop `serviceAccountKey` for a zero-network deployment.'),f){d=new fn({url:f,serviceAccountKey:t.
|
|
1125
1417
|
serviceAccountKey,surface:"sdk",...t.metering?.orgId?{orgId:t.metering.orgId}:{},...t.metering?.flushIntervalMs!=null?{flushIntervalMs:t.metering.flushIntervalMs}:{},...t.metering?.maxBatch!=null?{maxBatch:t.
|
|
1126
1418
|
metering.maxBatch}:{},...t.metering?.maxBuffer!=null?{maxBuffer:t.metering.maxBuffer}:{},...t.meteringFetch?{fetchImpl:t.meteringFetch}:t.licenseFetch?{fetchImpl:t.licenseFetch}:{},...t.now?{now:t.now}:
|
|
1127
|
-
{},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let
|
|
1128
|
-
let
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
e
|
|
1134
|
-
|
|
1135
|
-
i
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
t)
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1419
|
+
{},...t.metering?.ci!=null?{ci:t.metering.ci}:{},...t.silenceWarnings!=null?{silenceWarnings:t.silenceWarnings}:{}});let h=t.metering?.ci??Ei();if(t.metering?.seatId)d.setSeat(t.metering.seatId,h);else {
|
|
1420
|
+
let g=d;Ri(t.serviceAccountKey).then(p=>g.setSeat(p,h)).catch(()=>{});}d.start();}}return {batches:Yu({provider:n.provider,...n.costModels?{costModels:n.costModels}:{},exigirLicencia:()=>l.exigirLicencia(),
|
|
1421
|
+
now:n.now??Date.now}),generate:async f=>{let h=await r,g=await l.generate(f);if(!h&&t.silenceWarnings!==true&&el.has(f.model)&&W("tokenizador-exacto-ausente",tl),d)try{d.record(g.report);}catch{}return g},
|
|
1422
|
+
generateStream:(f,h)=>{let g=l.generateStream(f,h??{},r);return g.result.then(async p=>{if(d)try{d.record(p.report);}catch{}!await r&&t.silenceWarnings!==true&&el.has(f.model)&&W("tokenizador-exacto-ause\
|
|
1423
|
+
nte",tl);},()=>{}),g},close:()=>{l.cerrarVerificacion(),c?.stop(),o?.stop(),i?.stop(),d?.stop();}}}function ss(t){if(!Number.isFinite(t))throw new TypeError(`[bvsala] cannot write a non-finite number (${String(t)}) as a decimal`);if(Math.abs(t)>=1e21)return BigInt(Math.round(t)).toString();let e=t.
|
|
1424
|
+
toFixed(10).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return e==="-0"?"0":e}function nl(t,e){if(t==null)return "";if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`[bvsala] toCsv: \
|
|
1425
|
+
column "${e}" holds a non-finite number`);return ss(t)}if(typeof t=="boolean")return t?"true":"false";if(typeof t!="string")throw new TypeError(`[bvsala] toCsv: column "${e}" holds a ${typeof t}; writ\
|
|
1426
|
+
e strings, numbers, booleans or null (flatten objects such as a series row's \`dimensions\` into their own columns first)`);let n=t;return n===""||/[",\r\n]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}function Fm(t,e){
|
|
1427
|
+
let n;if(e?.columns)n=e.columns;else {if(t.length===0)return "";let o=new Set;for(let i of t)for(let s of Object.keys(i))o.add(s);n=[...o];}let r=[n.map(o=>nl(o,o)).join(",")];for(let o of t)r.push(n.map(
|
|
1428
|
+
i=>nl(o[i],i)).join(","));return r.map(o=>`${o}\r
|
|
1429
|
+
`).join("")}var rl={openai:{otel:"openai",nombre:"OpenAI"},anthropic:{otel:"anthropic",nombre:"Anthropic"},google:{otel:"gcp.gen_ai",nombre:"Google"},mistral:{otel:"mistral_ai",nombre:"Mistral AI"},deepseek:{otel:"\
|
|
1430
|
+
deepseek",nombre:"DeepSeek"},groq:{otel:"groq",nombre:"Groq"},xai:{otel:"x_ai",nombre:"xAI"},cohere:{otel:"cohere",nombre:"Cohere"},perplexity:{otel:"perplexity",nombre:"Perplexity"}};function ol(t){let e=t.
|
|
1431
|
+
indexOf("/");return e>0?t.slice(0,e):void 0}function as(t){let e=ol(t)?.toLowerCase();return e!==void 0&&Object.hasOwn(rl,e)?rl[e]:void 0}function il(t){return as(t)?.otel??ol(t)}function sl(t){return as(
|
|
1432
|
+
t)?.nombre}function pt(t){return as(t)?t.slice(t.indexOf("/")+1):t}var ce={operacion:"gen_ai.operation.name",proveedor:"gen_ai.provider.name",modeloPedido:"gen_ai.request.model",temperatura:"gen_ai.request.temperature",semilla:"gen_ai.request.seed",maxTokens:"gen_ai.\
|
|
1433
|
+
request.max_tokens",stream:"gen_ai.request.stream",conversacion:"gen_ai.conversation.id",modeloRespuesta:"gen_ai.response.model",motivosDeFin:"gen_ai.response.finish_reasons",primerTrozo:"gen_ai.respo\
|
|
1434
|
+
nse.time_to_first_chunk",entrada:"gen_ai.usage.input_tokens",salida:"gen_ai.usage.output_tokens",lecturaDeCache:"gen_ai.usage.cache_read.input_tokens"},al="error.type",q="com.bivelio.",cl=`${q}stream.\
|
|
1435
|
+
request_sent`;function $e(t){return t==="measured"||t==="reference"||t==="estimated"}function Ft(t){let e=Math.round(t*1e10)/1e10;return e===0?0:e}function ul(t){return Ft(t.cost.baselineEstimate-t.cost.
|
|
1436
|
+
actual)}function z(t,e,n){(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))&&(t[e]=n);}function cs(t,e){let{cost:n,tokens:r,calls:o,cache:i}=t,s={bivelio_request_id:t.requestId,
|
|
1437
|
+
bivelio_basis:n.basis,bivelio_currency:e};$e(n.basis)&&(s.bivelio_baseline_cost=n.baselineEstimate,s.bivelio_actual_cost=n.actual,s[`bivelio_saved_${n.basis}`]=ul(t),s.bivelio_net_savings_ratio=n.netSavings),
|
|
1145
1438
|
s.bivelio_avoided_calls=o.avoidedLlm,s.bivelio_eliminated_input_tokens=r.eliminatedInput,s.bivelio_compressed_input_tokens=r.compressedInput,r.providerCachedInput!==void 0&&(s.bivelio_provider_cached_input_tokens=
|
|
1146
|
-
r.providerCachedInput),s.bivelio_cache_result=i.result,t.qualityStatus!==void 0&&(s.bivelio_quality_status=t.qualityStatus);for(let[a,
|
|
1147
|
-
return s}function
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
baseline`,i.baselineLlm),
|
|
1152
|
-
ctual_input`,o.actualInput),
|
|
1153
|
-
`${
|
|
1154
|
-
erence_request_id`,s.reference?.requestId),
|
|
1155
|
-
|
|
1156
|
-
on.metadata.${l}`]=typeof d=="number"?
|
|
1157
|
-
metadata){let l={};for(let[d,
|
|
1158
|
-
"function"}function
|
|
1159
|
-
ngsLayer: `tracer` must be an OpenTelemetry Tracer, a TracerProvider or the `trace` object of the OpenTelemetry API")}function
|
|
1160
|
-
test(e)?e:"_OTHER"}function
|
|
1161
|
-
isFinite(
|
|
1162
|
-
conversacion]=s),r}function
|
|
1163
|
-
streaming;i?.delivery==="live"&&typeof i.firstEventMs=="number"&&Number.isFinite(i.firstEventMs)&&(o[
|
|
1164
|
-
try{if(t.isRecording?.()!==!1){let n={[
|
|
1165
|
-
if(e.currency!==void 0&&!/^[A-Z]{3}$/.test(e.currency))throw new TypeError(`[bvsala] instrumentSavingsLayer: currency must be an ISO 4217 code such as "USD" (got "${e.currency}")`);
|
|
1166
|
-
void 0?{currency:e.currency}:{},...e.langfuse?{langfuse:e.langfuse}:{},...e.datadog?{datadog:e.datadog}:{}},o=e.providerName;function i(s,a,u
|
|
1167
|
-
|
|
1168
|
-
l={valor:
|
|
1169
|
-
c,r),
|
|
1170
|
-
"string"?
|
|
1171
|
-
s!==void 0&&(a.cache_read_input_tokens=s),r.usageDetails=a,e?.includeCost&&n==="USD"&&Number.isFinite(t.cost.actual)&&(r.costDetails={total:t.cost.actual});}return r}var
|
|
1172
|
-
ust be "hour" or "day"`)}function
|
|
1173
|
-
USD"`)}function
|
|
1174
|
-
[bvsala] ${e}: invalid "at" for request ${String(t.report?.requestId)}: expected an ISO 8601 string, epoch milliseconds or a valid Date`);return r}function
|
|
1175
|
-
t/n)*n}function
|
|
1176
|
-
`[bvsala] ${r}: report ${n} has no finite number in ${e}`)}function
|
|
1177
|
-
la] ${n}: every record must be { at, report }`);let a=s.report,
|
|
1178
|
-
own cost basis`);let c
|
|
1439
|
+
r.providerCachedInput),s.bivelio_cache_result=i.result,t.qualityStatus!==void 0&&(s.bivelio_quality_status=t.qualityStatus);for(let[a,c]of Object.entries(s))typeof c=="number"&&!Number.isFinite(c)&&delete s[a];
|
|
1440
|
+
return s}function us(t){let e={};return z(e,ce.modeloRespuesta,pt(t.model)),$e(t.cost.basis)&&(z(e,ce.entrada,t.tokens.actualInput),z(e,ce.salida,t.tokens.actualOutput),t.tokens.providerCachedInput!==
|
|
1441
|
+
void 0&&z(e,ce.lecturaDeCache,t.tokens.providerCachedInput)),e}function Hr(t,e){let n=e?.currency??"USD",{cost:r,tokens:o,calls:i,cache:s}=t,a={};z(a,`${q}request_id`,t.requestId),z(a,`${q}sdk.version`,
|
|
1442
|
+
De),z(a,`${q}model.id`,t.model),z(a,`${q}model.requested_id`,t.modelCascade?.requestedModel),z(a,`${q}cost.basis`,r.basis),z(a,`${q}cost.currency`,n),$e(r.basis)&&(z(a,`${q}cost.baseline`,r.baselineEstimate),
|
|
1443
|
+
z(a,`${q}cost.actual`,r.actual),z(a,`${q}cost.saved.${r.basis}`,ul(t)),z(a,`${q}cost.net_savings_ratio`,r.netSavings),z(a,`${q}cost.eliminated_input_floor`,r.eliminatedInputFloorCost)),z(a,`${q}calls.\
|
|
1444
|
+
baseline`,i.baselineLlm),z(a,`${q}calls.actual`,i.actualLlm),z(a,`${q}calls.avoided`,i.avoidedLlm),z(a,`${q}calls.retries`,i.retries),z(a,`${q}tokens.baseline_input`,o.baselineInput),z(a,`${q}tokens.a\
|
|
1445
|
+
ctual_input`,o.actualInput),z(a,`${q}tokens.eliminated_input`,o.eliminatedInput),z(a,`${q}tokens.compressed_input`,o.compressedInput),z(a,`${q}tokens.provider_cached_input`,o.providerCachedInput),z(a,
|
|
1446
|
+
`${q}tokens.baseline_output`,o.baselineOutput),z(a,`${q}tokens.actual_output`,o.actualOutput),z(a,`${q}tokens.eliminated_output`,o.eliminatedOutput),z(a,`${q}cache.result`,s.result),z(a,`${q}cache.ref\
|
|
1447
|
+
erence_request_id`,s.reference?.requestId),z(a,`${q}cache.reference_rejected`,s.referenceRejected),z(a,`${q}quality.status`,t.qualityStatus),z(a,`${q}latency.preprocessing_ms`,t.latencyMs?.preprocessing),
|
|
1448
|
+
z(a,`${q}latency.provider_ms`,t.latencyMs?.provider);let u=e?.langfuse?.metadata||e?.datadog?.metadata?cs(t,n):void 0;if(u&&e?.langfuse?.metadata)for(let[l,d]of Object.entries(u))a[`langfuse.observati\
|
|
1449
|
+
on.metadata.${l}`]=typeof d=="number"?ss(d):d;if(e?.langfuse?.cost&&n==="USD"&&$e(r.basis)&&Number.isFinite(r.actual)&&(a["langfuse.observation.cost_details"]=JSON.stringify({total:r.actual})),u&&e?.datadog?.
|
|
1450
|
+
metadata){let l={};for(let[d,m]of Object.entries(u))l[d.replace(/^bivelio_/,"")]=m;a["_dd.ml_obs.metadata"]=JSON.stringify({bivelio:l});}return a}var zm=2,qm=2,Vm="@bivelio/savings-layer";function Um(t,e,n){try{if(t.isRecording?.()===!1)return;let r=Hr(e,n);n?.genAi&&Object.assign(r,us(e)),t.setAttributes(r);}catch{}}function ls(t){return typeof t==
|
|
1451
|
+
"function"}function Hm(t){let e=t;if(e&&ls(e.startActiveSpan))return e;if(e&&ls(e.getTracer)){let n=e.getTracer(Vm,De);if(n&&ls(n.startActiveSpan))return n}throw new TypeError("[bvsala] instrumentSavi\
|
|
1452
|
+
ngsLayer: `tracer` must be an OpenTelemetry Tracer, a TracerProvider or the `trace` object of the OpenTelemetry API")}function Wm(t){let e=t?.name;return typeof e=="string"&&/^[A-Za-z_$][\w$.-]{0,127}$/.
|
|
1453
|
+
test(e)?e:"_OTHER"}function Jm(t,e,n){let r={[ce.operacion]:"chat"},o=n??il(t.model);typeof o=="string"&&o!==""&&(r[ce.proveedor]=o),r[ce.modeloPedido]=pt(t.model);let i=(a,c)=>{typeof c=="number"&&Number.
|
|
1454
|
+
isFinite(c)&&(r[a]=c);};i(ce.temperatura,t.temperature),i(ce.semilla,t.seed),i(ce.maxTokens,t.response?.maxOutputTokens),e&&(r[ce.stream]=true);let s=t.context?.sessionId;return typeof s=="string"&&s!==""&&
|
|
1455
|
+
(r[ce.conversacion]=s),r}function ll(t,e,n){try{if(t.isRecording?.()!==!1){let r=e.report,o={...us(r),...Hr(r,n)};typeof e.finishReason=="string"&&e.finishReason!==""&&(o[ce.motivosDeFin]=[e.finishReason]);
|
|
1456
|
+
let i=r.streaming;i?.delivery==="live"&&typeof i.firstEventMs=="number"&&Number.isFinite(i.firstEventMs)&&(o[ce.primerTrozo]=i.firstEventMs/1e3),t.setAttributes(o);}}catch{}finally{try{t.end();}catch{}}}
|
|
1457
|
+
function ds(t,e){try{if(t.isRecording?.()!==!1){let n={[al]:Wm(e)};e instanceof ye&&(n[cl]=e.requestSent),t.setAttributes(n),t.setStatus?.({code:qm});}}catch{}finally{try{t.end();}catch{}}}function Km(t,e){
|
|
1458
|
+
let n=Hm(e?.tracer);if(e.currency!==void 0&&!/^[A-Z]{3}$/.test(e.currency))throw new TypeError(`[bvsala] instrumentSavingsLayer: currency must be an ISO 4217 code such as "USD" (got "${e.currency}")`);
|
|
1459
|
+
let r={...e.currency!==void 0?{currency:e.currency}:{},...e.langfuse?{langfuse:e.langfuse}:{},...e.datadog?{datadog:e.datadog}:{}},o=e.providerName;function i(s,a,c,u){let l,d,m=false,f;try{f=Jm(s,a,o);}catch{
|
|
1460
|
+
f=void 0;}let h=`chat ${Gm(s)}`;try{n.startActiveSpan(h,{kind:zm,...f?{attributes:f}:{}},g=>{if(l)return l.valor;if(d)throw d.error;if(m){try{g.end();}catch{}return}let p;try{p=c();}catch(y){throw d={error:y},
|
|
1461
|
+
ds(g,y),y}try{l={valor:u(g,p)};}catch{l={valor:p};try{g.end();}catch{}}return l.valor});}catch{}if(d)throw d.error;return l?l.valor:(m=true,c())}return {batches:t.batches,generate(s){return i(s,false,()=>t.generate(
|
|
1462
|
+
s),(a,c)=>c.then(u=>(ll(a,u,r),u),u=>{throw ds(a,u),u}))},generateStream(s,a){return i(s,true,()=>t.generateStream(s,a),(c,u)=>(u.result.then(l=>ll(c,l,r),l=>ds(c,l)),u))},close(){t.close();}}}function Gm(t){
|
|
1463
|
+
try{return typeof t.model=="string"?pt(t.model):""}catch{return ""}}function Ym(t,e){let n=e?.currency??"USD",r={model:pt(t.model),metadata:cs(t,n)};if($e(t.cost.basis)){let{actualInput:o,actualOutput:i,providerCachedInput:s}=t.tokens,a={input:Math.max(0,o-(s??0)),output:i};
|
|
1464
|
+
s!==void 0&&(a.cache_read_input_tokens=s),r.usageDetails=a,e?.includeCost&&n==="USD"&&Number.isFinite(t.cost.actual)&&(r.costDetails={total:t.cost.actual});}return r}var dl=["measured","reference","estimated","unmeasured"],ps=36e5,pl=24*ps;function Wr(t,e){if(t===void 0)return "day";if(t==="hour"||t==="day")return t;throw new TypeError(`[bvsala] ${e}: granularity m\
|
|
1465
|
+
ust be "hour" or "day"`)}function Jr(t,e){if(t===void 0)return "USD";if(typeof t=="string"&&/^[A-Z]{3}$/.test(t))return t;throw new TypeError(`[bvsala] ${e}: currency must be an ISO 4217 code such as "\
|
|
1466
|
+
USD"`)}function Zm(t,e){let n=t.at,r=Number.NaN;if(n instanceof Date?r=n.getTime():typeof n=="number"?r=n:typeof n=="string"&&n.trim()!==""&&(r=Date.parse(n)),!Number.isFinite(r))throw new TypeError(`\
|
|
1467
|
+
[bvsala] ${e}: invalid "at" for request ${String(t.report?.requestId)}: expected an ISO 8601 string, epoch milliseconds or a valid Date`);return r}function Qm(t,e){let n=e==="hour"?ps:pl;return Math.floor(
|
|
1468
|
+
t/n)*n}function Xm(t,e){return t+(e==="hour"?ps:pl)}function nt(t){return new Date(t).toISOString().replace(/\.\d{3}Z$/,"Z")}function ge(t,e,n,r){if(typeof t=="number"&&Number.isFinite(t))return t;throw new TypeError(
|
|
1469
|
+
`[bvsala] ${r}: report ${n} has no finite number in ${e}`)}function Kr(t,e,n,r){let o=new Map;for(let s of t){if(!s||typeof s!="object"||!s.report||typeof s.report!="object")throw new TypeError(`[bvsa\
|
|
1470
|
+
la] ${n}: every record must be { at, report }`);let a=s.report,c=a.cost?.basis;if(c==="shadow")continue;if(!dl.includes(c))throw new TypeError(`[bvsala] ${n}: report ${String(a.requestId)} has an unkn\
|
|
1471
|
+
own cost basis`);let u=c,l=Qm(Zm(s,n),e),{clave:d,extra:m}=r(s,l),f=JSON.stringify([l,a.model,u,d]),h=o.get(f);h||(h={inicio:l,fin:Xm(l,e),modelo:a.model,basis:u,clave:d,extra:m,peticiones:0,llamadas:0,
|
|
1179
1472
|
evitadas:0,baseline:0,actual:0,ahorro:0,suelo:void 0,tokens:{baselineInput:0,actualInput:0,eliminatedInput:0,compressedInput:0,providerCachedInput:void 0,baselineOutput:0,actualOutput:0,eliminatedOutput:0}},
|
|
1180
|
-
o.set(
|
|
1181
|
-
|
|
1182
|
-
compressedInput+=
|
|
1183
|
-
Output",
|
|
1184
|
-
"tokens.providerCachedInput",
|
|
1185
|
-
void 0&&(h.suelo=(h.suelo??0)+
|
|
1186
|
-
s.modelo>a.modelo?1:0)||i(s.basis)-i(a.basis)||(s.clave<a.clave?-1:s.clave>a.clave?1:0))}function
|
|
1187
|
-
measured:t.basis==="measured"?n:null,reference:t.basis==="reference"?n:null,estimated:t.basis==="estimated"?n:null,suelo:e&&t.suelo!==void 0?
|
|
1188
|
-
keys(t).sort().map(e=>[e,t[e]]))}function
|
|
1189
|
-
o,i]of Object.entries(t)){if(typeof i!="string")throw new TypeError(`[bvsala] ${n}: ${e} value for "${o}" must be a string`);r[o]=i;}return r}var
|
|
1473
|
+
o.set(f,h));let g=String(a.requestId);h.peticiones+=1,h.llamadas+=ge(a.calls?.actualLlm,"calls.actualLlm",g,n),h.evitadas+=ge(a.calls?.avoidedLlm,"calls.avoidedLlm",g,n);let p=a.tokens;if(h.tokens.baselineInput+=
|
|
1474
|
+
ge(p?.baselineInput,"tokens.baselineInput",g,n),h.tokens.actualInput+=ge(p?.actualInput,"tokens.actualInput",g,n),h.tokens.eliminatedInput+=ge(p?.eliminatedInput,"tokens.eliminatedInput",g,n),h.tokens.
|
|
1475
|
+
compressedInput+=ge(p?.compressedInput,"tokens.compressedInput",g,n),h.tokens.baselineOutput+=ge(p?.baselineOutput,"tokens.baselineOutput",g,n),h.tokens.actualOutput+=ge(p?.actualOutput,"tokens.actual\
|
|
1476
|
+
Output",g,n),h.tokens.eliminatedOutput+=ge(p?.eliminatedOutput,"tokens.eliminatedOutput",g,n),p.providerCachedInput!==void 0&&(h.tokens.providerCachedInput=(h.tokens.providerCachedInput??0)+ge(p.providerCachedInput,
|
|
1477
|
+
"tokens.providerCachedInput",g,n)),$e(u)){let y=ge(a.cost.baselineEstimate,"cost.baselineEstimate",g,n),b=ge(a.cost.actual,"cost.actual",g,n);h.baseline+=y,h.actual+=b,h.ahorro+=y-b,a.cost.eliminatedInputFloorCost!==
|
|
1478
|
+
void 0&&(h.suelo=(h.suelo??0)+ge(a.cost.eliminatedInputFloorCost,"cost.eliminatedInputFloorCost",g,n));}}let i=s=>dl.indexOf(s);return [...o.values()].sort((s,a)=>s.inicio-a.inicio||(s.modelo<a.modelo?-1:
|
|
1479
|
+
s.modelo>a.modelo?1:0)||i(s.basis)-i(a.basis)||(s.clave<a.clave?-1:s.clave>a.clave?1:0))}function Gr(t){let e=$e(t.basis),n=Ft(t.ahorro);return {baseline:e?Ft(t.baseline):null,actual:e?Ft(t.actual):null,
|
|
1480
|
+
measured:t.basis==="measured"?n:null,reference:t.basis==="reference"?n:null,estimated:t.basis==="estimated"?n:null,suelo:e&&t.suelo!==void 0?Ft(t.suelo):null}}function Yr(t){return JSON.stringify(Object.
|
|
1481
|
+
keys(t).sort().map(e=>[e,t[e]]))}function Zr(t,e,n){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new TypeError(`[bvsala] ${n}: ${e} must return an object of strings`);let r={};for(let[
|
|
1482
|
+
o,i]of Object.entries(t)){if(typeof i!="string")throw new TypeError(`[bvsala] ${n}: ${e} value for "${o}" must be a string`);r[o]=i;}return r}var eh=new Set(["periodStart","periodEnd","date","model","basis","currency","requests","providerCalls","avoidedCalls","baselineCost","actualCost","measuredSavings","referenceSavings","estimatedSavings",
|
|
1190
1483
|
"eliminatedInputFloorCost","baselineInputTokens","actualInputTokens","eliminatedInputTokens","compressedInputTokens","providerCachedInputTokens","baselineOutputTokens","actualOutputTokens","eliminated\
|
|
1191
|
-
OutputTokens","dimensions"]),
|
|
1192
|
-
keys(a))if(
|
|
1193
|
-
s.fin),date:
|
|
1484
|
+
OutputTokens","dimensions"]),Sn="toSavingsSeries";function th(t,e){let n=Wr(e?.granularity,Sn),r=Jr(e?.currency,Sn),o=e?.dimensions;return Kr(t,n,Sn,s=>{let a=o?Zr(o(s),"dimensions",Sn):{};for(let c of Object.
|
|
1485
|
+
keys(a))if(eh.has(c))throw new TypeError(`[bvsala] ${Sn}: dimension "${c}" repeats a column of the series`);return {clave:Yr(a),extra:a}}).map(s=>{let a=Gr(s),c=nt(s.inicio);return {periodStart:c,periodEnd:nt(
|
|
1486
|
+
s.fin),date:c.slice(0,10),model:s.modelo,basis:s.basis,currency:r,requests:s.peticiones,providerCalls:s.llamadas,avoidedCalls:s.evitadas,baselineCost:a.baseline,actualCost:a.actual,measuredSavings:a.measured,
|
|
1194
1487
|
referenceSavings:a.reference,estimatedSavings:a.estimated,eliminatedInputFloorCost:a.suelo,baselineInputTokens:s.tokens.baselineInput,actualInputTokens:s.tokens.actualInput,eliminatedInputTokens:s.tokens.
|
|
1195
1488
|
eliminatedInput,compressedInputTokens:s.tokens.compressedInput,providerCachedInputTokens:s.tokens.providerCachedInput??null,baselineOutputTokens:s.tokens.baselineOutput,actualOutputTokens:s.tokens.actualOutput,
|
|
1196
|
-
eliminatedOutputTokens:s.tokens.eliminatedOutput,dimensions:Object.freeze({...s.extra})}})}var
|
|
1197
|
-
`[bvsala] ${
|
|
1489
|
+
eliminatedOutputTokens:s.tokens.eliminatedOutput,dimensions:Object.freeze({...s.extra})}})}var be="toFocusRows",nh="BV-SALA savings ledger",fl="bivelio/";function ft(t){return typeof t=="string"&&t.trim()!==""}function fs(t,e,n,r){let o=typeof t=="function"?t(n):t??e;if(ft(o))return o;throw new TypeError(
|
|
1490
|
+
`[bvsala] ${be}: cannot determine the FOCUS ${r} for model "${n}". FOCUS allows no placeholder there: pass it in the options.`)}function rh(t,e,n){if(!n){let s=new Date(t);return {start:Date.UTC(s.getUTCFullYear(),
|
|
1198
1491
|
s.getUTCMonth(),1),end:Date.UTC(s.getUTCFullYear(),s.getUTCMonth()+1,1)}}let r=n(new Date(t)),o=r?.start instanceof Date?r.start.getTime():Number.NaN,i=r?.end instanceof Date?r.end.getTime():Number.NaN;
|
|
1199
|
-
if(!Number.isFinite(o)||!Number.isFinite(i)||o>=i)throw new TypeError(`[bvsala] ${
|
|
1200
|
-
llingPeriod must contain the charge period it is given`);return {start:o,end:i}}function
|
|
1201
|
-
red`);let n=
|
|
1202
|
-
Id must be a non-empty string or a function`);let
|
|
1203
|
-
tion"?o(l):o;if(!
|
|
1204
|
-
(!
|
|
1205
|
-
startsWith(
|
|
1206
|
-
[
|
|
1207
|
-
|
|
1208
|
-
EffectiveCost:0,ListCost:0,ContractedCost:0,BillingCurrency:r,BillingAccountId:
|
|
1209
|
-
ChargePeriodEnd:
|
|
1210
|
-
Usage-Based",InvoiceIssuerName:
|
|
1211
|
-
SubAccountId:
|
|
1492
|
+
if(!Number.isFinite(o)||!Number.isFinite(i)||o>=i)throw new TypeError(`[bvsala] ${be}: billingPeriod must return valid Dates with start before end`);if(t<o||e>i)throw new TypeError(`[bvsala] ${be}: bi\
|
|
1493
|
+
llingPeriod must contain the charge period it is given`);return {start:o,end:i}}function oh(t,e){if(!e||typeof e!="object")throw new TypeError(`[bvsala] ${be}: options with a billingAccountId are requi\
|
|
1494
|
+
red`);let n=Wr(e.granularity,be),r=Jr(e.currency,be),{billingAccountId:o,billingAccountName:i,subAccount:s,tags:a}=e;if(typeof o!="function"&&!ft(o))throw new TypeError(`[bvsala] ${be}: billingAccount\
|
|
1495
|
+
Id must be a non-empty string or a function`);let c=e.serviceName??nh;if(!ft(c))throw new TypeError(`[bvsala] ${be}: serviceName must be a non-empty string`);return Kr(t,n,be,l=>{let d=typeof o=="func\
|
|
1496
|
+
tion"?o(l):o;if(!ft(d))throw new TypeError(`[bvsala] ${be}: billingAccountId returned no id for request ${String(l.report.requestId)}`);let m=typeof i=="function"?i(l):i,f=s?s(l):void 0;if(f!==void 0&&
|
|
1497
|
+
(!ft(f?.id)||!ft(f?.name)))throw new TypeError(`[bvsala] ${be}: subAccount must return { id, name } as non-empty strings, or undefined`);let h=Zr(a?a(l):void 0,"tags",be);for(let p of Object.keys(h))if(p.
|
|
1498
|
+
startsWith(fl))throw new TypeError(`[bvsala] ${be}: tag "${p}" uses the reserved "${fl}" prefix`);let g={id:d,nombre:ft(m)?m:null,subId:f?f.id:null,subNombre:f?f.name:null,tags:h};return {clave:JSON.stringify(
|
|
1499
|
+
[g.id,g.nombre,g.subId,g.subNombre,Yr(h)]),extra:g}}).map(l=>{let d=l.modelo,m=fs(e.serviceProviderName,sl(d),d,"ServiceProviderName"),f=fs(e.invoiceIssuerName,m,d,"InvoiceIssuerName"),h=fs(e.hostProviderName,
|
|
1500
|
+
m,d,"HostProviderName"),g=rh(l.inicio,l.fin,e.billingPeriod),p=Gr(l),y=l.extra,b={"bivelio/basis":l.basis,"bivelio/model":d};for(let v of Object.keys(y.tags).sort())b[v]=y.tags[v];return {BilledCost:0,
|
|
1501
|
+
EffectiveCost:0,ListCost:0,ContractedCost:0,BillingCurrency:r,BillingAccountId:y.id,BillingAccountName:y.nombre,BillingPeriodStart:nt(g.start),BillingPeriodEnd:nt(g.end),ChargePeriodStart:nt(l.inicio),
|
|
1502
|
+
ChargePeriodEnd:nt(l.fin),ChargeCategory:"Adjustment",ChargeClass:null,ChargeDescription:`BV-SALA savings ledger for ${d} (basis: ${l.basis}). Not a charge: cost columns are 0 by design.`,ChargeFrequency:"\
|
|
1503
|
+
Usage-Based",InvoiceIssuerName:f,ServiceProviderName:m,HostProviderName:h,ServiceName:c,ServiceCategory:"AI and Machine Learning",ServiceSubcategory:"Generative AI",PricingQuantity:null,PricingUnit:null,
|
|
1504
|
+
SubAccountId:y.subId,SubAccountName:y.subNombre,Tags:JSON.stringify(b),x_BiVelioBasis:l.basis,x_BiVelioModelId:d,x_BiVelioRequestCount:l.peticiones,x_BiVelioProviderCallCount:l.llamadas,x_BiVelioAvoidedCallCount:l.
|
|
1212
1505
|
evitadas,x_BiVelioBaselineCost:p.baseline,x_BiVelioActualCost:p.actual,x_BiVelioMeasuredSavings:p.measured,x_BiVelioReferenceSavings:p.reference,x_BiVelioEstimatedSavings:p.estimated,x_BiVelioEliminatedInputFloorCost:p.
|
|
1213
1506
|
suelo,x_BiVelioBaselineInputTokens:l.tokens.baselineInput,x_BiVelioActualInputTokens:l.tokens.actualInput,x_BiVelioEliminatedInputTokens:l.tokens.eliminatedInput,x_BiVelioCompressedInputTokens:l.tokens.
|
|
1214
1507
|
compressedInput,x_BiVelioProviderCachedInputTokens:l.tokens.providerCachedInput??null,x_BiVelioBaselineOutputTokens:l.tokens.baselineOutput,x_BiVelioActualOutputTokens:l.tokens.actualOutput,x_BiVelioEliminatedOutputTokens:l.
|
|
@@ -1220,4 +1513,4 @@ tokens.eliminatedOutput}})}/*! Bundled license information:
|
|
|
1220
1513
|
@noble/curves/abstract/edwards.js:
|
|
1221
1514
|
@noble/curves/ed25519.js:
|
|
1222
1515
|
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
1223
|
-
*/export{
|
|
1516
|
+
*/export{$a as AnthropicProvider,De as BV_SALA_VERSION,Pr as BatchSubmitError,Wt as CATALOGO,Ao as COMPACTION_TRANSFORMS,wd as COMPACT_ROWS_INSTRUCTION,Hc as DEFAULT_COST_MODEL,$m as DEFAULT_MAX_STALENESS_SECONDS,_d as DEFAULT_MIN_SAVED_CHARS,Nc as EMBEDDED_PUBLIC_KEY,co as ExactTokenizer,$n as ExecutionRouter,Vn as FormatSelector,io as HeuristicEstimator,An as InMemoryExactCache,Bs as InMemorySemanticCache,To as InMemoryToolSetFreezer,Je as LicenseError,Sh as MODELOS_POR_CODIFICACION,In as MODELS_BY_ENCODING,Mo as MockProvider,_a as OpenAICompatibleProvider,no as PRECIOS_AL_DIA,lh as QUALITY_STATUSES,Cs as REFERENCE_MAX_AGE_MS,Rs as REFERENCE_MESSAGE_ALLOWANCE,Es as REFERENCE_OUTPUT_SHARE,ko as ResolverRegistry,Sr as RevocationPoller,At as RevocationSnapshot,kt as SavingsLedger,Un as SchemaRegistry,On as Singleflight,ye as StreamAbortedError,so as TokenizerRegistry,Bn as ToolSelector,sn as TraceCollector,Ns as UMBRAL_LOCAL,fn as UsageEmitter,dd as adaptiveK,Xl as arithmeticResolver,ho as buildExactKey,_s as buildInflightKey,Jh as calibrateSemanticFloor,mo as canonicalize,ea as compactRowsSerializer,ua as compactToolOutput,ia as compresionFiel,Jp as computeNextDelay,Jl as cosine,Sd as createCompactRowsSerializer,Fs as createDefaultResolvers,ph as createHandoff,cg as createMockProvider,gk as createSavingsLayer,na as csvSerializer,Ys as decodeCompactRows,ld as dedupe,ao as defaultTokenizerRegistry,Ri as deriveSeatId,Ci as deriveStatus,Ei as detectCi,js as embebedorLocal,k0 as emptyState,yd as encodeCompactRows,nd as evalArithmetic,_n as evaluatePolicy,Ks as executeRetrievalPlan,Vc as gateFromKey,yt as heuristicEstimator,Km as instrumentSavingsLayer,qp as isKeyset,We as isStrictCompatible,Gs as jsonCompactSerializer,Zl as keyTokensMatch,Ti as licenseKeyShape,wr as liveGateFromKey,x0 as mergeDelta,fo as modelFamilyOf,yo as multisetEqual,Qt as negationCount,X0 as noopCompressor,Dt as normalizeLicenseKey,Dn as normalizeText,Yt as numericTokens,En as precioDeLista,w0 as projectContext,H0 as providerNativeBackend,Vo as quitarPrefijoDeProveedor,Jt as randomId,Um as recordSavingsOnSpan,uo as registerExactTokenizer,Th as registrarTokenizadorExacto,fd as renderState,oa as resolveConstraintBackend,Wc as resolveDependencies,Lb as resolveLicense,Ls as sameAnswer,Hr as savingsSpanAttributes,ne as sha256,_o as shouldCompress,ve as stableStringify,Fm as toCsv,oh as toFocusRows,Ym as toLangfuseGeneration,th as toSavingsSeries,qn as uniformColumns,le as validateAgainstSchema,Wl as vectorLocal,Pi as verifyCompactSignature,_t as verifyLicenseToken,qc as verifyRevocationList,Q0 as withProtectedSpans,Zt as words};
|